/* global React */
const { useState: useS, useEffect: useE, useMemo: useM } = React;

/* ============================= HOME ============================= */
function HomePage({ nav }) {
  const D = window.PT_DATA;
  const latestSitting = D.SITTINGS[D.SITTINGS.length - 1];
  const featured = D.SPEECHES.find(s => s.sittingId === latestSitting.id && s.topics.some(t => t.slug === 'corruption'))
    || D.SPEECHES.find(s => s.sittingId === latestSitting.id);
  const todaySpeeches = D.SPEECHES.filter(s => s.sittingId === latestSitting.id).slice(0, 6);
  const mostActive = D.TOP_MPS.slice(0, 5);
  const topTopics = [...D.TOPICS].sort((a, b) => b.count - a.count);

  return (
    <div className="shell">
      {/* Edition strip */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '18px 0 14px', borderBottom: '1px solid var(--rule)', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)' }}>
        <span>{fmtDateLong(latestSitting.date).toUpperCase()} · EDITION No. 47</span>
        <span>10TH PARLIAMENT · SESSION 2 · SITTING {latestSitting.id}</span>
        <span style={{ display: 'none' }} className="hide-sm">{D.STATS.totalSpeeches.toLocaleString()} SPEECHES INDEXED</span>
      </div>

      {/* Hero */}
      <section style={{ padding: '36px 0 0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 64, alignItems: 'start' }} className="hero-grid">
          <div>
            <div className="kicker" style={{ color: 'var(--accent)', marginBottom: 10 }}>Latest from the chamber</div>
            <h1 className="serif" style={{ fontSize: 54, lineHeight: 1.04, fontWeight: 600, letterSpacing: '-0.025em', margin: 0, textWrap: 'balance' }}>
              What your Parliament said this week — on the record, in plain English.
            </h1>
            <p className="serif" style={{ fontSize: 18, lineHeight: 1.5, color: 'var(--ink-2)', marginTop: 20, marginBottom: 24, maxWidth: '60ch', textWrap: 'pretty' }}>
              Every speech from every MP in every sitting, summarised, tagged, and searchable. Built on the official Hansard.
              Find your MP, follow the issues you care about, and read what was actually said.
            </p>
            <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
              <button className="btn accent" onClick={() => nav('mps')}>Find your MP →</button>
              <button className="btn" onClick={() => nav('search')}>Search the record</button>
              <span style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)', marginLeft: 4 }}>
                or press <span style={{ border: '1px solid var(--rule)', padding: '1px 5px' }}>/</span>
              </span>
            </div>
          </div>

          <aside style={{ borderLeft: '1px solid var(--rule)', paddingLeft: 32 }}>
            <div className="kicker" style={{ marginBottom: 14 }}>Parliament Pulse · last 8 sittings</div>
            <PulseRibbon sittings={D.SITTINGS} nav={nav} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, marginTop: 16 }}>
              <div className="stat"><span className="n tnum">{D.STATS.totalSpeeches.toLocaleString()}</span><span className="l">Speeches</span></div>
              <div className="stat"><span className="n tnum">{D.STATS.totalMps}</span><span className="l">Members</span></div>
              <div className="stat"><span className="n tnum">{D.STATS.totalSittings}</span><span className="l">Sittings</span></div>
              <div className="stat"><span className="n tnum">{D.STATS.totalTopics}</span><span className="l">Policy areas</span></div>
            </div>
          </aside>
        </div>
      </section>

      {/* Featured speech */}
      <section style={{ marginTop: 56, borderTop: '2px solid var(--ink)', paddingTop: 24, display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 48 }} className="featured-grid">
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>Featured · {fmtDate(featured.sittingDate)}</div>
          <h2 className="serif" style={{ fontSize: 30, lineHeight: 1.15, fontWeight: 600, letterSpacing: '-0.015em', margin: 0 }}>
            “{featured.summary}”
          </h2>
          <div style={{ marginTop: 16, display: 'flex', gap: 8, alignItems: 'center' }}>
            {featured.mp && (
              <>
                <a href="#" onClick={(e) => { e.preventDefault(); nav('mp', { id: featured.mp.id }); }} className="serif" style={{ fontWeight: 600 }}>
                  {featured.mp.name}
                </a>
                <PartyChip party={featured.mp.party} />
                <span className="hair">·</span>
                <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{featured.mp.district}</span>
              </>
            )}
          </div>
          <div style={{ marginTop: 14, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {featured.topics.map(t => <TopicTag key={t.id} topic={t} onClick={(tt) => nav('topic', { slug: tt.slug })} />)}
          </div>
        </div>
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>Also on {fmtDate(latestSitting.date)}</div>
          <div>
            {todaySpeeches.slice(1, 5).map(s => (
              <a key={s.id} href="#" onClick={(e) => { e.preventDefault(); nav('speech', { id: s.id }); }}
                style={{ display: 'grid', gridTemplateColumns: '120px 1fr auto', gap: 12, padding: '12px 0', borderTop: '1px solid var(--rule)', alignItems: 'start' }}>
                <span className="serif" style={{ fontSize: 14, fontWeight: 600 }}>{s.mp?.name.split(' ').slice(-1)[0]}</span>
                <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>{s.summary.slice(0, 120)}{s.summary.length > 120 ? '…' : ''}</span>
                <span className="mono hair" style={{ fontSize: 10 }}>#{s.speechOrder}</span>
              </a>
            ))}
          </div>
          <a href="#" onClick={(e) => { e.preventDefault(); nav('sitting', { date: latestSitting.date }); }} className="mono" style={{ fontSize: 11, marginTop: 12, display: 'inline-block', color: 'var(--ink-3)' }}>
            full sitting record →
          </a>
        </div>
      </section>

      {/* Two-column: topics + most active MPs */}
      <section style={{ marginTop: 56, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48 }} className="hero-grid">
        <div>
          <div className="section-head">
            <h2>Policy areas</h2>
            <span className="kicker-r">18 topics · {fmtN(D.STATS.totalSpeeches)} tagged</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 24px' }}>
            {topTopics.map(t => (
              <a key={t.id} href="#" onClick={(e) => { e.preventDefault(); nav('topic', { slug: t.slug }); }}
                style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 8, padding: '10px 0', borderTop: '1px solid var(--rule)', alignItems: 'baseline' }}>
                <span className="serif" style={{ fontSize: 16 }}>{t.name}</span>
                <span className="mono hair" style={{ fontSize: 12 }}>{t.count}</span>
              </a>
            ))}
          </div>
        </div>
        <div>
          <div className="section-head">
            <h2>Most active members</h2>
            <span className="kicker-r">by speech count · this session</span>
          </div>
          <div>
            {mostActive.map((mp, i) => (
              <a key={mp.id} href="#" onClick={(e) => { e.preventDefault(); nav('mp', { id: mp.id }); }}
                style={{ display: 'grid', gridTemplateColumns: '28px 1fr 130px 60px', gap: 12, padding: '12px 0', borderTop: '1px solid var(--rule)', alignItems: 'center' }}>
                <span className="mono hair" style={{ fontSize: 12 }}>{String(i + 1).padStart(2, '0')}</span>
                <div>
                  <div className="serif" style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>{mp.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>
                    <PartyChip party={mp.party} /> <span className="hair">·</span> {mp.district}
                  </div>
                </div>
                <Sparkline values={mp.activity} width={130} height={22} color="var(--ink-2)" />
                <span className="mono tnum" style={{ fontSize: 14, textAlign: 'right' }}>{mp.speechCount}</span>
              </a>
            ))}
          </div>
        </div>
      </section>

      {/* Recent sittings */}
      <section style={{ marginTop: 56 }}>
        <div className="section-head">
          <h2>Recent sittings</h2>
          <a href="#" onClick={(e) => { e.preventDefault(); nav('sittings'); }} className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>all sittings →</a>
        </div>
        <table className="ptable">
          <thead>
            <tr>
              <th>Date</th>
              <th>Session</th>
              <th className="num">Speeches</th>
              <th>Top topics</th>
            </tr>
          </thead>
          <tbody>
            {[...D.SITTINGS].reverse().map(s => {
              const sitSpeeches = D.SPEECHES.filter(sp => sp.sittingId === s.id);
              const topicCounts = {};
              sitSpeeches.forEach(sp => sp.topics.forEach(t => topicCounts[t.slug] = (topicCounts[t.slug] || 0) + 1));
              const top = Object.entries(topicCounts).sort((a,b) => b[1]-a[1]).slice(0, 3).map(([slug]) => D.TOPICS.find(t => t.slug === slug));
              return (
                <tr key={s.id} onClick={() => nav('sitting', { date: s.date })} style={{ cursor: 'pointer' }}>
                  <td className="mono">{fmtDate(s.date)}</td>
                  <td style={{ color: 'var(--ink-3)' }}>{s.session}</td>
                  <td className="num">{s.speechCount}</td>
                  <td>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      {top.map(t => t && <span key={t.slug} className="tag-topic">{t.short}</span>)}
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </section>
    </div>
  );
}

/* Pulse ribbon — novel view */
function PulseRibbon({ sittings, nav }) {
  const [hover, setHover] = useS(null);
  const max = Math.max(...sittings.map(s => s.speechCount));
  return (
    <div>
      <div className="pulse-row">
        {sittings.map(s => {
          const h = (s.speechCount / max) * 56;
          return (
            <div
              key={s.id}
              className={'pulse-bar' + (hover?.id === s.id ? ' active' : '')}
              style={{ height: h }}
              onMouseEnter={() => setHover(s)}
              onMouseLeave={() => setHover(null)}
              onClick={() => nav('sitting', { date: s.date })}
              title={`${s.date} · ${s.speechCount} speeches`}
            />
          );
        })}
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-4)', marginTop: 6 }}>
        <span>{fmtDate(sittings[0].date).split(' ').slice(0, 2).join(' ')}</span>
        <span style={{ color: hover ? 'var(--accent)' : 'var(--ink-3)' }}>
          {hover ? `${fmtDate(hover.date)} · ${hover.speechCount} speeches` : 'hover to inspect'}
        </span>
        <span>{fmtDate(sittings[sittings.length - 1].date).split(' ').slice(0, 2).join(' ')}</span>
      </div>
    </div>
  );
}

Object.assign(window, { HomePage, PulseRibbon });
