import { useState, useEffect } from 'react'
import './App.css'

function Marker({ avatar, name, top, left }) {
    const _top = top == null ? "50%" : top + '%'
    const _left = left == null ? "50%" : left + '%'
    const props = {
        top: _top,
        left: _left,
    }
    return (
        <div className="marker" style={props}>
            <img className="markerimg" src={avatar} alt="{name} avatar"/>
            <div className="markertip">
                {name}
            </div>
        </div>
    )
}

function Room({ id, name, description, value, x, y, w, h, children }) {
    const props = {
        left: x + '%',
        top: y + '%',
        width: w + '%',
        height: h + '%',
    }
    return (
        <div className="room" style={props}>
            {children}
            <div className="roomtip">
                <span className="roomname">[#{id}] {name}</span>
                <br/>{description}
                <br/>Unlock price: {value} points
            </div>
        </div>
    )
}

function Map() {
    const [ rooms, setRooms ] = useState([])
    useEffect(() => {
        fetch("http://localhost:2526")
            .then(response => response.json())
            .then(data => setRooms(data))
            .catch(err => console.log("Fetch error: " + err.message))
        return () => {}
    }, [setRooms]);

    const roomsList = rooms.map(room => {
        const maxWidth = Math.ceil(Math.sqrt(room.markers.length))
        const markers = room.markers.map( (marker, index) =>
            <Marker
                key={marker.id}
                avatar={marker.avatar}
                name={marker.name}
                left={((index % maxWidth) + 0.5) / (maxWidth + 1) * 100}
                top={(Math.floor(index / maxWidth) + 0.5) / (maxWidth + 1) * 100}
            />
        )
        return (
            <Room
                id = {room.id}
                name={room.name}
                description={room.description}
                value={room.value}
                key={room.id}
                x={room.x}
                y={room.y}
                w={room.w}
                h={room.h}
            >
                {markers}
            </Room>
        )
    })

    return (
        <div className="map">
            <div>{roomsList}</div>
            <img className="mapimg" src="map.png" alt="SquadQuest map" />
        </div>
    )
}

function App() {
    return (
        <div>
            <Map />
        </div>
    )
}

export default App
