/* ===== Top bar (runes + rejuvenator) + App ===== */

function fmtClock(sec){
  const m=Math.floor(sec/60), s=Math.floor(sec%60);
  return m+':'+String(s).padStart(2,'0');
}
function heroImg(hero){ return (window.RD.HEROES[hero]||{}).icon; }

function UrnIcon(){
  return (
    <svg width="13" height="13" viewBox="0 0 14 14" fill="none">
      <path d="M3 4 h8 l-1.2 7 a3 3 0 0 1 -5.6 0 Z" fill="currentColor"/>
      <rect x="2.4" y="2.4" width="9.2" height="2.2" rx="1" fill="currentColor"/>
    </svg>
  );
}

function RuneBox({side, rune}){
  let cls=rune.state, body;
  if(rune.state==='active'){
    cls+=' '+rune.team;
    body=(<>
      <div className="rune-mini"><img src={heroImg(rune.hero)} alt="" draggable="false"/></div>
      <div className="rune-line">{fmtClock(rune.timer)}</div>
    </>);
  } else if(rune.state==='available'){
    body=(<>
      <div className="rune-glyph"><div className="di"></div></div>
      <div className="rune-sub">AVAILABLE</div>
    </>);
  } else {
    body=(<>
      <div className="rune-glyph"><div className="di"></div></div>
      <div className="rune-sub">SPAWN {fmtClock(rune.timer)}</div>
    </>);
  }
  return (
    <div className={"rune-box "+cls}>
      <div className="rcap"><span className="rd"></span>RUNE · {side}</div>
      {body}
    </div>
  );
}

function TopBar({matchTime, runes, rejuv}){
  return (
    <>
      <div className="topbar">
        <div className="radar-btn"><RadarIcon/></div>
        <RuneBox side="L" rune={runes[0]}/>
        <div className="status-card">
          <div className="l1">MID BOSS DEAD</div>
          <div className="l2">REJUVENATOR ACTIVE</div>
        </div>
        <RuneBox side="R" rune={runes[1]}/>
        <div className="obj-card">
          <div className="cap">MATCH TIME</div>
          <div className="val">{fmtClock(matchTime)}</div>
        </div>
      </div>
      {rejuv.active && rejuv.heroes.length>0 && (
        <div className="rejuv-strip">
          <div className="rejuv-tag"><UrnIcon/> REJUVENATOR&nbsp;·&nbsp;<span className="t">{fmtClock(rejuv.timer)}</span></div>
          {rejuv.heroes.map((h,i)=>(
            <div key={i} className={"rejuv-port "+h.team}><img src={heroImg(h.hero)} alt="" draggable="false"/></div>
          ))}
        </div>
      )}
    </>
  );
}

/* ---- random pools for live sim ---- */
function allPool(){
  return [
    ...window.RD.ALLIES.map(p=>({hero:p.hero,team:'ally'})),
    ...window.RD.ENEMIES.map(p=>({hero:p.hero,team:'enemy'})),
  ];
}
function pickOne(){ const a=allPool(); return a[Math.floor(Math.random()*a.length)]; }
function pickTeam3(){
  const team=Math.random()<0.5?'ally':'enemy';
  const ids=(team==='ally'?window.RD.ALLIES:window.RD.ENEMIES).map(p=>p.hero);
  const out=[];
  while(out.length<3 && ids.length){ out.push({team,hero:ids.splice(Math.floor(Math.random()*ids.length),1)[0]}); }
  return out;
}
const ri=(a,b)=>a+Math.floor(Math.random()*(b-a+1));

function clone(arr){ return arr.map(p=>{ const h=(window.MAPPOS&&window.MAPPOS[p.id])||[50,50]; return {...p, x:h[0],y:h[1],hx:h[0],hy:h[1], abils:p.abils.map(a=>({...a})), its:p.its.map(i=>i?{...i}:null)}; }); }

function App(){
  const [allies,setAllies]=useState(()=>clone(window.RD.ALLIES));
  const [enemies,setEnemies]=useState(()=>clone(window.RD.ENEMIES));
  const [matchTime,setMatchTime]=useState(1458);
  const [mapSize,setMapSize]=useState(780);
  const [runes,setRunes]=useState([
    {state:'active', team:'enemy', hero:'mcginnis', timer:43},
    {state:'available', timer:21},
  ]);
  const [rejuv,setRejuv]=useState({active:true, timer:58, heroes:[
    {team:'ally',hero:'haze'},{team:'ally',hero:'seven'},{team:'ally',hero:'infernus'},
  ]});

  const [isMobile,setIsMobile]=useState(()=>window.innerWidth<=760);
  const [drawer,setDrawer]=useState(null); // 'left' | 'right' | null
  useEffect(()=>{
    const onR=()=>setIsMobile(window.innerWidth<=760);
    window.addEventListener('resize',onR); return ()=>window.removeEventListener('resize',onR);
  },[]);
  // close drawers when leaving mobile
  useEffect(()=>{ if(!isMobile) setDrawer(null); },[isMobile]);

  // square map sizing
  useEffect(()=>{
    const el=document.querySelector('.mapwrap');
    if(!el) return;
    const floor=()=>window.innerWidth<=760?170:360;
    const size=()=>setMapSize(Math.max(floor(), Math.min(el.clientWidth, el.clientHeight)-4));
    const ro=new ResizeObserver(size); ro.observe(el);
    window.addEventListener('resize',size);
    size();
    return ()=>{ ro.disconnect(); window.removeEventListener('resize',size); };
  },[]);

  // live tick
  useEffect(()=>{
    const iv=setInterval(()=>{
      setMatchTime(t=>t+1);

      // runes
      setRunes(prev=>prev.map(r=>{
        let nr={...r}; nr.timer=Math.max(0,nr.timer-1);
        if(nr.timer<=0){
          if(nr.state==='idle'){ nr.state='available'; nr.timer=ri(20,35); delete nr.hero; delete nr.team; }
          else if(nr.state==='available'){ const h=pickOne(); nr.state='active'; nr.hero=h.hero; nr.team=h.team; nr.timer=ri(35,55); }
          else { nr.state='idle'; nr.timer=ri(60,95); delete nr.hero; delete nr.team; }
        }
        return nr;
      }));

      // rejuvenator
      setRejuv(prev=>{
        let t=prev.timer-1;
        if(t<=0) return {active:true, timer:ri(55,80), heroes:pickTeam3()};
        return {...prev, timer:t};
      });

      const step=(list,setter)=>{
        setter(prev=>prev.map(p=>{
          let np={...p, abils:p.abils.map(a=>({...a})), its:p.its};
          np.abils.forEach(a=>{ if(a.cd>0) a.cd=Math.max(0,a.cd-1); });
          if(!np.alive){
            np.respawn=Math.max(0,(np.respawn||0)-1);
            if(np.respawn<=0){ np.alive=true; np.hp=100; np.x=np.hx; np.y=np.hy; }
          } else {
            if(Math.random()<0.22){
              const ready=np.abils.filter(a=>a.cd<=0);
              if(ready.length){ const a=ready[Math.floor(Math.random()*ready.length)]; a.cd=a.max; }
            }
            if(Math.random()<0.3){ np.hp=Math.max(8,Math.min(100, np.hp + (Math.random()<0.5?-1:1)*Math.round(Math.random()*6))); }
            // sample roaming movement around the lane home
            let nx=np.x + (Math.random()-0.5)*3.6 + (np.hx-np.x)*0.05;
            let ny=np.y + (Math.random()-0.5)*3.6 + (np.hy-np.y)*0.05;
            nx=Math.max(np.hx-10, Math.min(np.hx+10, nx));
            ny=Math.max(np.hy-10, Math.min(np.hy+10, ny));
            np.x=Math.max(5, Math.min(95, nx));
            np.y=Math.max(7, Math.min(93, ny));
          }
          return np;
        }));
      };
      step(allies,setAllies); step(enemies,setEnemies);
    },1000);
    return ()=>clearInterval(iv);
  },[allies,enemies]);

  return (
    <div className={"radar"+(isMobile?' mobile':'')+(drawer?(' drawer-'+drawer):'')}>
      {isMobile && (
        <div className="mbar">
          <button className={"mbtn"+(drawer==='left'?' act':'')} onClick={()=>setDrawer(d=>d==='left'?null:'left')}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 6h16M4 12h16M4 18h16"/></svg>Settings
          </button>
          <div className="mbar-mid"><span className="ld"></span>LIVE · {fmtClock(matchTime)}</div>
          <button className={"mbtn"+(drawer==='right'?' act':'')} onClick={()=>setDrawer(d=>d==='right'?null:'right')}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/></svg>Players
          </button>
        </div>
      )}
      <LeftPanel/>
      <div className="center">
        <TopBar matchTime={matchTime} runes={runes} rejuv={rejuv}/>
        <div className="mapwrap">
          <MapView size={mapSize} allies={allies} enemies={enemies}/>
        </div>
      </div>
      <RightPanel allies={allies} enemies={enemies}/>
      {isMobile && drawer && <div className="mscrim" onClick={()=>setDrawer(null)}></div>}
      {isMobile && drawer && (
        <button className="dclose" onClick={()=>setDrawer(null)}
          style={{position:'fixed',top:'12px',zIndex:76,...(drawer==='left'?{left:'calc(min(88vw,370px) - 44px)'}:{right:'12px'})}}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
      )}
    </div>
  );
}

function fitStage(){
  const s=document.getElementById('stage');
  if(!s) return;
  if(window.innerWidth<=760){ s.style.transform='none'; return; } // mobile reflow: no canvas scaling
  const k=Math.min(window.innerWidth/1920, window.innerHeight/1080);
  s.style.transform=`scale(${k})`;
}
window.addEventListener('resize',fitStage);
fitStage();

ReactDOM.createRoot(document.getElementById('stage')).render(<App/>);
