// ── Mock data ────────────────────────────────────────────────
const SCHOOL_BOARD = [
  { rank: 1, name: 'PhotonPhoenix',  tag: 'Yr 11 · 7B',     score: 4820, streak: 12, you: false },
  { rank: 2, name: 'KineticKira',    tag: 'Yr 12 · 7C',     score: 4710, streak: 9 },
  { rank: 3, name: 'MitoMari',       tag: 'Yr 11 · 7A',     score: 4650, streak: 6 },
  { rank: 4, name: 'QuantumQuokka',  tag: 'Yr 11 · 7A',     score: 4420, streak: 7, you: true },
  { rank: 5, name: 'ProtonPete',     tag: 'Yr 12 · 7B',     score: 4380, streak: 4 },
  { rank: 6, name: 'AldolAlex',      tag: 'Yr 11 · 7B',     score: 4210, streak: 3 },
  { rank: 7, name: 'QuasarQ',        tag: 'Yr 12 · 7D',     score: 4140, streak: 5 },
  { rank: 8, name: 'TitratorT',      tag: 'Yr 11 · 7A',     score: 4020, streak: 2 },
];
const YEAR_BOARD = [
  { rank: 1,   name: 'ZenithMC',       tag: 'St Aubin\'s College',       score: 4980, streak: 14 },
  { rank: 2,   name: 'CurieKid_91',    tag: 'Harbour Heights Boys',      score: 4895, streak: 10 },
  { rank: 3,   name: 'VectorVi',       tag: 'Parkside Selective',        score: 4870, streak: 8 },
  { rank: 84,  name: 'QuantumQuokka',  tag: 'Northvale High',            score: 4420, streak: 7, you: true },
  { rank: 85,  name: 'OxideOlly',      tag: 'Ashglen Grammar',           score: 4418, streak: 6 },
  { rank: 86,  name: 'MoleMaverick',   tag: 'Stonebridge Grammar',       score: 4412, streak: 3 },
  { rank: 87,  name: 'TautoTina',      tag: 'Rosehaven Ladies\' College', score: 4405, streak: 4 },
  { rank: 88,  name: 'HelixHugo',      tag: 'Maple Hill College',        score: 4390, streak: 5 },
];
const TEACHER_BOARD = [
  { rank: 1, name: 'Dr Park',        tag: 'Biology · Harbour Heights Boys', score: 5780, streak: 22, teacher: true },
  { rank: 2, name: 'Ms Tanaka',      tag: 'Chemistry · Northvale Girls',    score: 5660, streak: 18, teacher: true },
  { rank: 3, name: 'Mr Whitlock',    tag: 'Physics · St Aubin\'s',          score: 5510, streak: 14, teacher: true },
  { rank: 4, name: 'ZenithMC',       tag: 'St Aubin\'s · Yr 12',            score: 4980, streak: 14 },
  { rank: 5, name: 'Ms Rao',         tag: 'Maths Ext · Parkside',           score: 4960, streak: 9,  teacher: true },
  { rank: 6, name: 'CurieKid_91',    tag: 'Harbour Heights · Yr 12',        score: 4895, streak: 10 },
  { rank: 7, name: 'VectorVi',       tag: 'Parkside · Yr 12',               score: 4870, streak: 8 },
  { rank: 8, name: 'Mr Halloran',    tag: 'Maths · Maple Hill',             score: 4810, streak: 6,  teacher: true },
];

// initials helper
function initials(name) {
  const parts = name.replace(/_\d+$/,'').split(/[ _]+/);
  if (parts.length === 1) return parts[0].slice(0,2).toUpperCase();
  return (parts[0][0] + (parts[parts.length-1][0] || '')).toUpperCase();
}

// ── Row ──
function LbRow({ row, dense = false, hideAvatar = false }) {
  const rankCls = row.rank === 1 ? 'gold' : row.rank === 2 ? 'silver' : row.rank === 3 ? 'bronze' : '';
  return (
    <div className={`wc-row ${row.you ? 'me' : ''} ${row.teacher ? 'teacher' : ''}`}>
      <div className={`wc-rank ${rankCls}`}>{row.rank}</div>
      <div className="wc-row-who">
        {!hideAvatar && (
          <div className={`wc-row-avatar ${row.teacher ? 'teacher' : ''} ${row.you ? 'me' : ''}`}>
            {initials(row.name)}
          </div>
        )}
        <div style={{ minWidth: 0 }}>
          <div className="wc-row-name">
            {row.name}
            {row.you && <span className="wc-row-chip you-chip">YOU</span>}
            {row.teacher && !dense && <span className="wc-row-chip teacher-chip">TEACHER</span>}
          </div>
          {!dense && <div className="wc-row-tag">{row.tag}</div>}
        </div>
      </div>
      {!dense && row.streak >= 5 && (
        <div className="wc-row-streak"><Icon name="flame"/>{row.streak}d</div>
      )}
      <div className="wc-row-score">
        <strong>{row.score.toLocaleString()}</strong>
        {!dense && <small>pts</small>}
      </div>
    </div>
  );
}

// ── Hub V1 — Standard tabbed leaderboard hub ──
function HubV1({ accent = 'rose', onPlay }) {
  const [tab, setTab] = React.useState('school');
  const [liveRows, setLiveRows] = React.useState(null); // null = not yet loaded
  const [weekKey, setWeekKey] = React.useState('');
  const [cd, setCd] = React.useState({ days: 3, hours: 14 });

  React.useEffect(() => {
    const sched = window.HSCQuizSchedule;
    if (sched) {
      const key = sched.getCurrentWeekKey();
      setWeekKey(key);
      // Countdown to next Saturday (next challenge drop)
      const nextSat = new Date(key + 'T00:00:00+10:00');
      nextSat.setDate(nextSat.getDate() + 7);
      const ms = nextSat - Date.now();
      if (ms > 0) setCd({ days: Math.floor(ms / 86400000), hours: Math.floor((ms % 86400000) / 3600000) });
    }
    // Load real quiz leaderboard (always set liveRows to an array — empty = no scores yet)
    const wq = window.HSCWeeklyQuiz;
    if (wq && window.HSCQuizSchedule) {
      const key = window.HSCQuizSchedule.getCurrentWeekKey();
      wq.getLeaderboard(key, null, null).then(function (rows) {
        setLiveRows((rows || []).map(function (r) {
          return { rank: r.rank, name: r.display || 'Unknown', tag: '', score: r.score, streak: 0, you: r.isMe };
        }));
      }).catch(function () { setLiveRows([]); });
    } else {
      setLiveRows([]);
    }
  }, []);

  const weekNum = weekKey
    ? Math.ceil((new Date(weekKey) - new Date(weekKey.slice(0, 4) + '-01-01')) / (7 * 86400000)) + 1
    : 28;
  const weekYear = weekKey ? weekKey.slice(0, 4) : '2026';

  const boardRows = liveRows; // null = loading, [] = no scores yet, [...] = live data

  const tabMeta = {
    school:  { title: 'Your school',      sub: 'Weekly challenge scores',  icon: 'school',  cls: '' },
    year:    { title: 'Year 11 · NSW',    sub: 'Weekly challenge scores',  icon: 'users',   cls: 'plum' },
    teacher: { title: 'Beat the Teacher', sub: 'All ages · all subjects',  icon: 'crown',   cls: 'gold' },
  };

  return (
    <div className="wc-shell">
      {/* hero */}
      <section className="wc-hero">
        <div className="wc-hero-inner">
          <div>
            <div className="wc-hero-badges">
              <span className="wc-hero-badge"><Icon name="flag"/> Week {weekNum} · {weekYear}</span>
              <span className="wc-hero-badge">Year 11 · Mixed</span>
              <span className="wc-hero-badge gold"><Icon name="bolt"/> +120 XP available</span>
            </div>
            <h1>Weekly Challenge<br/><em>Boards</em></h1>
            <p className="wc-hero-sub">15 quick-fire questions covering everything you've learnt this year. Climb the boards. Topple a teacher.</p>
            <div className="wc-hero-actions">
              <button className="wc-cta wc-cta-gold" onClick={function () { onPlay && onPlay(); }}>
                <Icon name="play"/> Play this week's challenge
              </button>
              <button className="wc-cta wc-cta-ghost">How it works</button>
            </div>
          </div>
          <div className="wc-countdown">
            <CountdownRing days={cd.days} hours={cd.hours}/>
            <div>
              <div className="wc-cd-label">Next release</div>
              <div className="wc-cd-title">Monday 9:00 AM</div>
              <div className="wc-cd-sub">Boards reset weekly · last week's champs locked in your profile</div>
            </div>
          </div>
        </div>
      </section>

      {/* Beat the teacher feature */}
      <section className="wc-bt">
        <div className="wc-bt-inner">
          <span className="wc-bt-eye"><Icon name="crown"/> &nbsp; Featured board</span>
          <h2>Beat the Teacher</h2>
          <p>The top score from every teacher at every subject and stage, mixed with the best students of all ages. One board. No mercy.</p>
          <div className="wc-hero-actions" style={{ display: 'flex', gap: 10 }}>
            <button className="wc-cta wc-cta-gold" onClick={function () { window.location.href = 'leaderboard.html'; }}>
              View board <Icon name="chevronR"/>
            </button>
            <button className="wc-cta wc-cta-ghost">Past winners</button>
          </div>
        </div>
        <div className="wc-bt-teachers">
          <div className="wc-bt-teacher">
            <div className="wc-bt-teacher-avatar">MW</div>
            <div className="wc-bt-teacher-name">Mr Whitlock</div>
            <div className="wc-bt-teacher-score">5,510</div>
            <div className="wc-bt-teacher-tag">Physics · 3rd</div>
          </div>
          <div className="wc-bt-teacher lead">
            <div className="wc-bt-teacher-crown"><Icon name="crown"/></div>
            <div className="wc-bt-teacher-avatar">DP</div>
            <div className="wc-bt-teacher-name">Dr Park</div>
            <div className="wc-bt-teacher-score">5,780</div>
            <div className="wc-bt-teacher-tag">Biology · 1st</div>
          </div>
          <div className="wc-bt-teacher">
            <div className="wc-bt-teacher-avatar">MT</div>
            <div className="wc-bt-teacher-name">Ms Tanaka</div>
            <div className="wc-bt-teacher-score">5,660</div>
            <div className="wc-bt-teacher-tag">Chem · 2nd</div>
          </div>
        </div>
      </section>

      <div className="wc-section-label">Live this week</div>

      <nav className="wc-tabs">
        {['school','year','teacher'].map(k => (
          <button key={k}
            className={`wc-tab ${tabMeta[k].cls} ${tab === k ? 'active' : ''}`}
            onClick={() => setTab(k)}>
            <div className="wc-tab-icon-wrap"><Icon name={tabMeta[k].icon}/></div>
            <span>
              <span className="wc-tab-label">{k === 'school' ? 'Your school' : k === 'year' ? 'Year 11 · NSW' : 'Beat the Teacher'}</span>
              <span className="wc-tab-count">{tabMeta[k].sub}</span>
            </span>
          </button>
        ))}
      </nav>

      <div className="wc-card wc-board" style={{ margin: '14px 20px' }}>
        <div className="wc-board-head">
          <div className={`wc-board-icon ${tab === 'school' ? 'rose' : tab === 'year' ? 'plum' : 'gold'}`}>
            <Icon name={tabMeta[tab].icon}/>
          </div>
          <div>
            <div className="wc-board-title">{tabMeta[tab].title}</div>
            <div className="wc-board-sub">{tabMeta[tab].sub} · Week {weekNum}</div>
          </div>
          <div className="wc-board-meta">{boardRows === null ? 'Loading…' : 'Live'}</div>
        </div>
        {boardRows === null && (
          <div style={{ padding: '32px 20px', textAlign: 'center', color: 'var(--adv-muted)', fontSize: 14 }}>Loading scores…</div>
        )}
        {boardRows !== null && boardRows.length === 0 && (
          <div style={{ padding: '32px 20px', textAlign: 'center', color: 'var(--adv-muted)', fontSize: 14 }}>
            No scores yet this week — <button className="wc-cta wc-cta-gold" style={{ display: 'inline-flex', padding: '6px 14px', fontSize: 13 }} onClick={function () { onPlay && onPlay(); }}>play the quiz</button> to be first!
          </div>
        )}
        {boardRows !== null && boardRows.length > 0 && boardRows.map(r => <LbRow key={r.rank + r.name} row={r}/>)}
      </div>
    </div>
  );
}

// ── Hub V2 — Trophy hall with podiums + three boards visible ──
function HubV2() {
  const PodiumBoard = ({ rows, icon, iconCls, title, sub, meta }) => {
    const top3 = rows.slice(0,3);
    const rest = rows.slice(3, 6);
    // arrange 2-1-3 visually
    const podiumOrder = [top3[1], top3[0], top3[2]];
    const podiumCls = ['second', 'first', 'third'];
    return (
      <div className="wc-card wc-board">
        <div className="wc-board-head">
          <div className={`wc-board-icon ${iconCls}`}><Icon name={icon}/></div>
          <div>
            <div className="wc-board-title">{title}</div>
            <div className="wc-board-sub">{sub}</div>
          </div>
        </div>
        <div className="wc-podium">
          {podiumOrder.map((r, i) => r && (
            <div key={i} className={`wc-podium-pillar ${podiumCls[i]}`}>
              <div className="wc-podium-rank">{r.rank}</div>
              <div className="wc-podium-name">{r.name}</div>
              <div className="wc-podium-pts">{r.score.toLocaleString()}</div>
            </div>
          ))}
        </div>
        {rest.map(r => <LbRow key={r.rank+r.name} row={r} dense={true}/>)}
        <div style={{ padding: '10px 18px', textAlign: 'center', fontSize: 12, color: 'var(--adv-muted)', fontWeight: 600, borderTop: '1px solid var(--adv-rule-soft)' }}>
          {meta}
        </div>
      </div>
    );
  };
  return (
    <div className="wc-scope">
      <TopBar/>

      <div className="wc-shell">
        {/* hero */}
        <section className="wc-hero">
          <div className="wc-hero-inner">
            <div>
              <div className="wc-hero-badges">
                <span className="wc-hero-badge"><Icon name="flag"/> Week 28 · 2026</span>
                <span className="wc-hero-badge gold"><Icon name="bolt"/> Live now</span>
              </div>
              <h1>Trophy <em>Hall</em></h1>
              <p className="wc-hero-sub">Three boards. One challenge. 15 questions, 5 minutes — covering everything taught up to this week.</p>
              <div className="wc-hero-actions">
                <button className="wc-cta wc-cta-gold"><Icon name="play"/> Start this week's challenge</button>
                <span style={{ color: 'rgba(255,255,255,0.7)', fontSize: 13.5, marginLeft: 6 }}>
                  Best of <strong style={{color:'#fff'}}>3 attempts</strong> counts
                </span>
              </div>
            </div>
            <div className="wc-countdown">
              <CountdownRing days={3} hours={14}/>
              <div>
                <div className="wc-cd-label">New challenge in</div>
                <div className="wc-cd-title">3 days 14 hours</div>
                <div className="wc-cd-sub">Monday 9:00 AM · boards reset · streaks carry over</div>
              </div>
            </div>
          </div>
        </section>

        <div className="wc-section-label">The three boards</div>

        <div className="wc-boards-3">
          <PodiumBoard rows={SCHOOL_BOARD}  icon="school" iconCls="rose" title="Your school"      sub="Northvale High · 124 playing" meta="View all 124 →" />
          <PodiumBoard rows={YEAR_BOARD}    icon="users"  iconCls="plum" title="Year 11 · NSW"    sub="4,820 students playing"        meta={<>You're at <strong style={{color:'var(--adv-ink)'}}>#84</strong> · climb 5 to enter top 1% →</>} />
          <PodiumBoard rows={TEACHER_BOARD} icon="crown"  iconCls="gold" title="Beat the Teacher" sub="All ages · all subjects"       meta="3 teachers ahead of every student →" />
        </div>

        {/* Your position card */}
        <div className="wc-card" style={{ margin: '14px 20px', padding: '22px 26px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
            <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--adv-rose)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--adv-display)', fontWeight: 800, fontSize: 22, boxShadow: '0 3px 0 var(--adv-rose-deep)' }}>KJ</div>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: 1.4, textTransform: 'uppercase', color: 'var(--adv-plum)' }}>Your week so far</div>
              <div style={{ fontFamily: 'var(--adv-display)', fontSize: 22, fontWeight: 800, color: 'var(--adv-ink)', marginTop: 2 }}>
                4,420 pts <span style={{ fontSize: 14, color: 'var(--adv-ink-soft)', fontWeight: 600 }}>· #4 at Northvale · #84 in NSW</span>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button className="wc-cta wc-cta-rose"><Icon name="play"/> Improve your score</button>
              <button className="wc-cta wc-cta-soft">My profile</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HubV1, HubV2, SCHOOL_BOARD, YEAR_BOARD, TEACHER_BOARD, LbRow, initials });
