/* global React */

/* ============================= SITTING ============================= */
function SittingPage({ date, nav }) {
  const D = window.PT_DATA;
  const sitting = D.SITTINGS.find(s => s.date === date) || D.SITTINGS[D.SITTINGS.length - 1];
  const speeches = D.SPEECHES.filter(s => s.sittingId === sitting.id);

  // group by debate
  const byDebate = {};
  speeches.forEach(s => { (byDebate[s.debate] = byDebate[s.debate] || []).push(s); });
  const debateOrder = Object.keys(byDebate);

  // topic counts for this sitting
  const topicCount = {};
  speeches.forEach(s => s.topics.forEach(t => topicCount[t.slug] = (topicCount[t.slug] || 0) + 1));
  const topTopics = Object.entries(topicCount).sort((a,b)=>b[1]-a[1]).slice(0, 6).map(([slug, n]) => ({ topic: D.TOPICS.find(t=>t.slug===slug), n }));

  const idx = D.SITTINGS.findIndex(s => s.id === sitting.id);
  const prev = D.SITTINGS[idx - 1];
  const next = D.SITTINGS[idx + 1];

  return (
    <div className="shell">
      <div style={{ padding: '18px 0 12px', display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)' }}>
        <a href="#" onClick={(e)=>{e.preventDefault();nav('sittings');}}>← all sittings</a>
        <div>
          {prev && <a href="#" onClick={(e)=>{e.preventDefault();nav('sitting',{date:prev.date});}}>← {fmtDate(prev.date)}</a>}
          {prev && next && <span style={{ margin: '0 12px', color: 'var(--ink-4)' }}>·</span>}
          {next && <a href="#" onClick={(e)=>{e.preventDefault();nav('sitting',{date:next.date});}}>{fmtDate(next.date)} →</a>}
        </div>
      </div>

      <header style={{ borderTop: '2px solid var(--ink)', borderBottom: '1px solid var(--rule)', padding: '28px 0' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>Sitting record · {sitting.session}</div>
        <h1 className="serif" style={{ fontSize: 52, lineHeight: 1.05, fontWeight: 600, letterSpacing: '-0.025em', margin: 0 }}>
          {fmtDateLong(sitting.date)}
        </h1>
        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '140px 140px 1fr', gap: 24, alignItems: 'baseline' }}>
          <div><div className="n serif tnum" style={{ fontSize: 28 }}>{speeches.length}</div><div className="l kicker">Speeches</div></div>
          <div><div className="n serif tnum" style={{ fontSize: 28 }}>{new Set(speeches.map(s => s.mp.id)).size}</div><div className="l kicker">Members spoke</div></div>
          <div>
            <div className="kicker" style={{ marginBottom: 6 }}>Top topics today</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {topTopics.map(x => (
                <a key={x.topic.slug} href="#" onClick={(e)=>{e.preventDefault();nav('topic',{slug:x.topic.slug});}} className="tag-topic">
                  {x.topic.short} <span className="mono hair" style={{ marginLeft: 4 }}>{x.n}</span>
                </a>
              ))}
            </div>
          </div>
        </div>
      </header>

      {/* Agenda / debates */}
      <section style={{ padding: '28px 0' }}>
        <div className="section-head">
          <h2>Order of business</h2>
          <span className="kicker-r">{debateOrder.length} items</span>
        </div>
        {debateOrder.map((dbt, i) => (
          <div key={dbt} style={{ padding: '22px 0', borderTop: '1px solid var(--rule)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 18 }}>
              <span className="mono hair" style={{ fontSize: 12, paddingTop: 6 }}>{String(i+1).padStart(2,'0')}</span>
              <div>
                <h3 className="serif" style={{ fontSize: 22, fontWeight: 600, margin: 0, letterSpacing: '-0.01em' }}>{dbt}</h3>
                <div className="mono hair" style={{ fontSize: 11, marginTop: 4 }}>{byDebate[dbt].length} speeches</div>
                <div style={{ marginTop: 14 }}>
                  {byDebate[dbt].slice(0, 4).map(s => <SpeechItem key={s.id} speech={s} showDate={false} nav={nav} />)}
                  {byDebate[dbt].length > 4 && (
                    <a href="#" style={{ fontSize: 11, fontFamily: 'var(--mono)', color: 'var(--ink-3)', marginTop: 10, display: 'inline-block' }}>
                      + {byDebate[dbt].length - 4} more speeches
                    </a>
                  )}
                </div>
              </div>
            </div>
          </div>
        ))}
      </section>
    </div>
  );
}

/* ============================= SPEECH ============================= */
function SpeechPage({ id, nav }) {
  const D = window.PT_DATA;
  const speech = D.SPEECHES.find(s => s.id === Number(id)) || D.SPEECHES[0];
  const sitting = D.SITTINGS.find(s => s.id === speech.sittingId);
  // fake but plausible full text
  const fullText = `Mr. Speaker, I rise today to speak on a matter of urgent public interest. ${speech.summary} The House will recall that the relevant Minister undertook, in response to my question on the 14th of February, to provide a written reply within fourteen days. That reply has not been forthcoming.

The position of the Hon. Member opposite, with respect, fails to take into account the most recent data published by the Department of Census and Statistics. I would draw the attention of the House to page twelve of the most recent Bulletin, which sets out in clear terms the trend I have described.

Mr. Speaker, I move accordingly that this House takes note of the serious concerns raised by the constituents of my district, and calls upon the Honourable Minister to lay before Parliament, within fourteen sitting days, a comprehensive statement of the government's position and the steps it proposes to take.

I thank you, Mr. Speaker.`;

  // adjacent speeches in same sitting
  const sittingSpeeches = D.SPEECHES.filter(s => s.sittingId === speech.sittingId);
  const idxIn = sittingSpeeches.findIndex(s => s.id === speech.id);
  const prev = sittingSpeeches[idxIn - 1];
  const next = sittingSpeeches[idxIn + 1];

  return (
    <div className="shell" style={{ maxWidth: 980 }}>
      <div style={{ padding: '18px 0 12px', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)' }}>
        <a href="#" onClick={(e)=>{e.preventDefault();nav('sitting',{date:sitting.date});}}>← {fmtDate(sitting.date)} sitting</a>
      </div>

      <header style={{ borderTop: '2px solid var(--ink)', borderBottom: '1px solid var(--rule)', padding: '28px 0' }}>
        <div className="kicker" style={{ marginBottom: 10 }}>{speech.debate} · Speech #{speech.speechOrder}</div>
        <h1 className="serif" style={{ fontSize: 38, lineHeight: 1.15, fontWeight: 600, letterSpacing: '-0.015em', margin: 0, textWrap: 'balance' }}>
          “{speech.summary}”
        </h1>
        <div style={{ marginTop: 22, display: 'flex', gap: 14, alignItems: 'baseline', flexWrap: 'wrap' }}>
          <a href="#" onClick={(e)=>{e.preventDefault();nav('mp',{id:speech.mp.id});}} className="serif" style={{ fontSize: 20, fontWeight: 600 }}>
            {speech.mp.name}
          </a>
          <PartyChip party={speech.mp.party} />
          <span className="hair">·</span>
          <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{speech.mp.district}</span>
          <span className="hair">·</span>
          <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{fmtDate(sitting.date)}</span>
        </div>
        <div style={{ marginTop: 14, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {speech.topics.map(t => <TopicTag key={t.id} topic={t} onClick={(tt) => nav('topic', { slug: tt.slug })} />)}
        </div>
      </header>

      {/* AI summary banner */}
      <div style={{ margin: '24px 0 0', padding: '14px 18px', background: 'var(--paper-2)', borderLeft: '3px solid var(--accent)', display: 'grid', gridTemplateColumns: '80px 1fr', gap: 16 }}>
        <div className="kicker" style={{ color: 'var(--accent)' }}>AI Summary</div>
        <p className="serif" style={{ margin: 0, fontSize: 15, lineHeight: 1.5, color: 'var(--ink-2)' }}>{speech.summary}</p>
      </div>

      {/* Full text */}
      <article style={{ padding: '32px 0', columnCount: 1 }}>
        <div className="kicker" style={{ marginBottom: 16 }}>Verbatim Hansard</div>
        <div className="serif" style={{ fontSize: 18, lineHeight: 1.65, color: 'var(--ink)', maxWidth: '68ch', textWrap: 'pretty' }}>
          {fullText.split('\n\n').map((p, i) => (
            <p key={i} style={{ margin: i === 0 ? '0 0 1em' : '0 0 1em', textIndent: i === 0 ? 0 : '1.5em' }}>
              {i === 0 ? <span className="kicker" style={{ marginRight: 8 }}>¶ 01</span> : <span className="mono hair" style={{ marginRight: 8, fontSize: 10 }}>¶ {String(i+1).padStart(2,'0')}</span>}
              {p}
            </p>
          ))}
        </div>
      </article>

      {/* Footer: provenance + prev/next */}
      <footer style={{ borderTop: '1px solid var(--rule)', paddingTop: 16, marginBottom: 24, display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-3)' }}>
        <span className="mono">Source: Hansard {fmtDate(sitting.date)} · p.{ (idxIn * 2 + 3) } · col.{idxIn % 2 === 0 ? 'L' : 'R'}</span>
        <span>
          {prev && <a href="#" onClick={(e)=>{e.preventDefault();nav('speech',{id:prev.id});}}>← previous</a>}
          {prev && next && <span style={{ margin: '0 12px' }}>·</span>}
          {next && <a href="#" onClick={(e)=>{e.preventDefault();nav('speech',{id:next.id});}}>next →</a>}
        </span>
      </footer>
    </div>
  );
}

Object.assign(window, { SittingPage, SpeechPage });
