/* eslint-disable */
const { useState, useEffect, useMemo } = React;

// ============ SETUP WIZARD ============
function SetupScreen({ state, setState, onJoinRoom, room }) {
  const [step, setStep] = useState(0);
  const [joinMode, setJoinMode] = useState(false);
  const [joinCode, setJoinCode] = useState('');
  const [joinName, setJoinName] = useState('');
  const [points, setPoints] = useState(state.points);
  const [playerCount, setPlayerCount] = useState(state.playerCount);
  const [faction, setFaction] = useState(state.faction);
  const [deployment, setDeployment] = useState(state.deployment);
  const [rounds, setRounds] = useState(state.rounds);
  const [hardMode, setHardMode] = useState(state.hardMode);

  const factionList = Object.keys(window.HORDE_DATA.factions);
  const deployments = ['Dawn of War', 'Hammer and Anvil', 'Search and Destroy', 'Tipping Point', "Crucible of Battle", 'Sweeping Engagement'];

  function startGame() {
    const data = window.HORDE_DATA;
    const allSecrets = data.cards.secret;
    // Deal 2 secrets per player
    const shuffled = window.HordeState.shuffle(allSecrets);
    const players = [];
    for (let i = 1; i <= playerCount; i++) {
      const p = window.HordeState.newPlayer(i);
      p.secrets = [shuffled.shift(), shuffled.shift()].filter(Boolean).map(c => c.n);
      players.push(p);
    }
    setState({
      ...window.HordeState.defaultGameState(),
      setup: true, points, playerCount, faction, deployment, rounds, hardMode,
      players,
      activePlayer: 1,
    });
  }

  if (joinMode) {
    const isConnecting = room && room.status === 'connecting';
    const isConnected = room && room.status === 'connected';
    const buttonLabel = isConnecting ? 'CONNECTING…' : (isConnected ? 'WAITING FOR HOST…' : 'Join Game');
    return (
      <div style={{minHeight:'100dvh', position:'relative'}}>
        <div className="setup-bg"/>
        <div className="view" style={{position:'relative', zIndex:1, paddingTop:'calc(40px + env(safe-area-inset-top))'}}>
          <div className="brand-mark" style={{textAlign:'center', marginBottom:'var(--pad-4)'}}>
            <div className="l1">40K</div>
            <div className="l2">HORDE MODE</div>
            <div className="tag">— JOIN A GAME —</div>
          </div>
          <div className="col gap-3">
            <div className="eyebrow">— Enter room code —</div>
            <h2 className="h2">Type the 4-letter code</h2>
            <div className="muted" style={{fontSize:12}}>The host shares this from their Multiplayer Room screen.</div>
            <input value={joinCode} onChange={e => setJoinCode(e.target.value.toUpperCase().replace(/[^A-Z0-9]/g,''))} placeholder="ABCD" maxLength={4}
              style={{width:'100%', padding:'18px', fontFamily:'var(--display)', fontStyle:'italic', fontWeight:800, fontSize:36, letterSpacing:'0.25em', textAlign:'center', background:'var(--bg-3)', border:'1px solid var(--line)', color:'var(--ink)', textTransform:'uppercase'}}/>
            <div className="eyebrow" style={{marginTop:'var(--pad-2)'}}>— Your display name —</div>
            <input value={joinName} onChange={e => setJoinName(e.target.value.slice(0,24))} placeholder="e.g. Marneus" maxLength={24}
              style={{width:'100%', padding:'14px', fontFamily:'var(--display)', fontWeight:700, fontSize:18, letterSpacing:'0.05em', background:'var(--bg-3)', border:'1px solid var(--line)', color:'var(--ink)'}}/>
            <button className="btn full" disabled={joinCode.length !== 4 || joinName.trim().length === 0 || isConnecting || isConnected} onClick={() => onJoinRoom && onJoinRoom(joinCode, joinName.trim())}>
              {buttonLabel}
            </button>
            {isConnected && (
              <div className="muted" style={{fontSize:11, textAlign:'center'}}>
                Connected to relay. Waiting for the host to send the game state…
                <div style={{marginTop:6, opacity:0.7}}>Peers visible: {room?.peers?.length ?? 0} · Channel: {window.HordeNet?.getStrategy?.() || '?'} {window.HordeNet?.getAppVersion?.() || ''}</div>
                {room?.peers?.length === 0 && (
                  <div style={{marginTop:6, color:'var(--c-misery)'}}>No host found on this code yet. Make sure host is on the Multiplayer Room screen with the same channel & version stamp.</div>
                )}
              </div>
            )}
            {room?.error && (
              <div className="col gap-2">
                <div className="chip misery" style={{textAlign:'center'}}>{room.error}</div>
                <button className="btn ghost full sm" onClick={() => { window.HordeNet?.disconnect(); }}>Reset connection</button>
              </div>
            )}
            <div className="muted" style={{fontSize:11, textAlign:'center', marginTop:8}}>Your name appears in the host's player list once you join. Game state syncs from the host.</div>
            <button className="btn ghost full" onClick={() => { setJoinMode(false); }}>← Back to setup</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{minHeight:'100dvh', position:'relative'}}>
      <div className="setup-bg"/>
      <div className="view" style={{position:'relative', zIndex:1, paddingTop:'calc(40px + env(safe-area-inset-top))'}}>
        <div className="brand-mark" style={{textAlign:'center', marginBottom:'var(--pad-4)'}}>
          <div className="l1">40K</div>
          <div className="l2">HORDE MODE</div>
          <div className="tag">— THE COMPANION —</div>
        </div>

        {step === 0 && (
          <div className="col gap-3">
            <div className="row" style={{justifyContent:'center', marginBottom:'var(--pad-2)'}}>
              <button className="btn ghost sm" onClick={() => setJoinMode(true)}>
                Joining a friend's game? →
              </button>
            </div>
            <div className="eyebrow">— Step 1 of 4 — Game Size —</div>
            <h2 className="h2">Pick a points value</h2>
            <div className="row" style={{gap:8}}>
              {[1000, 2000].map(v =>
                <button key={v} className={`option-row grow ${points === v ? 'active' : ''}`} onClick={() => setPoints(v)} style={{justifyContent:'center', padding:'18px'}}>
                  <div>
                    <div className="name" style={{fontSize:22}}>{v}</div>
                    <div className="meta">{v === 1000 ? '2 spawn zones' : '4 spawn zones'}</div>
                  </div>
                </button>
              )}
            </div>
            <div className="hr"/>
            <h2 className="h2">Players</h2>
            <div className="player-pills">
              {[1,2,3,4].map(n =>
                <button key={n} className={playerCount === n ? 'active' : ''} onClick={() => setPlayerCount(n)}>
                  {n} {n === 1 ? 'PLAYER' : 'PLAYERS'}
                </button>
              )}
            </div>
            <div className="muted" style={{fontSize:12}}>
              {Math.floor(points / playerCount)} pts each. {playerCount === 1 && 'Solo: SP gains are doubled.'}
            </div>
            <div className="hr"/>
            <h2 className="h2">Game Length</h2>
            <div className="row" style={{gap:8}}>
              {[5, 0].map(v =>
                <button key={v} className={`option-row grow ${rounds === v ? 'active' : ''}`} onClick={() => setRounds(v)} style={{justifyContent:'center'}}>
                  <div>
                    <div className="name">{v === 5 ? '5 ROUNDS' : 'INFINITE'}</div>
                    <div className="meta">{v === 5 ? 'Recommended' : 'Play until you lose'}</div>
                  </div>
                </button>
              )}
            </div>
            <div className="row gap-3" style={{marginTop:'var(--pad-3)'}}>
              <button className="btn ghost grow" onClick={() => setStep(1)} style={{visibility:'hidden'}}>Back</button>
              <button className="btn full grow" onClick={() => setStep(1)}>Next →</button>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="col gap-3">
            <div className="eyebrow">— Step 2 of 4 — The Horde —</div>
            <h2 className="h2">Pick a Horde Faction</h2>
            <div className="muted" style={{fontSize:12}}>This sets the spawn table and primary faction rule.</div>
            <div className="option-list" style={{maxHeight:'50dvh', overflow:'auto', paddingRight:4}}>
              {factionList.map(f =>
                <div key={f} className={`option-row ${faction === f ? 'active' : ''}`} onClick={() => setFaction(f)}>
                  <div className="grow">
                    <div className="name">{f}</div>
                    <div className="meta">{(window.HORDE_DATA.factionRules[f] || '').split(':')[0]}</div>
                  </div>
                </div>
              )}
            </div>
            <div className="row gap-3">
              <button className="btn ghost grow" onClick={() => setStep(0)}>← Back</button>
              <button className="btn grow" onClick={() => setStep(2)}>Next →</button>
            </div>
          </div>
        )}

        {step === 2 && (
          <div className="col gap-3">
            <div className="eyebrow">— Step 3 of 4 — Deployment —</div>
            <h2 className="h2">Pick a Deployment</h2>
            <div className="muted" style={{fontSize:12}}>Dawn of War &amp; Hammer and Anvil are easiest for spawning zones.</div>
            <div className="option-list">
              {deployments.map(d =>
                <div key={d} className={`option-row ${deployment === d ? 'active' : ''}`} onClick={() => setDeployment(d)}>
                  <div className="grow">
                    <div className="name">{d}</div>
                    <div className="meta">{['Dawn of War','Hammer and Anvil'].includes(d) ? 'Recommended' : 'Advanced — non-rectangular zones'}</div>
                  </div>
                </div>
              )}
            </div>
            <div className="row gap-3">
              <button className="btn ghost grow" onClick={() => setStep(1)}>← Back</button>
              <button className="btn grow" onClick={() => setStep(3)}>Next →</button>
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="col gap-3">
            <div className="eyebrow">— Step 4 of 4 — Confirm —</div>
            <h2 className="h2">Ready to deploy?</h2>
            <div className="tile">
              <div className="kv"><span className="k">Game</span><span className="v">{points} PTS · {playerCount}P</span></div>
              <div className="kv"><span className="k">Length</span><span className="v">{rounds === 5 ? '5 rounds' : 'Infinite'}</span></div>
              <div className="kv"><span className="k">Horde Faction</span><span className="v">{faction}</span></div>
              <div className="kv"><span className="k">Deployment</span><span className="v">{deployment}</span></div>
              <div className="kv"><span className="k">Spawn Zones</span><span className="v">{points === 1000 ? 2 : 4}</span></div>
            </div>
            <div className="faction-rule">
              <div className="eyebrow" style={{color:'var(--c-horde)'}}>Horde Primary Faction Rule</div>
              <div style={{marginTop:6, fontSize:14}} className="body-text">
                {window.HORDE_DATA.factionRules[faction]}
              </div>
            </div>
            <label className="row" style={{padding:'var(--pad-2)', background:'var(--bg-2)', border:'1px solid var(--line-soft)', cursor:'pointer'}}>
              <input type="checkbox" checked={hardMode} onChange={e => setHardMode(e.target.checked)} style={{accentColor:'var(--c-misery)', width:18, height:18}}/>
              <div className="grow">
                <div className="display" style={{fontSize:14}}>Add Hard Mode rules</div>
                <div className="muted" style={{fontSize:11}}>Optional add-on tweaks</div>
              </div>
            </label>
            <div className="row gap-3">
              <button className="btn ghost grow" onClick={() => setStep(2)}>← Back</button>
              <button className="btn danger grow lg" onClick={startGame}>BEGIN GAME</button>
            </div>
            <div className="muted center-text" style={{fontSize:11, marginTop:8}}>
              Players begin with 2 CP each. The Horde takes the first turn.
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ============ ROUND TRACKER ============
function RoundScreen({ state, setState, openCard, openDatasheet }) {
  const round = state.round;
  const phasesDone = state.phasesDone || {};

  function setPhase(id, val) {
    setState({...state, phasesDone: {...phasesDone, [id]: val}});
  }

  function nextRound() {
    if (state.rounds === 5 && round >= 5) {
      // End the game
      setState({...state, gameOver: true, gameEndedAt: Date.now()});
      return;
    }
    setState({
      ...state,
      round: round + 1,
      phasesDone: {},
      activeMisery: [], // discarded at start of next round
      revealedSecondary: null,
    });
  }
  function prevRound() {
    if (round <= 1) return;
    setState({...state, round: round - 1, phasesDone: {}});
  }

  const data = window.HORDE_DATA;
  const miseryById = (n) => data.cards.misery.find(c => c.n === n);
  const secondaryById = (n) => data.cards.secondary.find(c => c.n === n);

  function drawMisery(count = 1) {
    const used = state.activeMisery;
    const available = data.cards.misery.filter(c => !used.includes(c.n));
    const drawn = window.HordeState.shuffle(available).slice(0, count).map(c => c.n);
    setState({...state, activeMisery: [...used, ...drawn]});
    return drawn;
  }
  function clearMisery() { setState({...state, activeMisery: []}); }
  function drawSecondary() {
    const all = data.cards.secondary;
    const card = window.HordeState.pick(all);
    setState({...state, revealedSecondary: card.n});
    return card;
  }
  // Combined updates so we don't lose state from sequential setState calls.
  function drawMiseryAndMark(count, phaseId) {
    const used = state.activeMisery;
    const available = data.cards.misery.filter(c => !used.includes(c.n));
    const drawn = window.HordeState.shuffle(available).slice(0, count).map(c => c.n);
    setState({
      ...state,
      activeMisery: [...used, ...drawn],
      phasesDone: {...(state.phasesDone || {}), [phaseId]: true},
    });
  }
  function drawSecondaryAndMark(phaseId) {
    const card = window.HordeState.pick(data.cards.secondary);
    setState({
      ...state,
      revealedSecondary: card.n,
      phasesDone: {...(state.phasesDone || {}), [phaseId]: true},
    });
  }

  // Round-specific quick actions
  const miseryCountForRound = round === 1 ? 0 : (round >= 5 ? 3 : 1);
  const spawnMod = round >= 5 ? 2 : (round >= 3 ? 1 : 0);

  return (
    <div className="view">
      <div className="row between" style={{gap:8}}>
        <div className="round-badge">
          <div className="word">ROUND</div>
          <div className="num">{round}{state.rounds === 5 ? `/5` : ''}</div>
        </div>
        <div className="row" style={{gap:6}}>
          <button className="btn subtle sm" onClick={prevRound} disabled={round <= 1}>← Prev</button>
          <button className="btn sm" onClick={nextRound}>Next round →</button>
        </div>
      </div>
      {state.rounds === 5 && (
        <div className="round-gauge">
          {[1,2,3,4,5].map(n =>
            <div key={n} className={`seg ${n < round ? 'passed' : ''} ${n === round ? 'current' : ''}`}/>
          )}
        </div>
      )}

      <div className="tile">
        <div className="row between">
          <div>
            <div className="eyebrow">This round</div>
            <div className="display h3" style={{marginTop:2}}>
              {round === 1 ? 'Setup turn — spawn the horde' :
               round >= 5 ? `Final pressure — 3 Misery, +2 spawn` :
               round >= 3 ? `Pressure mounts — 1 Misery, +1 spawn` :
               '1 Misery this round'}
            </div>
          </div>
        </div>
        <div className="row gap-3" style={{marginTop:'var(--pad-2)'}}>
          <span className="chip misery">+{miseryCountForRound} Misery</span>
          <span className="chip">+{spawnMod} Spawn</span>
        </div>
      </div>

      <div>
        <div className="section-title">
          <h3 className="h3">Phase Checklist</h3>
        </div>
        <div className="tile" style={{padding:0}}>
          <div className="phase-list">
            {window.HordeState.DEFAULT_PHASES.map(p => (
              <div key={p.id} className={`phase-row ${phasesDone[p.id] ? 'done' : ''}`} onClick={() => setPhase(p.id, !phasesDone[p.id])}>
                <div className="check">✓</div>
                <div className="grow">
                  <div className="label">{p.label}</div>
                  <div className="desc">{p.desc}</div>
                </div>
                {p.id === 'reveal-misery' && miseryCountForRound > 0 && (
                  <button className="btn misery sm" onClick={(e) => { e.stopPropagation(); drawMiseryAndMark(miseryCountForRound, p.id); }}>
                    Draw {miseryCountForRound}
                  </button>
                )}
                {p.id === 'reveal-secondary' && (
                  <button className="btn secondary-c sm" onClick={(e) => { e.stopPropagation(); drawSecondaryAndMark(p.id); }}>
                    Reveal
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      <div>
        <div className="section-title">
          <h3 className="h3">Active Misery</h3>
          {state.activeMisery.length > 0 && (
            <button className="btn sm subtle" style={{marginLeft:'auto'}} onClick={clearMisery}>Discard all</button>
          )}
        </div>
        {state.activeMisery.length === 0 ? (
          <Empty title="No active Misery" subtitle="Draw at the start of round 2+." action={
            <button className="btn misery sm" onClick={() => drawMisery(1)}>+ Draw 1 Misery</button>
          }/>
        ) : (
          <div className="card-grid">
            {state.activeMisery.map(n => {
              const c = miseryById(n);
              return c && <CardImage key={n} card={c} onClick={() => openCard(c, 'misery')}/>
            })}
          </div>
        )}
      </div>

      <div>
        <div className="section-title">
          <h3 className="h3">Secondary This Round</h3>
        </div>
        {state.revealedSecondary == null ? (
          <Empty title="No secondary revealed" subtitle="Each round reveals a new mission." action={
            <button className="btn secondary-c sm" onClick={drawSecondary}>Reveal Secondary</button>
          }/>
        ) : (
          <div style={{maxWidth:280, margin:'0 auto'}}>
            <CardImage card={secondaryById(state.revealedSecondary)} onClick={() => openCard(secondaryById(state.revealedSecondary), 'secondary')}/>
            <div className="row gap-3" style={{marginTop:'var(--pad-2)'}}>
              <button className="btn subtle grow sm" onClick={drawSecondary}>↻ Re-reveal</button>
              <button className="btn ghost grow sm" onClick={() => setState({...state, revealedSecondary: null})}>Discard</button>
            </div>
          </div>
        )}
      </div>

      <div>
        <div className="section-title">
          <h3 className="h3">Spawns This Round</h3>
        </div>
        {(() => {
          const sp = (state.savedSpawns && state.savedSpawns[round]) || [];
          if (sp.length === 0) {
            return <Empty title="No spawns saved" subtitle="Roll all zones in the Spawn tab and tap Save."/>;
          }
          return (
            <div className="tile" style={{padding:0}}>
              <div className="phase-list">
                {sp.map(r => {
                  const canOpen = !!r.pickedUnit && !!openDatasheet;
                  return (
                  <div key={r.zone} className="phase-row" style={{cursor: canOpen ? 'pointer' : 'default'}}
                    onClick={canOpen ? () => openDatasheet(r.pickedUnit) : undefined}>
                    <div className="check" style={{background:'var(--c-horde)', color:'#fff', borderColor:'var(--c-horde)'}}>{r.zone}</div>
                    <div className="grow">
                      <div className="label">{r.pickedUnit || (r.bracket ? `Bracket ${r.bracket} — pick pending` : 'No spawn')}</div>
                      <div className="desc">
                        {r.die1}+{r.die2}{r.roundMod?`+${r.roundMod}`:''}{r.extraMod?(r.extraMod>0?`+${r.extraMod}`:`${r.extraMod}`):''} = {r.total}
                        {r.bracket && ` · BRACKET ${r.bracket}`}
                        {canOpen && <span style={{color:'var(--c-horde)'}}> · view datasheet ›</span>}
                      </div>
                    </div>
                  </div>
                  );
                })}
              </div>
            </div>
          );
        })()}
      </div>
    </div>
  );
}

Object.assign(window, { SetupScreen, RoundScreen });
