// Bill detail page — bill metadata, action timeline, vote breakdown,
// and where the money flowed.

const BILLS = {
  "hr7024": {
    id: "hr7024",
    number: "H.R. 7024",
    congress: "118th Congress",
    title: "Tax Relief for American Families and Workers Act of 2024",
    short: "Tax Relief Act",
    introduced: "2024-01-17",
    status: "Stalled in Senate",
    statusTone: "warn",
    sponsor: { name: "Jason Smith", party: "Republican", state: "MO", district: "8" },
    cosponsors: { total: 19, byParty: { Democrat: 9, Republican: 10 } },
    summary:
      "Expands the Child Tax Credit through 2025, restores immediate expensing for R&D and capital investment, extends the low-income housing tax credit, and accelerates the wind-down of the Employee Retention Credit program to offset costs.",
    keyPoints: [
      "Restores immediate R&D expensing through 2025 (§174)",
      "Expands refundability of the Child Tax Credit",
      "Extends 100% bonus depreciation through 2025",
      "Ends Employee Retention Credit early to fund the package",
    ],
    timeline: [
      { date: "2024-01-17", body: "House Ways & Means", action: "Introduced by Rep. Smith" },
      { date: "2024-01-19", body: "House Ways & Means", action: "Markup; reported favorably (40–3)" },
      { date: "2024-01-31", body: "House floor",         action: "Passed House under suspension (357–70)" },
      { date: "2024-02-01", body: "U.S. Senate",         action: "Received from House; referred to Finance" },
      { date: "2024-08-01", body: "U.S. Senate",         action: "Cloture motion failed (48–44, 60 required)" },
      { date: "2024-12-19", body: "U.S. Senate",         action: "No further action this Congress" },
    ],
    vote: {
      chamber: "House",
      date: "2024-01-31",
      result: "Passed",
      yea: 357, nay: 70, present: 1, notVoting: 4,
      byParty: [
        { party: "Democrat",   yea: 188, nay: 23 },
        { party: "Republican", yea: 169, nay: 47 },
      ],
    },
    lobbying: [
      { industry: "Real Estate",          for: "$14.2M", against: "$0.3M", net: 0.97 },
      { industry: "Accounting",           for: "$9.8M",  against: "$0.0",  net: 1.00 },
      { industry: "Manufacturing",        for: "$8.4M",  against: "$0.4M", net: 0.95 },
      { industry: "Pharmaceuticals",      for: "$6.1M",  against: "$1.2M", net: 0.84 },
      { industry: "Defense electronics",  for: "$4.9M",  against: "$0.1M", net: 0.98 },
      { industry: "Consumer advocacy",    for: "$0.4M",  against: "$2.6M", net: -0.74 },
      { industry: "Tax preparers",        for: "$0.2M",  against: "$3.1M", net: -0.88 },
    ],
    contrib: {
      yes: { avgFromSupporters: 78400, avgFromOpponents: 18200 },
      no:  { avgFromSupporters: 21900, avgFromOpponents: 41700 },
    },
    quickFacts: [
      { l: "Cost over 10 years",       v: "$78B"  },
      { l: "Children covered (CTC)",   v: "~16M"  },
      { l: "Vote margin in House",     v: "+287"  },
      { l: "Lobbying for vs. against", v: "12 : 1" },
    ],
  },
};

function BillDetail({ id = "hr7024", onNavigate }) {
  const b = BILLS[id] || BILLS.hr7024;
  return (
    <div className="cv-bill" data-screen-label={`05 Bill · ${b.number}`}>
      <BillHeader b={b} onNavigate={onNavigate} />
      <BillQuickFacts b={b} />
      <div className="cv-bill-grid">
        <BillTimeline b={b} />
        <BillVote b={b} />
      </div>
      <BillLobbying b={b} />
      <BillMoneyByVote b={b} />
      <BillFootnote/>
    </div>
  );
}

// ─── Header ─────────────────────────────────────────────────────────────
function BillHeader({ b, onNavigate }) {
  return (
    <header className="cv-bill-hd">
      <div className="cv-bill-hd-eyebrow">
        <button className="cv-bill-back" onClick={() => onNavigate("home")}>← Back</button>
        <span className="cv-bill-hd-meta">
          <span className="cv-bill-num">{b.number}</span>
          <span className="cv-bill-hd-dot">·</span>
          <span>{b.congress}</span>
        </span>
        <span className={`cv-bill-status cv-bill-status-${b.statusTone}`}>{b.status}</span>
      </div>
      <h1 className="cv-bill-title">{b.title}</h1>
      <div className="cv-bill-sub">
        <span className="cv-bill-sub-l">Introduced by</span>
        <span className="cv-bill-sub-sponsor">
          <PartyTag party={b.sponsor.party}/>
          <button className="cv-link" onClick={() => onNavigate("politician", { id: "aoc" })}>
            {b.sponsor.name}
          </button>
          <span className="cv-bill-sub-dist">({b.sponsor.party[0]}-{b.sponsor.state}-{b.sponsor.district})</span>
        </span>
        <span className="cv-bill-hd-dot">·</span>
        <span>{fmtDate(b.introduced)}</span>
        <span className="cv-bill-hd-dot">·</span>
        <span>
          <strong>{b.cosponsors.total}</strong> cosponsors
          <span className="cv-bill-cosp"> ({b.cosponsors.byParty.Democrat} D · {b.cosponsors.byParty.Republican} R)</span>
        </span>
      </div>
      <div className="cv-bill-summary">
        <h4 className="cv-h4">What it does</h4>
        <p className="cv-bill-sum-p">{b.summary}</p>
        <ul className="cv-bill-keys">
          {b.keyPoints.map((k, i) => (
            <li key={i}><span className="cv-bill-key-bullet">§</span> {k}</li>
          ))}
        </ul>
        <SourceLink label="Full bill text (Congress.gov)" />
      </div>
    </header>
  );
}

// ─── Quick facts ────────────────────────────────────────────────────────
function BillQuickFacts({ b }) {
  return (
    <div className="cv-bill-facts">
      {b.quickFacts.map((f, i) => (
        <div key={i} className="cv-bill-fact">
          <div className="cv-bill-fact-l">{f.l}</div>
          <div className="cv-bill-fact-v">{f.v}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Timeline ───────────────────────────────────────────────────────────
function BillTimeline({ b }) {
  return (
    <section className="cv-bill-card">
      <header className="cv-sec-hd">
        <div>
          <h3 className="cv-sec-title">Action timeline</h3>
          <p className="cv-sec-sub">Every official action, from introduction to last status.</p>
        </div>
        <SourceLink label="Congress.gov" />
      </header>
      <ol className="cv-bill-tl">
        {b.timeline.map((t, i) => (
          <li key={i} className={`cv-bill-tl-row ${i === b.timeline.length - 1 ? "cv-bill-tl-last" : ""}`}>
            <span className="cv-bill-tl-dot" aria-hidden="true"/>
            <span className="cv-bill-tl-date">{fmtDate(t.date)}</span>
            <span className="cv-bill-tl-body">
              <span className="cv-bill-tl-action">{t.action}</span>
              <span className="cv-bill-tl-where">{t.body}</span>
            </span>
          </li>
        ))}
      </ol>
    </section>
  );
}

// ─── Vote breakdown ─────────────────────────────────────────────────────
function BillVote({ b }) {
  const v = b.vote;
  const total = v.yea + v.nay + v.present + v.notVoting;
  return (
    <section className="cv-bill-card">
      <header className="cv-sec-hd">
        <div>
          <h3 className="cv-sec-title">Floor vote · {v.chamber}</h3>
          <p className="cv-sec-sub">{fmtDate(v.date)} · <strong>{v.result}</strong></p>
        </div>
        <SourceLink label="Roll call" />
      </header>
      <div className="cv-bill-vote-bars">
        <VoteBar label="Yea" count={v.yea} total={total} tone="yea" />
        <VoteBar label="Nay" count={v.nay} total={total} tone="nay" />
        {v.present > 0 && <VoteBar label="Present" count={v.present} total={total} tone="present" />}
        {v.notVoting > 0 && <VoteBar label="Not voting" count={v.notVoting} total={total} tone="nv" />}
      </div>
      <h4 className="cv-h4">Crosstabs · by party</h4>
      <div className="cv-bill-party-tabs">
        {v.byParty.map((row, i) => (
          <BillPartyRow key={i} row={row}/>
        ))}
      </div>
    </section>
  );
}

function VoteBar({ label, count, total, tone }) {
  const pct = (count / total) * 100;
  return (
    <div className={`cv-bill-vote-row cv-bill-vote-${tone}`}>
      <span className="cv-bill-vote-l">{label}</span>
      <span className="cv-bill-vote-bar"><span style={{ width: `${pct}%` }}/></span>
      <span className="cv-bill-vote-n">{count}</span>
    </div>
  );
}

function BillPartyRow({ row }) {
  const total = row.yea + row.nay;
  const yeaPct = (row.yea / total) * 100;
  return (
    <div className="cv-bill-pty">
      <span className="cv-bill-pty-name">
        <PartyTag party={row.party}/>
        <span>{row.party}s</span>
      </span>
      <span className="cv-bill-pty-bar">
        <span className="cv-bill-pty-fill" style={{ width: `${yeaPct}%` }}/>
      </span>
      <span className="cv-bill-pty-counts">
        <span className="cv-bill-pty-y">{row.yea} Y</span>
        <span className="cv-bill-pty-sep">/</span>
        <span className="cv-bill-pty-n">{row.nay} N</span>
      </span>
    </div>
  );
}

// ─── Lobbying around this bill ──────────────────────────────────────────
function BillLobbying({ b }) {
  return (
    <section className="cv-bill-card">
      <header className="cv-sec-hd">
        <div>
          <h3 className="cv-sec-title">Money around this bill</h3>
          <p className="cv-sec-sub">Industries that disclosed lobbying activity on this bill, by side.</p>
        </div>
        <SourceLink label="Senate LDA filings" />
      </header>
      <div className="cv-bill-lob">
        <div className="cv-bill-lob-hd">
          <span>Industry</span>
          <span>For</span>
          <span>vs.</span>
          <span>Against</span>
        </div>
        {b.lobbying.map((row, i) => {
          const f = parseFloat(row.for.replace(/[^0-9.]/g, ""));
          const a = parseFloat(row.against.replace(/[^0-9.]/g, ""));
          const max = Math.max(...b.lobbying.map(r => Math.max(parseFloat(r.for.replace(/[^0-9.]/g, "")), parseFloat(r.against.replace(/[^0-9.]/g, "")))));
          return (
            <div key={i} className="cv-bill-lob-row">
              <span className="cv-bill-lob-ind">{row.industry}</span>
              <span className="cv-bill-lob-for">
                <span className="cv-bill-lob-amt">{row.for}</span>
                <span className="cv-bill-lob-bar">
                  <span style={{ width: `${(f / max) * 100}%` }}/>
                </span>
              </span>
              <span className="cv-bill-lob-vs">·</span>
              <span className="cv-bill-lob-against">
                <span className="cv-bill-lob-bar cv-bill-lob-bar-r">
                  <span style={{ width: `${(a / max) * 100}%` }}/>
                </span>
                <span className="cv-bill-lob-amt">{row.against}</span>
              </span>
            </div>
          );
        })}
      </div>
    </section>
  );
}

// ─── Money by vote ──────────────────────────────────────────────────────
function BillMoneyByVote({ b }) {
  const c = b.contrib;
  return (
    <section className="cv-bill-card">
      <header className="cv-sec-hd">
        <div>
          <h3 className="cv-sec-title">Donor patterns by vote</h3>
          <p className="cv-sec-sub">
            Average prior-cycle contributions to <strong>Yea</strong> and <strong>Nay</strong> voters,
            from the industries lobbying on either side.
          </p>
        </div>
        <SourceLink label="FEC × LDA crosswalk" />
      </header>
      <div className="cv-bill-corr">
        <div className="cv-bill-corr-side cv-bill-corr-yes">
          <div className="cv-bill-corr-lbl">Yea voters received, on average</div>
          <div className="cv-bill-corr-pair">
            <div className="cv-bill-corr-row">
              <span>from supporting industries</span>
              <span className="cv-bill-corr-num">${c.yes.avgFromSupporters.toLocaleString()}</span>
            </div>
            <div className="cv-bill-corr-row cv-bill-corr-muted">
              <span>from opposing industries</span>
              <span className="cv-bill-corr-num">${c.yes.avgFromOpponents.toLocaleString()}</span>
            </div>
          </div>
        </div>
        <div className="cv-bill-corr-side cv-bill-corr-no">
          <div className="cv-bill-corr-lbl">Nay voters received, on average</div>
          <div className="cv-bill-corr-pair">
            <div className="cv-bill-corr-row cv-bill-corr-muted">
              <span>from supporting industries</span>
              <span className="cv-bill-corr-num">${c.no.avgFromSupporters.toLocaleString()}</span>
            </div>
            <div className="cv-bill-corr-row">
              <span>from opposing industries</span>
              <span className="cv-bill-corr-num">${c.no.avgFromOpponents.toLocaleString()}</span>
            </div>
          </div>
        </div>
      </div>
      <div className="cv-bill-corr-foot">
        <SourceIcon/>
        Correlation, not causation. These are aggregate averages across all voters in each
        bucket — useful as a signal, not a verdict. Click any voter on the roll call to see
        their individual itemized contributions.
      </div>
    </section>
  );
}

function BillFootnote() {
  return (
    <footer className="cv-card-footnote cv-bill-footnote">
      <SourceIcon/>
      Bill data from Congress.gov. Roll-call data from the House &amp; Senate clerks.
      Lobbying activity from Senate LDA filings (§207 reports). Contribution averages from FEC itemized data.
    </footer>
  );
}

Object.assign(window, { BillDetail, BILLS });
