/* Football Manager Retro 4.1 – Drag-and-drop tactical board */
(function(){
  'use strict';
  const FORMATION_LAYOUTS={
    '4-4-2':[
      {pos:'TW',x:50,y:89},{pos:'LV',x:14,y:70},{pos:'IV',x:38,y:74},{pos:'IV',x:62,y:74},{pos:'RV',x:86,y:70},
      {pos:'LM',x:14,y:45},{pos:'ZM',x:38,y:50},{pos:'ZM',x:62,y:50},{pos:'RM',x:86,y:45},{pos:'ST',x:36,y:20},{pos:'ST',x:64,y:20}
    ],
    '5-3-2':[
      {pos:'TW',x:50,y:89},{pos:'LV',x:10,y:66},{pos:'IV',x:30,y:74},{pos:'IV',x:50,y:76},{pos:'IV',x:70,y:74},{pos:'RV',x:90,y:66},
      {pos:'ZM',x:25,y:45},{pos:'ZM',x:50,y:50},{pos:'ZM',x:75,y:45},{pos:'ST',x:36,y:20},{pos:'ST',x:64,y:20}
    ],
    '4-3-3':[
      {pos:'TW',x:50,y:89},{pos:'LV',x:14,y:70},{pos:'IV',x:38,y:74},{pos:'IV',x:62,y:74},{pos:'RV',x:86,y:70},
      {pos:'ZM',x:24,y:49},{pos:'ZM',x:50,y:55},{pos:'ZM',x:76,y:49},{pos:'LA',x:18,y:20},{pos:'ST',x:50,y:15},{pos:'RA',x:82,y:20}
    ]
  };
  let selectedPlayerId=null;
  const positionGroup=pos=>pos==='TW'?'TW':['RV','IV','LV','LIB'].includes(pos)?'ABW':['DM','ZM','OM','LM','RM'].includes(pos)?'MIT':'ST';
  function compatible(player,slot){
    if(!player)return false;
    const pg=positionGroup(player.position),sg=positionGroup(slot);
    return pg===sg || (pg==='MIT'&&sg==='ST'&&['RA','LA','OM'].includes(player.position)) || (pg==='ST'&&sg==='MIT'&&['RA','LA'].includes(player.position));
  }
  function statusText(p){
    if((p.injuryGames||0)>0)return `Verletzt (${p.injuryGames})`;
    if((p.suspensionGames||0)>0)return `Gesperrt (${p.suspensionGames})`;
    return `${p.fitness}% fit`;
  }
  function isUnavailable(p){return (p.injuryGames||0)>0||(p.suspensionGames||0)>0;}
  function assignedIndex(id){return (state.selectedXI||[]).findIndex(x=>x===id);}
  function ensureFormationLineup(){
    if(typeof ensureGameSystems==='function')ensureGameSystems();
    const slots=FORMATION_LAYOUTS[state.formation]||FORMATION_LAYOUTS['4-4-2'];
    state.selectedXI=Array.isArray(state.selectedXI)?state.selectedXI.slice(0,slots.length):[];
    while(state.selectedXI.length<slots.length)state.selectedXI.push(null);
  }
  function assignPlayer(playerId,index){
    const club=getUserClub(),player=club.squad.find(p=>p.id===playerId),slots=FORMATION_LAYOUTS[state.formation];
    if(!player||!slots[index]||isUnavailable(player))return;
    const oldIndex=assignedIndex(playerId),displaced=state.selectedXI[index]||null;
    if(oldIndex===index){selectedPlayerId=null;return;}
    if(oldIndex>=0)state.selectedXI[oldIndex]=displaced;
    else state.selectedXI[index]=playerId;
    if(oldIndex>=0)state.selectedXI[index]=playerId;
    selectedPlayerId=null;
    if(typeof save==='function')save();
    if(typeof render==='function')render();
  }
  function clearSlot(index){
    state.selectedXI[index]=null;selectedPlayerId=null;if(typeof save==='function')save();if(typeof render==='function')render();
  }
  function playerCard(p){
    const used=assignedIndex(p.id)>=0,unavailable=isUnavailable(p),selected=selectedPlayerId===p.id;
    return `<button type="button" class="tactical-player ${used?'is-fielded':''} ${unavailable?'is-unavailable':''} ${selected?'is-selected':''}" draggable="${unavailable?'false':'true'}" data-tactical-player="${p.id}" ${unavailable?'disabled':''}>
      <span class="tactical-player-pos">${p.position}</span><span class="tactical-player-main"><b>${esc(p.name)}</b><small>Stärke ${p.rating} · ${statusText(p)}</small></span>${used?'<span class="fielded-check">✓</span>':''}
    </button>`;
  }
  function tacticalLineup(){
    if(typeof ensureAllPlayerDNA==='function')ensureAllPlayerDNA();ensureFormationLineup();
    const club=getUserClub(),layout=FORMATION_LAYOUTS[state.formation]||FORMATION_LAYOUTS['4-4-2'];
    const squad=[...club.squad].sort((a,b)=>{const uA=isUnavailable(a)?1:0,uB=isUnavailable(b)?1:0;return uA-uB||(((typeof POSITION_ORDER!=='undefined'?POSITION_ORDER[a.position]:undefined)??99)-((typeof POSITION_ORDER!=='undefined'?POSITION_ORDER[b.position]:undefined)??99))||b.rating-a.rating;});
    return `<div class="card tactical-page">
      <div class="tactical-header"><div><h2>Aufstellung</h2><p class="muted">Spieler ziehen oder am iPad zuerst den Spieler und danach die Position antippen.</p></div>
      <label class="formation-control">Formation<select id="formationSelect">${Object.keys(FORMATION_LAYOUTS).map(f=>`<option value="${f}" ${state.formation===f?'selected':''}>${f}</option>`).join('')}</select></label></div>
      <div class="tactical-workspace">
        <section class="pitch-panel" aria-label="Taktik-Spielfeld"><div class="football-pitch">
          <div class="pitch-markings"><span class="halfway"></span><span class="center-circle"></span><span class="box box-top"></span><span class="box box-bottom"></span></div>
          ${layout.map((slot,i)=>{const p=club.squad.find(x=>x.id===state.selectedXI[i]);return `<button type="button" class="pitch-slot ${p?'occupied':''} ${selectedPlayerId?'ready-to-drop':''}" style="left:${slot.x}%;top:${slot.y}%" data-pitch-slot="${i}" data-slot-position="${slot.pos}" draggable="${p?'true':'false'}">
            <span class="slot-position">${slot.pos}</span>${p?`<b>${esc(p.name)}</b><small>${p.rating} · ${p.fitness}%</small>`:'<b>Spieler wählen</b>'}
          </button>`}).join('')}
        </div><p class="tactical-hint">Doppeltippen auf ein Positionsfeld entfernt den Spieler. Ein Spieler auf einer ungewohnten Position erhält im Spiel einen Leistungsabzug.</p></section>
        <section class="squad-panel"><div class="squad-panel-head"><h3>Kader</h3><span>${state.selectedXI.filter(Boolean).length}/11 aufgestellt</span></div><div class="tactical-squad-list">${squad.map(playerCard).join('')}</div></section>
      </div>
    </div>`;
  }
  function bindBoard(){
    const formation=document.querySelector('#formationSelect');
    if(formation)formation.onchange=e=>{state.formation=e.target.value;selectedPlayerId=null;if(typeof normalizeLineup==='function')normalizeLineup();save();render();};
    document.querySelectorAll('[data-tactical-player]').forEach(el=>{
      el.addEventListener('click',()=>{selectedPlayerId=selectedPlayerId===el.dataset.tacticalPlayer?null:el.dataset.tacticalPlayer;render();});
      el.addEventListener('dragstart',e=>{e.dataTransfer.setData('text/player-id',el.dataset.tacticalPlayer);e.dataTransfer.effectAllowed='move';});
    });
    document.querySelectorAll('[data-pitch-slot]').forEach(el=>{
      const index=Number(el.dataset.pitchSlot);
      el.addEventListener('dragover',e=>{e.preventDefault();e.dataTransfer.dropEffect='move';el.classList.add('drag-over');});
      el.addEventListener('dragleave',()=>el.classList.remove('drag-over'));
      el.addEventListener('drop',e=>{e.preventDefault();el.classList.remove('drag-over');const id=e.dataTransfer.getData('text/player-id');if(id)assignPlayer(id,index);});
      el.addEventListener('dragstart',e=>{const id=state.selectedXI[index];if(id)e.dataTransfer.setData('text/player-id',id);});
      el.addEventListener('click',()=>{if(selectedPlayerId)assignPlayer(selectedPlayerId,index);});
      el.addEventListener('dblclick',()=>clearSlot(index));
    });
  }
  if(typeof lineup==='function')lineup=tacticalLineup;
  if(typeof bindDynamic==='function'){
    const oldBind=bindDynamic;bindDynamic=function(){oldBind();if(view==='lineup')bindBoard();};
  }
  if(typeof render==='function'){
    const oldRender=render;render=function(){oldRender();const label=document.querySelector('#seasonLabel');if(label&&state)label.textContent=label.textContent.replace(/Version\s+[\d.]+(?:\s+·\s+Player DNA)?/,'Version 4.1 · Taktiktafel');};
  }
})();
