
let imageWidth = 3072;
let imageHeight = 3072;

let bounds = [[0,0],[imageHeight,imageWidth]];

let map = L.map('map',{
crs:L.CRS.Simple,
minZoom:-2,
maxZoom:2,
zoomControl:false,
scrollWheelZoom:false,
doubleClickZoom:false,
attributionControl:false
});

let currentMap = 1;
let currentLayer;
let spotMarkers = [];

let drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

let drawControl = new L.Control.Draw({
edit:{
featureGroup:drawnItems
}
});

map.addControl(drawControl);

map.on(L.Draw.Event.CREATED,function(e){
drawnItems.addLayer(e.layer);
});

function loadMap(){

currentMap=document.getElementById('mapSelector').value;

if(currentLayer){
map.removeLayer(currentLayer);
}

currentLayer=L.imageOverlay(
`maps/map${currentMap}.jpg`,
bounds
).addTo(map);

map.fitBounds(bounds);

loadSpots();
loadStrategyList();

}

map.on('click',function(e){

let nombre=prompt('Nombre del spot');
if(!nombre)return;

let tipo=prompt('Tipo');
if(!tipo)return;

let video=prompt('Link video');

let faction=document.getElementById(
'factionSelect'
).value;

fetch('api/add_spot.php',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
mapa_id:currentMap,
nombre:nombre,
tipo:tipo,
video_link:video,
faction:faction,
x:e.latlng.lng,
y:e.latlng.lat
})
}).then(()=>loadSpots());

});

function createSpotMarker(s){

let icon=L.icon({
iconUrl:`assets/icons/${s.tipo}.png`,
iconSize:[30,30]
});

let marker=L.marker([s.y,s.x],{
icon:icon
}).addTo(map);

marker.tipo=s.tipo;

marker.bindPopup(`
<div style="min-width:220px;color:white;">

<h3>${s.nombre}</h3>

<div style="margin-bottom:10px;font-weight:bold;">
${s.faction === 'Allies'
? '🇺🇸 Allies'
: '🇩🇪 Axis'}
</div>

<b>Tipo:</b> ${s.tipo}<br><br>

<a href="${s.video_link || '#'}"
target="_blank"
style="
background:#222;
padding:8px 12px;
color:white;
text-decoration:none;
border:1px solid #555;
display:inline-block;
">
🎥 Ver referencia
</a>

</div>
`);

spotMarkers.push(marker);

}

function loadSpots(){

spotMarkers.forEach(m=>{
map.removeLayer(m);
});

spotMarkers=[];

document.getElementById('spotList').innerHTML='';

fetch(`api/get_spots.php?mapa_id=${currentMap}`)
.then(r=>r.json())
.then(data=>{

data.forEach(s=>{

createSpotMarker(s);

let card=document.createElement('div');

card.className='spot-card';

card.innerHTML=`
<b>${s.nombre}</b><br>
${s.tipo}<br>
${s.faction}
`;

document.getElementById('spotList').appendChild(card);

});

});

}

function filterSpots(){

let filtro=document.getElementById('filter').value;

spotMarkers.forEach(m=>{

if(filtro==='all'){
map.addLayer(m);
}else{

if(m.tipo===filtro){
map.addLayer(m);
}else{
map.removeLayer(m);
}

}

});

}

let gridLayer=L.layerGroup().addTo(map);
let gridEnabled=false;

function toggleGrid(){

gridEnabled=!gridEnabled;

gridLayer.clearLayers();

if(!gridEnabled)return;

let letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ';

for(let y=0;y<10;y++){

for(let x=0;x<10;x++){

let label=letters[y]+(x+1);

let lat=(y*imageHeight/10)+50;
let lng=(x*imageWidth/10)+100;

L.marker([lat,lng],{
icon:L.divIcon({
className:'grid-label',
html:label
})
}).addTo(gridLayer);

}

}

}

function saveStrategy(){

let geo=drawnItems.toGeoJSON();

fetch('api/save_strategy.php',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
mapa_id:currentMap,
nombre:document.getElementById('strategyName').value,
datos:JSON.stringify(geo)
})
});

alert('Estrategia guardada');

loadStrategyList();

}

function loadStrategyList(){

fetch(
`api/get_strategies.php?mapa_id=${currentMap}`
)

.then(r=>r.json())

.then(data=>{

let select=document.getElementById(
'strategyList'
);

select.innerHTML='';

data.forEach(strategy=>{

let option=document.createElement(
'option'
);

option.value=strategy.id;

option.innerHTML=strategy.nombre;

select.appendChild(option);

});

});

}

function loadSelectedStrategy(){

let id=document.getElementById(
'strategyList'
).value;

fetch(`api/load_strategy.php?id=${id}`)

.then(r=>r.json())

.then(data=>{

drawnItems.clearLayers();

if(!data.datos)return;

let geo=JSON.parse(data.datos);

L.geoJSON(geo).eachLayer(layer=>{

drawnItems.addLayer(layer);

});

});

}

loadMap();
