/* global React */

/* ============================= MP PROFILE ============================= */
function MpPage({ id, nav }) {
  const D = window.PT_DATA;
  const mp = D.MPS.find(m => m.id === Number(id)) || D.TOP_MPS[0];
  const speeches = D.SPEECHES.filter(s => s.mp.id === mp.id).slice(0, 12);
  // Rank among party and overall
  const sortedAll = D.TOP_MPS;
  const rankAll = sortedAll.findIndex(m => m.id === mp.id) + 1;
  const rankParty = D.MPS.filter(m => m.party.id === mp.party.id).sort((a,b)=>b.speechCount-a.speechCount).findIndex(m => m.id === mp.id) + 1;
  return (
    <div className="shell">
      <div style={{ padding: '18px 0 12px', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)' }}>
        <a href="#" onClick={(e)=>{e.preventDefault();nav('mps');}}>← all members</a>
      </div>

      <div style={{ borderTop: '2px solid var(--ink)', borderBottom: '1px solid var(--rule)', padding: '24px 0', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 48 }} className="hero-grid">
        <div>
          <div className="kicker" style={{ marginBottom: 8 }}>Member of Parliament · {mp.isActive ? 'Active' : 'Inactive'}</div>
          <h1 className="serif" style={{ fontSize: 54, lineHeight: 1.0, fontWeight: 600, letterSpacing: '-0.025em', margin: 0 }}>{mp.name}</h1>
          <div style={{ marginTop: 14, display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap', fontSize: 14 }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="party-dot" style={{ background: mp.party.color, width: 10, height: 10 }} />
              <span className="serif" style={{ fontWeight: 600 }}>{mp.party.name}</span>
              <span className="hair">({mp.party.abbr})</span>
            </span>
            <span className="hair">·</span>
            <span>{mp.district} District</span>
            <span className="hair">·</span>
            <span>10th Parliament</span>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 0 }}>
          <div className="stat"><span className="n tnum">{mp.speechCount}</span><span className="l">Speeches</span></div>
          <div className="stat"><span className="n tnum">#{rankAll}</span><span className="l">Overall rank</span></div>
          <div className="stat"><span className="n tnum">#{rankParty}</span><span className="l">In {mp.party.abbr}</span></div>
        </div>
      </div>

      {/* Activity + topic breakdown */}
      <section style={{ padding: '28px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 48 }} className="hero-grid">
        <div>
          <div className="kicker" style={{ marginBottom: 12 }}>Activity by sitting</div>
          <ActivityChart mp={mp} sittings={D.SITTINGS} nav={nav} />
        </div>
        <div>
          <div className="kicker" style={{ marginBottom: 12 }}>Topic focus</div>
          <HBar
            items={mp.topicBreakdown.map(tb => ({ label: tb.topic.name, value: tb.count, slug: tb.topic.slug }))}
            onClick={(it) => nav('topic', { slug: it.slug })}
          />
          <p style={{ marginTop: 14, fontSize: 12, color: 'var(--ink-3)' }}>
            AI-assigned topic tags across {mp.speechCount} speeches. A speech can hold up to three topics.
          </p>
        </div>
      </section>

      {/* Speeches */}
      <section>
        <div className="section-head">
          <h2>Recent speeches</h2>
          <span className="kicker-r">{speeches.length} of {mp.speechCount}</span>
        </div>
        <div>
          {speeches.map(s => (
            <SpeechItem key={s.id} speech={s} showMp={false} showDate={true} nav={nav} />
          ))}
        </div>
      </section>

      {/* Related MPs */}
      <section style={{ marginTop: 48 }}>
        <div className="section-head">
          <h2>Others from {mp.party.abbr}</h2>
          <a href="#" onClick={(e)=>{e.preventDefault();nav('mps', { party: mp.party.abbr });}} className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>all {mp.party.abbr} members →</a>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0 }} className="grid-4">
          {D.MPS.filter(m => m.party.id === mp.party.id && m.id !== mp.id).slice(0, 4).map(m => (
            <a key={m.id} href="#" onClick={(e)=>{e.preventDefault();nav('mp',{id:m.id});}}
              style={{ padding: 16, borderTop: '1px solid var(--rule)', borderRight: '1px solid var(--rule)' }}>
              <div className="serif" style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em' }}>{m.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 2 }}>{m.district}</div>
              <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <Sparkline values={m.activity} width={80} height={16} color="var(--ink-3)" />
                <span className="mono tnum" style={{ fontSize: 12 }}>{m.speechCount}</span>
              </div>
            </a>
          ))}
        </div>
      </section>
    </div>
  );
}

function ActivityChart({ mp, sittings, nav }) {
  const max = Math.max(...mp.activity, 1);
  const W = 420, H = 140, PAD = 24;
  const step = (W - PAD * 2) / (sittings.length - 1 || 1);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block', border: '1px solid var(--rule)' }}>
      {/* gridlines */}
      {[0, 0.5, 1].map(g => (
        <line key={g} x1={PAD} x2={W - PAD} y1={PAD + (H - PAD * 2) * g} y2={PAD + (H - PAD * 2) * g} stroke="var(--rule)" strokeDasharray="2 3" />
      ))}
      {/* bars */}
      {mp.activity.map((v, i) => {
        const h = (v / max) * (H - PAD * 2);
        const x = PAD + i * step - 8;
        return (
          <g key={i} style={{ cursor: 'pointer' }} onClick={() => nav('sitting', { date: sittings[i].date })}>
            <rect x={x} y={H - PAD - h} width={16} height={h} fill="var(--accent)" />
            <text x={x + 8} y={H - 6} fontSize="9" textAnchor="middle" fill="var(--ink-3)" fontFamily="var(--mono)">
              {sittings[i].date.slice(5)}
            </text>
            <text x={x + 8} y={H - PAD - h - 4} fontSize="10" textAnchor="middle" fill="var(--ink-2)" fontFamily="var(--mono)">{v || ''}</text>
          </g>
        );
      })}
    </svg>
  );
}

/* ============================= TOPIC ============================= */
function TopicPage({ slug, nav }) {
  const D = window.PT_DATA;
  const topic = D.TOPICS.find(t => t.slug === slug) || D.TOPICS[0];
  const speeches = D.SPEECHES.filter(s => s.topics.some(t => t.slug === topic.slug)).slice(0, 10);
  // top MPs for topic
  const mpCount = {};
  D.SPEECHES.filter(s => s.topics.some(t => t.slug === topic.slug)).forEach(s => {
    mpCount[s.mp.id] = (mpCount[s.mp.id] || 0) + 1;
  });
  const topMps = Object.entries(mpCount).sort((a,b) => b[1]-a[1]).slice(0, 6).map(([id, c]) => ({ mp: D.MPS.find(m => m.id === Number(id)), count: c }));
  // party breakdown from matrix
  const partyRow = D.TOPIC_PARTY_MATRIX.find(r => r.topic === topic.slug);
  const partyBreakdown = D.PARTIES.map(p => ({
    label: p.abbr, value: Math.round((partyRow.values[p.abbr] || 0) * topic.count),
    color: p.color
  })).filter(x => x.value > 0).sort((a, b) => b.value - a.value);

  const idx = D.TOPICS.findIndex(t => t.slug === topic.slug);
  const prev = D.TOPICS[(idx - 1 + D.TOPICS.length) % D.TOPICS.length];
  const next = D.TOPICS[(idx + 1) % D.TOPICS.length];

  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('topics');}}>← all topics</a>
        <div>
          <a href="#" onClick={(e)=>{e.preventDefault();nav('topic',{slug:prev.slug});}}>← {prev.short}</a>
          <span style={{ margin: '0 12px', color: 'var(--ink-4)' }}>·</span>
          <a href="#" onClick={(e)=>{e.preventDefault();nav('topic',{slug:next.slug});}}>{next.short} →</a>
        </div>
      </div>

      <header style={{ borderTop: '2px solid var(--ink)', borderBottom: '1px solid var(--rule)', padding: '28px 0' }}>
        <div className="kicker" style={{ marginBottom: 8 }}>Topic · {String(idx + 1).padStart(2,'0')} of 18</div>
        <h1 className="serif" style={{ fontSize: 64, lineHeight: 1.0, fontWeight: 600, letterSpacing: '-0.025em', margin: 0, textWrap: 'balance' }}>
          {topic.name}
        </h1>
        <div style={{ marginTop: 18, display: 'flex', gap: 40, alignItems: 'baseline', fontSize: 14 }}>
          <span><strong className="mono tnum" style={{ fontSize: 18 }}>{topic.count}</strong> <span className="muted">speeches tagged</span></span>
          <span><strong className="mono tnum" style={{ fontSize: 18 }}>{topMps.length}+</strong> <span className="muted">members speaking</span></span>
          <span><strong className="mono tnum" style={{ fontSize: 18 }}>{partyBreakdown.length}</strong> <span className="muted">parties engaged</span></span>
        </div>
      </header>

      {/* Two-col: top MPs + party breakdown */}
      <section style={{ padding: '28px 0', display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 48 }} className="hero-grid">
        <div>
          <div className="kicker" style={{ marginBottom: 12 }}>Most vocal on this topic</div>
          <div>
            {topMps.map((x, i) => (
              <a key={x.mp.id} href="#" onClick={(e)=>{e.preventDefault();nav('mp',{id:x.mp.id});}}
                style={{ display: 'grid', gridTemplateColumns: '28px 1fr auto auto', gap: 14, padding: '10px 0', borderTop: '1px solid var(--rule)', alignItems: 'center' }}>
                <span className="mono hair">{String(i+1).padStart(2,'0')}</span>
                <div>
                  <div className="serif" style={{ fontSize: 16, fontWeight: 600 }}>{x.mp.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)' }}><PartyChip party={x.mp.party} /> · {x.mp.district}</div>
                </div>
                <span className="mono hair" style={{ fontSize: 11 }}>of {x.mp.speechCount}</span>
                <span className="mono tnum" style={{ fontSize: 14 }}>{x.count}</span>
              </a>
            ))}
          </div>
        </div>
        <div>
          <div className="kicker" style={{ marginBottom: 12 }}>Where it's coming from · by party</div>
          <HBar items={partyBreakdown} colorKey="color" />
          <p style={{ marginTop: 14, fontSize: 12, color: 'var(--ink-3)' }}>
            Share of speeches tagged <em>{topic.short}</em> by the MP's party. Includes multi-tagged speeches.
          </p>
        </div>
      </section>

      <section>
        <div className="section-head">
          <h2>Recent speeches</h2>
          <span className="kicker-r">{speeches.length} of {topic.count}</span>
        </div>
        {speeches.map(s => <SpeechItem key={s.id} speech={s} showDate={true} nav={nav} />)}
      </section>
    </div>
  );
}

Object.assign(window, { MpPage, TopicPage, ActivityChart });
