/* =========================================================================
   CISCO ARENA — Chrome components (Header, Sidebar, Footer, ScreenNav)
   ========================================================================= */

const { useState, useEffect, useMemo, useRef } = React;

function Header({ theme, phaseLabel, phaseKey, me, team, sessionCode, proctorName }) {
  const themeLabel = theme.label.toUpperCase();
  return (
    <>
    <a href="#main-stage" className="sr-only-focusable">Skip to content</a>
    <div className="header" role="banner">
      <div className="brand">
        <div className="brand-mark">A</div>
        <div>
          <div className="brand-name">{themeLabel}</div>
          <div className="brand-tag">{phaseKey === "join" ? "CHECK-IN · SEASON 04" : `${phaseLabel.toUpperCase()} · SEASON 04 · ROUND 03`}</div>
        </div>
      </div>
      <div className="phase-pill">
        <span className="dot" />
        {phaseLabel}
      </div>
      <div className="header-right">
        <div className="me-chip" title="You">
          <span className="label">{me.name}</span>
          <span className="sub">·</span>
          <span className="sub">{team.short}</span>
          <span className="avatar" style={{background: team.color, color: "#0a1320"}}>
            {me.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
          </span>
        </div>
        <button className="icon-btn" aria-label="Settings">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="12" cy="12" r="3"/>
            <path d="M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.7 1.7 0 0 0-1.87-.34 1.7 1.7 0 0 0-1.03 1.56V21a2 2 0 1 1-4 0v-.09A1.7 1.7 0 0 0 9 19.4a1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.7 1.7 0 0 0 .34-1.87 1.7 1.7 0 0 0-1.56-1.03H3a2 2 0 1 1 0-4h.09A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.7 1.7 0 0 0 1.87.34H9a1.7 1.7 0 0 0 1.03-1.56V3a2 2 0 1 1 4 0v.09A1.7 1.7 0 0 0 15 4.6a1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.7 1.7 0 0 0-.34 1.87V9c.1.39.39.72.78.89a1.7 1.7 0 0 0 .78.11H21a2 2 0 1 1 0 4h-.09a1.7 1.7 0 0 0-1.51 1z"/>
          </svg>
        </button>
      </div>
    </div>
    </>
  );
}

function Sidebar({ theme, leaderboard, me, streak, score, prevScore, timerSec, totalSec, urgent, powerupsSpent, onPowerup, layoutCompact, screen, draftStatus, draftTeams, draftUndrafted, isCaptain, isMyTurn, connected, tdActive }) {
  // Filter out proctors
  const activePlayers = leaderboard.filter(p => !p.is_proctor && p.role !== 'proctor');
  // Build team groups sorted by team total score DESC
  const teamGroups = useMemo(() => {
    const groups = theme.teams.map(t => {
      const members = activePlayers
        .filter(p => p.tid === t.id)
        .sort((a, b) => (b.score || 0) - (a.score || 0));
      const total = members.reduce((s, p) => s + (p.score || 0), 0);
      return { ...t, members, total };
    }).sort((a, b) => b.total - a.total);
    const unassigned = activePlayers.filter(p => !p.tid).sort((a, b) => (b.score || 0) - (a.score || 0));
    if (unassigned.length > 0) groups.push({ id: '__none__', short: '—', name: 'Sin equipo', color: 'var(--ink-muted)', emoji: '❓', members: unassigned, total: 0 });
    return groups;
  }, [theme, activePlayers]);
  const sorted = [...activePlayers].sort((a,b) => b.score - a.score);
  const myRank = sorted.findIndex(p => p.id === me.id) + 1;
  const showTimer = (screen === "quiz" || screen === "triage") && !tdActive;
  const isLobby = screen === "lobby";
  const draftActive = !!(draftStatus && draftStatus.active);
  const [draftNow, setDraftNow] = useState(Date.now());

  const timerDisplay = useMemo(() => {
    const s = Math.max(0, Math.floor(timerSec));
    return `${String(Math.floor(s/60)).padStart(2,"0")}:${String(s%60).padStart(2,"0")}`;
  }, [timerSec]);
  const timerPct = Math.max(0, Math.min(100, (timerSec / totalSec) * 100));

  useEffect(() => {
    if (!draftActive) return;
    const t = setInterval(() => setDraftNow(Date.now()), 100);
    return () => clearInterval(t);
  }, [draftActive]);

  // ── Lobby / Draft: roster view ──
  if (isLobby) {
    if (draftActive) {
      const getTeamTheme = (teamId) => theme.teams.find(t => t.id === teamId) || {};
      const getTeamName = (teamId) => getTeamTheme(teamId).name || teamId || "Unassigned";
      const getCurrentCaptainInfo = () => {
        if (!draftStatus || !draftStatus.active) return null;
        const order = draftStatus.captain_order || [];
        const idx = draftStatus.current_pick_index || 0;
        const round = draftStatus.round || 1;
        const n = order.length;
        if (n === 0) return null;
        const captainIdx = round % 2 === 1 ? (idx % n) : ((n - 1) - (idx % n));
        const email = order[captainIdx];
        for (const [teamId, teamData] of Object.entries(draftTeams || {})) {
          const captain = teamData.captain || (teamData.members || []).find(m => m.isCaptain);
          if (captain && captain.email === email) {
            const themeTeam = theme.teams.find(t => t.id === teamId);
            return { ...captain, teamId, teamName: themeTeam?.name || teamId, teamColor: themeTeam?.color || 'var(--accent)' };
          }
        }
        return { email, teamId: '', teamName: '', teamColor: 'var(--accent)' };
      };

      const currentCaptain = getCurrentCaptainInfo();
      const draftCountdown = draftStatus?.pick_deadline ? Math.max(0, draftStatus.pick_deadline - (draftNow / 1000)) : 0;
      const draftTotal = draftStatus?.pick_duration || 15;
      const draftPct = draftTotal > 0 ? Math.max(0, Math.min(100, (draftCountdown / draftTotal) * 100)) : 0;
      const draftTimerColor = draftPct > 60 ? "var(--success)" : (draftPct > 30 ? "var(--warning)" : "var(--danger)");
      const assignedTeam = me?.tid ? getTeamName(me.tid) : "";
      const maxManual = draftStatus?.max_manual_rounds || 2;
      const modeLabel = (draftStatus?.round || 1) > maxManual ? "Auto" : "Manual";

      return (
        <aside className="side" role="complementary" aria-label="Draft status">
          <div className="panel" style={{borderColor: "color-mix(in oklch, var(--accent) 45%, var(--line))", boxShadow: "0 14px 30px rgba(0,0,0,.18)"}}>
            <div className="panel-head">
              <span style={{display: "flex", alignItems: "center", gap: 8}}>
                <span className="mono" style={{padding: "4px 8px", borderRadius: 999, background: "color-mix(in oklch, var(--accent) 18%, transparent)", color: "var(--accent)", letterSpacing: ".16em", fontSize: 11}}>DRAFT</span>
                <span>Round {draftStatus?.round || 1}</span>
              </span>
              <span className="mono" style={{color:"var(--ink-muted)"}}>{modeLabel}</span>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <span>Pick Clock</span>
              <span className="mono" style={{color: draftTimerColor}}>{draftCountdown.toFixed(1)}s</span>
            </div>
            <div className={`timer-bar ${draftPct < 30 ? "urgent" : ""}`} style={{marginTop: 4}}>
              <span style={{width: `${draftPct}%`, background: `linear-gradient(90deg, ${draftTimerColor}, color-mix(in oklch, ${draftTimerColor} 65%, white 35%))`}}/>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <span>Current Pick</span>
              <span className="mono" style={{color:"var(--ink-muted)"}}>{currentCaptain?.teamName || "Awaiting"}</span>
            </div>
            <div style={{display: "flex", alignItems: "center", gap: 10, fontSize: "0.92rem"}}>
              <span style={{display:"inline-block", width:10, height:10, borderRadius:999, background: currentCaptain?.teamColor || "var(--accent)", boxShadow: `0 0 18px ${currentCaptain?.teamColor || "var(--accent)"}`}} />
              <div>
                <div className="lb-name">{currentCaptain?.name || currentCaptain?.email || "Captain pending"}</div>
                <div className="lb-sub">{currentCaptain?.teamName || "Draft board live"}</div>
              </div>
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <span>Your Status</span>
              <span className="mono" style={{color:"var(--ink-muted)"}}>{connected ? "LIVE" : "DEMO"}</span>
            </div>
            <div style={{display: "grid", gap: 6, fontSize: "0.9rem"}}>
              {isCaptain ? (
                <>
                  <div className="lb-name">You're captain!</div>
                  <div className="lb-sub">{isMyTurn ? "Your turn to pick right now." : "Waiting for the board to swing back to you."}</div>
                </>
              ) : (
                <>
                  <div className="lb-name">{me?.tid ? `Assigned to ${assignedTeam}` : "In the draft pool"}</div>
                  <div className="lb-sub">{me?.tid ? "Your squad slot is locked in." : "A captain will pick you soon."}</div>
                </>
              )}
              <div className="mono" style={{color: "var(--ink-muted)", marginTop: 4}}>{(draftUndrafted || []).length} players remaining</div>
            </div>
          </div>

          {theme.teams.map(t => {
            const teamData = (draftTeams && draftTeams[t.id]) || {};
            const members = teamData.members || [];
            return (
              <div key={t.id} className="panel">
                <div className="panel-head">
                  <span><span style={{display:"inline-block", width:10, height:10, borderRadius:3, background:t.color, marginRight:6, verticalAlign:"middle"}}/>{t.name}</span>
                  <span className="mono" style={{color:"var(--ink-muted)"}}>{members.length}</span>
                </div>
                <div className="lb-list">
                  {members.map(p => (
                    <div key={p.email || p.id || p.name} className={`lb-row ${(p.email || p.id) === me.id ? "me" : ""}`}>
                      <div className="lb-av" style={{background: t.color, color:"#0a1320"}}>
                        {(p.name || "?").split(" ").map(n=>n[0]).join("").slice(0,2)}
                      </div>
                      <div>
                        <div className="lb-name">{p.name}</div>
                        {(p.isCaptain || p.role) && <div className="lb-sub">{p.isCaptain ? "Captain" : p.role}</div>}
                      </div>
                    </div>
                  ))}
                  {members.length === 0 && (
                    <div style={{padding:"8px 12px", color:"var(--ink-muted)", fontSize:"0.82rem", fontStyle:"italic"}}>No picks yet</div>
                  )}
                </div>
              </div>
            );
          })}
        </aside>
      );
    }

    const unassigned = leaderboard.filter(p => !p.tid);
    return (
      <aside className="side" role="complementary" aria-label="Roster">
        {/* Player count */}
        <div className="panel">
          <div className="panel-head">
            <span>Registered Players</span>
            <span className="mono" style={{color:"var(--ink-muted)"}}>{leaderboard.length}</span>
          </div>
        </div>

        {/* Teams */}
        {theme.teams.map(t => {
          const members = leaderboard.filter(p => p.tid === t.id);
          return (
            <div key={t.id} className="panel">
              <div className="panel-head">
                <span><span style={{display:"inline-block", width:10, height:10, borderRadius:3, background:t.color, marginRight:6, verticalAlign:"middle"}}/>{t.name}</span>
                <span className="mono" style={{color:"var(--ink-muted)"}}>{members.length}</span>
              </div>
              <div className="lb-list">
                {members.map(p => (
                  <div key={p.id} className={`lb-row ${p.id === me.id ? "me" : ""}`}>
                    <div className="lb-av" style={{background: t.color, color:"#0a1320"}}>
                      {p.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
                    </div>
                    <div>
                      <div className="lb-name">{p.name}</div>
                      {p.role && <div className="lb-sub">{p.role}</div>}
                    </div>
                  </div>
                ))}
                {members.length === 0 && (
                  <div style={{padding:"8px 12px", color:"var(--ink-muted)", fontSize:"0.82rem", fontStyle:"italic"}}>No players yet</div>
                )}
              </div>
            </div>
          );
        })}

        {/* Unassigned / Waiting room */}
        {unassigned.length > 0 && (
          <div className="panel available-panel">
            <div className="panel-head available-panel-head">
              <div className="available-panel-title">
                <span>Available Players</span>
                <span className="available-panel-sub">Draft pool</span>
              </div>
              <span className="mono available-panel-count">{unassigned.length}</span>
            </div>
            <div className="lb-list available-list">
              {unassigned.map(p => (
                <div key={p.id} className={`available-card ${p.id === me.id ? "me" : ""}`}>
                  <div className="available-card-main">
                    <div className="lb-av available-av" style={{background:"color-mix(in oklch, var(--accent) 78%, white 22%)", color:"#0a1320"}}>
                      {p.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
                    </div>
                    <div className="available-copy">
                      <div className="available-topline">
                        <div className="lb-name">{p.name}</div>
                        <div className="available-score mono">{(p.score ?? 0).toLocaleString()}</div>
                      </div>
                      <div className="available-meta">
                        <span className="available-tag">{p.role || "Player"}</span>
                        {(p.isMe || p.id === me.id) && <span className="available-tag me">You</span>}
                        <span className="available-status">Available for draft</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </aside>
    );
  }

  // ── Game mode: timer + score + leaderboard + powerups ──
  return (
    <aside className="side" role="complementary" aria-label="Leaderboard">
      {/* Timer — only during quiz/triage phases */}
      {showTimer && (
      <div className="panel">
        <div className="panel-head">
          <span>Phase Clock</span>
          <span className="live"><span className="dot"/>LIVE</span>
        </div>
        <div className="timer">
          <div className={`timer-num mono ${urgent ? "urgent" : ""}`} aria-live="polite" aria-label="Time remaining">{timerDisplay}</div>
          <div className="timer-meta">
            <div className="q">Q {Math.min(5, Math.ceil((totalSec - timerSec) / (totalSec/5)))}/5</div>
            <div>phase in progress</div>
          </div>
        </div>
        <div className={`timer-bar ${urgent ? "urgent" : ""}`}>
          <span style={{width: `${timerPct}%`}}/>
        </div>
      </div>
      )}

      {/* Streak / score */}
      <div className="panel">
        <div className="panel-head">
          <span>Your Score</span>
          <span className="mono" style={{color:"var(--ink-muted)"}}>#{myRank || "—"}</span>
        </div>
        <div className="streak">
          <div className="streak-score">
            <span key={score} className="big mono">{score.toLocaleString()}</span>
            {score > prevScore && <span className="delta">+{score - prevScore}</span>}
          </div>
          <div className="streak-flames">STREAK × {streak}</div>
        </div>
      </div>

      {/* Team-grouped Leaderboard */}
      <div className="panel lb">
        <div className="panel-head">
          <span>Leaderboard</span>
          <span className="mono" style={{color:"var(--ink-muted)"}}>{theme.teams.length} {tc("teams")}</span>
        </div>
        <div className="lb-list">
          {teamGroups.map((tg, ti) => {
            const isMyTeam = tg.id === me.tid;
            return (
              <div key={tg.id} className={`team-lb-group ${isMyTeam ? "team-lb-group--mine" : ""}`}
                style={isMyTeam ? {"--team-accent": tg.color} : {}}>
                {/* Team header row */}
                <div className="team-lb-header" style={{borderLeft: `3px solid ${tg.color}`}}>
                  <div className="team-lb-header-left">
                    <span className="team-lb-rank mono" style={{color: tg.color}}>{ti + 1}</span>
                    <span className="team-lb-emoji">{tg.emoji}</span>
                    <span className="team-lb-short">{tg.short}</span>
                  </div>
                  <div className="team-lb-header-right">
                    <span className="team-lb-count mono" style={{color:"var(--ink-muted)"}}>{tg.members.length}p</span>
                    <span className="team-lb-total mono">{tg.total.toLocaleString()}</span>
                  </div>
                </div>
                {/* Players in this team */}
                {tg.members.slice(0, layoutCompact ? 3 : 5).map((p) => (
                  <div key={p.id} className={`lb-row team-lb-player ${p.id === me.id ? "me" : ""} ${p.climbing ? "climbing" : ""}`}
                    style={{paddingLeft: 18}}>
                    <div className="lb-av" style={{background: tg.color, color:"#0a1320"}}>
                      {p.name.split(" ").map(n=>n[0]).join("").slice(0,2)}
                    </div>
                    <div>
                      <div className="lb-name">{p.name}</div>
                      <div className="lb-sub">{p.role}</div>
                    </div>
                    <div className="lb-score mono">{(p.score||0).toLocaleString()}</div>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      </div>

      {/* Power-ups */}
      <div className="panel">
        <div className="panel-head">
          <span>Power-ups</span>
          <span className="mono" style={{color:"var(--ink-muted)"}}>50 pts ea.</span>
        </div>
        <div className="powerups">
          {theme.powerups.map(p => (
            <button
              key={p.id}
              className={`powerup ${powerupsSpent.includes(p.id) ? "spent" : ""}`}
              onClick={() => !powerupsSpent.includes(p.id) && onPowerup(p.id)}
              disabled={powerupsSpent.includes(p.id)}
              title={p.name}
            >
              <span className="icon">{p.icon}</span>
              <span className="name">{p.name}</span>
              <span className="cost mono">50</span>
            </button>
          ))}
        </div>
      </div>
    </aside>
  );
}

function Footer({ theme, sessionCode, proctorName, region }) {
  const displaySession = sessionCode || "CA-7842-KR";
  const displayProctor = proctorName || "J. Medina";
  const displayRegion  = region      || "LATAM-S";
  return (
    <>
      <div className="checker-strip" />
      <div className="foot" role="contentinfo">
        <div>
          <span style={{color:"var(--ink-dim)"}}>{theme.label}</span>
          <span className="sep">/</span>
          <span>Powered by Cisco Arena</span>
        </div>
        <div>
          <span>Session: {displaySession}</span>
          <span className="sep">/</span>
          <span>Proctor: {displayProctor}</span>
          <span className="sep">/</span>
          <span>Region: {displayRegion}</span>
        </div>
        <div className="cisco-mark">
          <span className="swatch" />
          <span>Cisco · v4.2</span>
        </div>
      </div>
    </>
  );
}

function ScreenNav({ screen, onPick }) {
  const items = [
    { k: "join",    label: "01", ariaLabel: "Go to Join screen" },
    { k: "lobby",   label: "02", ariaLabel: "Go to Lobby screen" },
    { k: "quiz",    label: "03", ariaLabel: "Go to Quiz screen" },
    { k: "triage",  label: "04", ariaLabel: "Go to Triage screen" },
    { k: "wrap",    label: "05", ariaLabel: "Go to Wrap-up screen" },
  ];
  return (
    <nav className="scr-nav" aria-label="Screen navigation">
      {items.map(i => (
        <button
          key={i.k}
          className={screen === i.k ? "active" : ""}
          onClick={() => onPick(i.k)}
          title={i.k}
          aria-label={i.ariaLabel}
          aria-current={screen === i.k ? "page" : undefined}
        >{i.label}</button>
      ))}
    </nav>
  );
}

window.Header   = Header;
window.Sidebar  = Sidebar;
window.Footer   = Footer;
window.ScreenNav = ScreenNav;
