// Politician Card — the full "baseball card" with all 6 tabs.

function PoliticianCard({ id, onCompare, onNavigate, density = "regular" }) {
  const p = window.CV_DATA.POLITICIANS[id];
  const [tab, setTab] = React.useState("votes");
  const [scope, setScope] = React.useState("current");
  const [pickerOpen, setPickerOpen] = React.useState(false);
  if (!p) return <div style={{ padding: 40 }}>Unknown politician.</div>;

  const party = partyOf(p.party);
  const goBill = (ref) => onNavigate && onNavigate("bill", { id: "hr7024" });
  const openPicker = () => setPickerOpen(true);

  // Conditionally include tabs based on what data exists. Challengers without
  // a voting record skip "Votes"; candidates without ratings skip "Accountability".
  const hasCareer = (p.career || []).length > 0 || (p.fundraisingHistory || []).length > 0;
  const hasVotes = (p.votes || []).length > 0;
  const hasMoney = p.raised != null;
  const hasTrades = p.chamber === "House" || p.chamber === "Senate"; // sitting members get the section
  const hasLobbying = !!p.lobbying;
  const hasAccountability = (p.ratings || []).length > 0 || (p.investigations || []).length > 0 || (p.id === "cruz");
  const hasPromises = (p.promises || []).length > 0;

  const tabs = [
    hasCareer         && { label: "Career",         value: "career"         },
    hasVotes          && { label: "Votes",          value: "votes"          },
    hasMoney          && { label: "Money",          value: "money"          },
    hasPromises       && { label: "Promises",       value: "promises", count: (p.promises || []).filter(pr => pr.status === "reversed").length || null },
    hasTrades         && { label: "Trades",         value: "trades",   count: p.trades?.lateFilings || null },
    hasLobbying       && { label: "Lobbying",       value: "lobbying"       },
    hasAccountability && { label: "Accountability", value: "accountability", count: p.conflicts || null },
    { label: "Contact", value: "contact" },
  ].filter(Boolean);

  // If the default tab isn't valid for this politician, pick the first one
  React.useEffect(() => {
    if (!tabs.find(t => t.value === tab)) setTab(tabs[0]?.value || "contact");
  }, [tabs.map(t => t.value).join(",")]);

  return (
    <article className={`cv-card cv-d-${density}`} data-screen-label={`Politician · ${p.name}`}>
      <CardHeader p={p} party={party} onCompare={openPicker} />
      <StatsRow p={p} />
      {p.conflicts > 0 && (
        <button
          type="button"
          className="cv-conflict-bar"
          onClick={() => setTab("accountability")}
        >
          <ConflictIcon />
          <span><b>{p.conflicts}</b> potential conflict{p.conflicts > 1 ? "s" : ""} detected</span>
          <span className="cv-conflict-cta">View details →</span>
        </button>
      )}
      <div className="cv-card-tabs">
        <Tabs items={tabs} value={tab} onChange={setTab} />
      </div>
      <div className="cv-tab-pane">
        {tab === "career"         && <TabCareer p={p} onNavigate={onNavigate} />}
        {tab === "votes"          && <TabVotes p={p} onPickBill={goBill} scope={scope} onScope={setScope} />}
        {tab === "money"          && <TabMoney p={p} scope={scope} onScope={setScope} />}
        {tab === "promises"       && <TabPromises p={p} onPickBill={goBill} scope={scope} onScope={setScope} />}
        {tab === "trades"         && <TabTrades p={p} scope={scope} onScope={setScope} />}
        {tab === "lobbying"       && <TabLobbying p={p} scope={scope} onScope={setScope} />}
        {tab === "accountability" && <TabAccountability p={p} scope={scope} onScope={setScope} />}
        {tab === "contact"        && <TabContact p={p} />}
      </div>
      <CardFootnote />
      <ComparePicker
        open={pickerOpen}
        anchor={id}
        lineup={[{ id }]}
        onChange={() => {}}
        onClose={() => setPickerOpen(false)}
        onCompare={(ids) => {
          setPickerOpen(false);
          onNavigate && onNavigate("vs", { ids });
        }}
      />
    </article>
  );
}

// ─── Header ─────────────────────────────────────────────────────────────
function CardHeader({ p, party, onCompare }) {
  const dist = p.district ? `${p.state}-${p.district}` : p.state;
  return (
    <header className="cv-card-hd">
      <div className="cv-card-hd-l">
        <Avatar photo={p.photo} name={p.name} size={92} shape="rounded" party={p.party} />
        <div className="cv-card-hd-meta">
          <div className="cv-card-hd-eyebrow">
            <PartyTag party={p.party} />
            <span className="cv-card-hd-office">{p.office}</span>
            <span className="cv-card-hd-dot">·</span>
            <span className="cv-card-hd-dist">{dist}</span>
          </div>
          <h1 className="cv-card-hd-name">{p.name}</h1>
          <div className="cv-card-hd-tenure">
            {p.candidate
              ? <>Candidate · no prior elected office · 1st run</>
              : <>In office since {p.since} · {p.years} year{p.years === 1 ? "" : "s"}</>}
          </div>
        </div>
      </div>
      <div className="cv-card-hd-r">
        <div className="cv-card-stamp" aria-hidden="true">
          <div className="cv-stamp-label">CLARION FILE</div>
          <div className="cv-stamp-id">№ {p.id.toUpperCase().slice(0, 8).padEnd(8, "·")}</div>
          <div className="cv-stamp-yr">{p.candidate ? "CANDIDATE" : `EST. ${p.since}`}</div>
        </div>
        <div className="cv-card-hd-actions">
          <CVButton variant="ghost" onClick={onCompare}>
            <CompareIcon /> Compare
          </CVButton>
          <CVButton variant="ghost" onClick={() => {}}>
            <ShareIcon /> Share
          </CVButton>
        </div>
      </div>
    </header>
  );
}

// ─── Stats row ──────────────────────────────────────────────────────────
function StatsRow({ p }) {
  if (p.candidate) {
    return (
      <div className="cv-stats-row">
        <StatBlock label={<Term name="fec">Total Raised</Term>} value={`$${p.raised}`} hint="current cycle" />
        <StatBlock label={<Term name="small-dollar">Small-dollar</Term>} value={p.smallDollar ?? "—"} suffix={p.smallDollar != null ? "%" : ""} hint="of total" />
        <StatBlock label={<Term name="pac-share">PAC share</Term>} value={p.pacShare ?? "—"} suffix={p.pacShare != null ? "%" : ""} hint="from PACs" />
        <StatBlock label="Status" value="Active" hint="on the ballot" tone="high" />
      </div>
    );
  }
  return (
    <div className="cv-stats-row">
      <StatBlock label={<Term name="tenure">Years in Office</Term>} value={p.years} hint={`since ${p.since}`} />
      <StatBlock label={<Term name="party-loyalty">Party Loyalty</Term>} value={p.loyalty} suffix="%" hint="votes with party"
                 tone={p.loyalty >= 90 ? "high" : p.loyalty >= 75 ? "mid" : "low"} />
      <StatBlock label={<Term name="missed-votes">Missed Votes</Term>} value={p.missed} suffix="%" hint="current Congress"
                 tone={p.missed <= 3 ? "high" : p.missed <= 8 ? "mid" : "low"} />
      <StatBlock label={<Term name="fec">Total Raised</Term>} value={`$${p.raised}`} hint={`${p.cycles || "this"} cycle${p.cycles && p.cycles > 1 ? "s" : ""}`} />
    </div>
  );
}

// ─── Tab: Votes ─────────────────────────────────────────────────────────
function TabVotes({ p, onPickBill, scope, onScope }) {
  const votes = p.votes || [];
  const careerTotal = (p.careerStats && p.careerStats.officesHeld ? 1872 : 412);
  const shown = scope === "career" ? Math.min(votes.length, 12) : Math.min(votes.length, 8);
  const visible = votes.slice(0, shown);
  return (
    <section>
      <SectionHead
        title="Recent floor votes"
        sub={<>Voted on {scope === "career" ? `${careerTotal.toLocaleString()} measures across their entire career` : `412 measures this Congress`} · {p.loyalty}% <Term name="party-loyalty">with party</Term></>}
        right={<SourceButton label="House Clerk roll-call" />}
      />
      {onScope && <ScopeToggle scope={scope} onChange={onScope} hint={scope === "career" ? "Every roll call across every office held" : "118th Congress only"}/>}
      <div className="cv-votes">
        <div className="cv-vote-hd">
          <span>Bill</span>
          <span>Title</span>
          <span className="cv-vote-pos">Vote</span>
          <span className="cv-vote-date">Date</span>
        </div>
        {votes.length === 0 && (
          <EmptyState text="No recent floor votes for this politician." />
        )}
        {visible.map((v, i) => (
          <div key={i} className="cv-vote-row">
            <button className="cv-vote-bill cv-vote-cell" onClick={() => onPickBill(v.bill)}>{v.bill}</button>
            <button className="cv-vote-title cv-vote-cell" onClick={() => onPickBill(v.bill)}>
              <span className="cv-vote-title-l">{v.title}</span>
              <span className="cv-vote-outcome">{v.outcome}</span>
            </button>
            <span className="cv-vote-pos"><VoteBadge position={v.position} /></span>
            <span className="cv-vote-date">{fmtDate(v.date)}</span>
            <span className="cv-vote-src"><SourceLink label="record" /></span>
          </div>
        ))}
      </div>
      <div className="cv-section-foot">
        <a className="cv-link" href="#" onClick={(e) => e.preventDefault()}>View all 412 →</a>
      </div>
    </section>
  );
}

// ─── Tab: Money ─────────────────────────────────────────────────────────
function TabMoney({ p, scope, onScope }) {
  const donors = p.topDonors || [];
  const industries = p.topIndustries || [];
  const small = p.smallDollar ?? 50;
  const pac = p.pacShare ?? 10;
  const isCareer = scope === "career";
  const fundHistory = p.fundraisingHistory || [];
  const careerStats = p.careerStats || {};
  return (
    <section>
      <SectionHead
        title="Campaign finance"
        sub={<>All figures from the <Term name="fec">Federal Election Commission</Term> · {isCareer ? "every cycle they've ever run" : "current cycle"}</>}
        right={<SourceButton label="FEC filings" />}
      />
      {onScope && <ScopeToggle scope={scope} onChange={onScope} hint={isCareer ? "Across all reported cycles" : "Most recent reporting cycle"}/>}
      <div className="cv-money-top">
        <div className="cv-money-big">
          <div className="cv-money-big-l">{isCareer ? "Lifetime raised" : "Total raised (cycle)"}</div>
          <div className="cv-money-big-v">
            <span className="cv-money-big-curr">$</span>
            <span className="cv-money-big-num">{isCareer && careerStats.lifetimeRaised ? `${careerStats.lifetimeRaised}M` : p.raised}</span>
          </div>
          <div className="cv-money-big-h">
            {isCareer
              ? `across ${careerStats.cyclesRun || p.cycles || 1} cycle${(careerStats.cyclesRun || p.cycles || 1) > 1 ? "s" : ""}`
              : `current reporting cycle`}
          </div>
        </div>
        <div className="cv-money-bars">
          <div className="cv-money-bar">
            <div className="cv-money-bar-h">
              <span><Term name="small-dollar">Small-dollar (under $200)</Term></span>
              <span>Large donors</span>
            </div>
            <RatioBar
              left={small} right={100 - small}
              leftLabel="small" rightLabel="large"
              leftColor="var(--cv-accent)" rightColor="var(--cv-ink-2)"
            />
          </div>
          <div className="cv-money-bar">
            <div className="cv-money-bar-h">
              <span>Individuals</span>
              <span><Term name="pac-share">PACs</Term></span>
            </div>
            <RatioBar
              left={100 - pac} right={pac}
              leftLabel="ind." rightLabel="PAC"
              leftColor="var(--cv-ink)" rightColor="#A93232"
            />
          </div>
        </div>
      </div>
      {isCareer && fundHistory.length > 1 && (
        <>
          <h4 className="cv-h4"><span>Fundraising by cycle</span><span className="cv-h4-sub">FEC history</span></h4>
          <FundraisingHistory entries={fundHistory}/>
        </>
      )}
      <div className="cv-money-grid">
        <div className="cv-money-col">
          <h4 className="cv-h4">Top donors <span className="cv-h4-sub">(employers)</span></h4>
          <ol className="cv-list">
            {donors.map((d, i) => (
              <li key={i} className="cv-list-row">
                <span className="cv-list-rank">{i + 1}</span>
                <span className="cv-list-main">
                  <span className="cv-list-name">{d.name}</span>
                  <span className="cv-list-sub">{d.employer}</span>
                </span>
                <span className="cv-list-amt">{d.amount}</span>
                <SourceLink label="" />
              </li>
            ))}
            {donors.length === 0 && <EmptyState text="No itemized donors disclosed yet for this cycle." />}
          </ol>
        </div>
        <div className="cv-money-col">
          <h4 className="cv-h4">Top industries</h4>
          <ol className="cv-list">
            {industries.map((d, i) => (
              <li key={i} className="cv-list-row">
                <span className="cv-list-rank">{i + 1}</span>
                <span className="cv-list-main">
                  <span className="cv-list-name">{d.name}</span>
                </span>
                <span className="cv-list-amt">{d.amount}</span>
                <SourceLink label="" />
              </li>
            ))}
            {industries.length === 0 && <EmptyState text="Industry breakdown not yet classified." />}
          </ol>
        </div>
      </div>
    </section>
  );
}

// ─── Tab: Trades ────────────────────────────────────────────────────────
function TabTrades({ p, scope, onScope }) {
  const t = p.trades || { total: 0, lateFilings: 0, overlaps: 0, list: [] };
  // Disclosure availability rule (mocked — backend will return this).
  // Federal sitting members are required to file PTRs. Candidates / state-local
  // officials get the "why no data" treatment from the brief.
  const fed = p.chamber === "House" || p.chamber === "Senate";
  const jurisdictionalGap = !fed && !p.candidate;
  return (
    <section>
      <SectionHead
        title="Stock & asset trades"
        sub={<><Term name="ptr">Periodic Transaction Reports</Term> filed under the <Term name="stock-act">STOCK Act</Term>.</>}
        right={<SourceButton label="House Clerk PTR archive" />}
      />
      {onScope && fed && <ScopeToggle scope={scope} onChange={onScope} hint={scope === "career" ? "Every PTR filed across their tenure" : "Current Congress only"}/>}
      {jurisdictionalGap ? (
        <div className="cv-disc-gap">
          <div className="cv-disc-gap-hd">
            <span className="cv-disc-gap-icon" aria-hidden="true">⚠</span>
            <div>
              <div className="cv-disc-gap-l">Why no disclosures appear here</div>
              <div className="cv-disc-gap-sub">
                {p.state} does not require {p.office?.toLowerCase().includes("state") ? "state legislators" : "officials at this level"} to disclose individual stock trades or financial interests in a public registry.
              </div>
            </div>
          </div>
          <div className="cv-disc-gap-actions">
            <CVButton variant="primary" onClick={() => {}}><FoiaIcon/> Generate FOIA request</CVButton>
            <CVButton variant="ghost" onClick={() => {}}><MailIcon/> Email this official asking to disclose</CVButton>
          </div>
          <div className="cv-disc-gap-foot">
            ClarionVote will draft the public-records request letter for you, addressed to the correct agency. You review and send.
          </div>
        </div>
      ) : (
        <>
          <div className="cv-trade-stats">
            <StatBlock small label="Reported trades"    value={t.total}        hint={scope === "career" ? "career total" : "this Congress"} />
            <StatBlock small label="Late filings"       value={t.lateFilings}  hint=">45 days" tone={t.lateFilings > 0 ? "low" : "high"} />
            <StatBlock small label="Committee overlaps" value={t.overlaps}     hint="traded sector matches assignment" tone={t.overlaps > 0 ? "mid" : "high"} />
          </div>
          {t.total === 0 ? (
            <EmptyState
              text="No PTRs filed for this politician under the STOCK Act."
              detail="An empty record is itself a fact: this politician has not disclosed any individual trades during their current term."
            />
          ) : (
            <div className="cv-trade-table">
              <div className="cv-trade-hd">
                <span>Asset</span><span>Side</span><span>Date</span><span>Amount</span><span>Disc. lag</span>
              </div>
              {t.list.map((tr, i) => (
                <div key={i} className="cv-trade-row">
                  <span className="cv-trade-asset">{tr.asset}</span>
                  <span className={`cv-trade-side cv-trade-${tr.side?.toLowerCase()}`}>{tr.side}</span>
                  <span>{fmtDate(tr.date)}</span>
                  <span>{tr.range}</span>
                  <span className={tr.lag > 45 ? "cv-trade-late" : ""}>{tr.lag}d</span>
                </div>
              ))}
            </div>
          )}
        </>
      )}
    </section>
  );
}

function FoiaIcon() { return <svg width="13" height="13" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="2" y="1.5" width="8" height="11" stroke="currentColor" strokeWidth="1.3"/><line x1="4" y1="4" x2="8" y2="4" stroke="currentColor" strokeWidth="1.3"/><line x1="4" y1="6" x2="8" y2="6" stroke="currentColor" strokeWidth="1.3"/><line x1="4" y1="8" x2="6" y2="8" stroke="currentColor" strokeWidth="1.3"/></svg>; }
function MailIcon() { return <svg width="13" height="13" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="1.5" y="3" width="11" height="8" stroke="currentColor" strokeWidth="1.3"/><path d="M1.5 4L7 8L12.5 4" stroke="currentColor" strokeWidth="1.3"/></svg>; }

// ─── Tab: Lobbying ──────────────────────────────────────────────────────
function TabLobbying({ p, scope, onScope }) {
  const l = p.lobbying;
  const foreign = window.CV_DATA.FOREIGN_LOBBYING || [];
  const foreignFor = foreign.filter(f => f.politicianIds.includes(p.id));
  const foreignPacs = window.CV_DATA.FOREIGN_PACS || [];
  if (!l) {
    return (
      <section>
        <SectionHead title="Lobbying influence" sub="Lobbying directed at this politician's committees." />
        <EmptyState text="Lobbying data not yet aggregated for this politician." />
      </section>
    );
  }
  return (
    <section>
      <SectionHead
        title="Lobbying influence"
        sub={`${l.total} directed at the committees this politician sits on, this Congress.`}
        right={<SourceButton label="Senate LDA reports" />}
      />
      {onScope && <ScopeToggle scope={scope} onChange={onScope} hint={scope === "career" ? "Every lobbying relationship across their tenure" : "Current Congress only"}/>}
      <div className="cv-lob-meta">
        <span className="cv-meta-lbl">Committees:</span>
        {l.committees.map((c) => (
          <span key={c} className="cv-pill">{c}</span>
        ))}
      </div>
      <h4 className="cv-h4">Top lobbying firms</h4>
      <div className="cv-lob-firms">
        {l.firms.map((f, i) => (
          <div key={i} className="cv-lob-firm">
            <div className="cv-lob-firm-name">{f.name}</div>
            <div className="cv-lob-firm-meta">{f.issues}</div>
            <div className="cv-lob-firm-spend">{f.spend}</div>
            <SourceLink label="filing" />
          </div>
        ))}
      </div>
      <h4 className="cv-h4">Revolving door</h4>
      <div className="cv-lob-revolve">
        {l.revolvingDoor.length === 0 ? (
          <EmptyState text="No former staff currently registered as lobbyists." />
        ) : (
          l.revolvingDoor.map((r, i) => (
            <div key={i} className="cv-revolve-row">
              <span className="cv-revolve-name">{r.name}</span>
              <span className="cv-revolve-arrow">
                <span className="cv-revolve-was">{r.was}</span>
                <span className="cv-revolve-mid">→</span>
                <span className="cv-revolve-now">{r.now}</span>
              </span>
              <SourceLink label="registration" />
            </div>
          ))
        )}
      </div>
      <h4 className="cv-h4">
        <span>Foreign agents <span className="cv-h4-tag">FARA</span></span>
        <span className="cv-h4-sub">targeting their committees</span>
      </h4>
      {foreignFor.length === 0 ? (
        <EmptyState text="No registered foreign agents currently lobbying this politician's committees." />
      ) : (
        <div className="cv-fara-list">
          {foreignFor.map((f, i) => (
            <div key={i} className="cv-fara-row">
              <span className="cv-fara-flag" aria-hidden="true">{f.flag}</span>
              <div className="cv-fara-meta">
                <div className="cv-fara-country">{f.country}</div>
                <div className="cv-fara-via">via <strong>{f.firm}</strong> — {f.committee}</div>
              </div>
              <span className="cv-fara-amount">{f.spend}/yr</span>
              <SourceLink label="FARA filing"/>
            </div>
          ))}
        </div>
      )}
      {foreignPacs.length > 0 && (
        <>
          <h4 className="cv-h4">Foreign-connected PAC contributions</h4>
          <div className="cv-fara-pacs">
            {foreignPacs.filter(fp => !fp.politicianIds || fp.politicianIds.includes(p.id)).map((fp, i) => (
              <div key={i} className="cv-fara-pac-row">
                <span className="cv-fara-flag" aria-hidden="true">{fp.flag}</span>
                <span className="cv-fara-pac-name">
                  <strong>{fp.pac}</strong>
                  <span> · subsidiary of {fp.parent} ({fp.country})</span>
                </span>
                <span className="cv-fara-pac-amt">{fp.amount}</span>
                <SourceLink label="FEC"/>
              </div>
            ))}
          </div>
        </>
      )}
    </section>
  );
}

// ─── Tab: Accountability ────────────────────────────────────────────────
function TabAccountability({ p, scope, onScope }) {
  const flags = (p.id === "cruz" ? window.CV_DATA.CONFLICTS_CRUZ : window.CV_DATA.CONFLICTS_AOC) || [];
  const ratings = p.ratings || [];
  return (
    <section>
      <SectionHead
        title="Accountability"
        sub="Flags from automated detection · interest-group ratings · ethics record."
        right={<SourceButton label="OCE & OGE filings" />}
      />
      {onScope && <ScopeToggle scope={scope} onChange={onScope} hint={scope === "career" ? "Every investigation, complaint, and rating across their career" : "Current term only"}/>}
      <h4 className="cv-h4">
        <span><Term name="conflict-flag">Conflict flags</Term></span>
      </h4>
      {flags.length === 0 ? (
        <div className="cv-conflict-empty">
          <CheckIcon /> No conflict flags detected from automated checks.
          <span className="cv-conflict-empty-hint">
            Absence of a flag is not absence of conflict — it means no automated rule matched.
          </span>
        </div>
      ) : (
        <div className="cv-conflicts">
          {flags.map((f, i) => (
            <div key={i} className="cv-conflict">
              <div className="cv-conflict-hd">
                <div className="cv-conflict-title">{f.title}</div>
                <span className={`cv-sev cv-sev-${f.severity.toLowerCase()}`}>{f.severity}</span>
              </div>
              <div className="cv-conflict-sum">{f.summary}</div>
              <div className="cv-conflict-ev">
                {f.evidence.map((ev, j) => <SourceLink key={j} label={ev} />)}
              </div>
            </div>
          ))}
        </div>
      )}
      <h4 className="cv-h4">
        <span><Term name="interest-group-rating">Interest-group ratings</Term></span>
        <span className="cv-h4-sub">{ratings.length} groups</span>
      </h4>
      {ratings.length === 0 && <EmptyState text="No interest-group ratings collected yet." />}
      <div className="cv-rrows">
        {ratings.map((r, i) => (
          <RatingRow key={i} group={r.group} category={r.category} score={r.score} />
        ))}
      </div>
      <h4 className="cv-h4">Ethics investigations</h4>
      {(p.investigations || []).length === 0 ? (
        <EmptyState text="No ethics investigations on file." />
      ) : (
        <div className="cv-timeline">
          {p.investigations.map((iv, i) => (
            <div key={i} className="cv-tl-row">
              <span className="cv-tl-date">{iv.date}</span>
              <span className="cv-tl-body">{iv.body}</span>
              <span className="cv-tl-action">{iv.action}</span>
              <SourceLink label="document" />
            </div>
          ))}
        </div>
      )}
      <h4 className="cv-h4">FEC enforcement</h4>
      {(p.fec || []).length === 0 ? (
        <EmptyState text="No open or closed FEC enforcement cases." />
      ) : (
        <div className="cv-fec">{/* would list cases */}</div>
      )}
    </section>
  );
}

// ─── Tab: Contact ───────────────────────────────────────────────────────
function TabContact({ p }) {
  const items = [
    { label: "Office",   value: p.address, icon: <PinIcon />     },
    { label: "Phone",    value: p.phone || "—", icon: <PhoneIcon /> },
    { label: "Website",  value: p.website || "—", icon: <GlobeIcon />, link: p.website ? `https://${p.website}` : null },
  ].filter(i => i.value && i.value !== "—" || i.label === "Office");

  const socials = [
    { name: "Twitter / X", handle: p.twitter,  icon: "𝕏" },
    { name: "Facebook",    handle: p.facebook,  icon: "f" },
    { name: "Instagram",   handle: p.instagram, icon: "◌" },
    { name: "YouTube",     handle: p.youtube,   icon: "▶" },
  ].filter(s => s.handle);

  return (
    <section>
      <SectionHead title="Contact" sub="Official channels only. Citizen contact is your strongest tool." />
      <div className="cv-contact-rows">
        {items.map((it, i) => (
          <div key={i} className="cv-contact-row">
            <span className="cv-contact-ico">{it.icon}</span>
            <span className="cv-contact-lbl">{it.label}</span>
            <span className="cv-contact-val">
              {it.link
                ? <a href={it.link} onClick={(e) => e.preventDefault()} className="cv-link">{it.value}</a>
                : it.value}
            </span>
          </div>
        ))}
      </div>
      {socials.length > 0 && (
        <>
          <h4 className="cv-h4">Social</h4>
          <div className="cv-socials">
            {socials.map((s, i) => (
              <a key={i} href="#" onClick={(e) => e.preventDefault()} className="cv-social">
                <span className="cv-social-ico" aria-hidden="true">{s.icon}</span>
                <span className="cv-social-meta">
                  <span className="cv-social-net">{s.name}</span>
                  <span className="cv-social-handle">@{s.handle}</span>
                </span>
              </a>
            ))}
          </div>
        </>
      )}
      <div className="cv-contact-note">
        <SourceIcon />
        Pulled from the official congressional directory. Mailing address may differ from district office.
      </div>
    </section>
  );
}

// ─── Helpers ────────────────────────────────────────────────────────────
function SectionHead({ title, sub, right }) {
  return (
    <header className="cv-sec-hd">
      <div>
        <h3 className="cv-sec-title">{title}</h3>
        {sub && <p className="cv-sec-sub">{sub}</p>}
      </div>
      {right && <div className="cv-sec-right">{right}</div>}
    </header>
  );
}

function EmptyState({ text, detail }) {
  return (
    <div className="cv-empty">
      <div className="cv-empty-text">{text}</div>
      {detail && <div className="cv-empty-detail">{detail}</div>}
    </div>
  );
}

function CardFootnote() {
  return (
    <footer className="cv-card-footnote">
      <SourceIcon />
      Data: U.S. House clerk, U.S. Senate clerk, FEC, OpenSecrets, Senate LDA, House Ethics. Updated daily.
      No opinion — just public records.
    </footer>
  );
}

function fmtDate(s) {
  if (!s) return "";
  const d = new Date(s);
  return d.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

// ─── Inline icons ───────────────────────────────────────────────────────
function ConflictIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true">
      <path d="M7 1.5L13 12H1L7 1.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
      <line x1="7" y1="5.5" x2="7" y2="8.5" stroke="currentColor" strokeWidth="1.4"/>
      <circle cx="7" cy="10.4" r="0.8" fill="currentColor"/>
    </svg>
  );
}
function CheckIcon() {
  return <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M2 7L6 11L12 3" stroke="currentColor" strokeWidth="1.6" strokeLinecap="square"/></svg>;
}
function CompareIcon() {
  return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true"><rect x="1" y="2" width="3.5" height="8" stroke="currentColor" strokeWidth="1.3"/><rect x="7.5" y="2" width="3.5" height="8" stroke="currentColor" strokeWidth="1.3"/></svg>;
}
function ShareIcon() {
  return <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true"><circle cx="3" cy="6" r="1.5" stroke="currentColor" strokeWidth="1.3"/><circle cx="9" cy="2.5" r="1.5" stroke="currentColor" strokeWidth="1.3"/><circle cx="9" cy="9.5" r="1.5" stroke="currentColor" strokeWidth="1.3"/><line x1="4.2" y1="5.3" x2="7.8" y2="3.2" stroke="currentColor" strokeWidth="1.3"/><line x1="4.2" y1="6.7" x2="7.8" y2="8.8" stroke="currentColor" strokeWidth="1.3"/></svg>;
}
function PinIcon()   { return <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M7 12.5C7 12.5 11.5 8.5 11.5 5.5C11.5 3 9.5 1 7 1C4.5 1 2.5 3 2.5 5.5C2.5 8.5 7 12.5 7 12.5Z" stroke="currentColor" strokeWidth="1.3"/><circle cx="7" cy="5.5" r="1.5" stroke="currentColor" strokeWidth="1.3"/></svg>; }
function PhoneIcon() { return <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M2.5 3C2.5 2 3 1.5 4 1.5L5.5 1.5L6.5 4L5 5.5C5 7 7 9 8.5 9L10 7.5L12.5 8.5V10C12.5 11 12 11.5 11 11.5C6 11.5 2.5 8 2.5 3Z" stroke="currentColor" strokeWidth="1.3"/></svg>; }
function GlobeIcon() { return <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><circle cx="7" cy="7" r="5.5" stroke="currentColor" strokeWidth="1.3"/><ellipse cx="7" cy="7" rx="2.2" ry="5.5" stroke="currentColor" strokeWidth="1.3"/><line x1="1.5" y1="7" x2="12.5" y2="7" stroke="currentColor" strokeWidth="1.3"/></svg>; }

// Wrap the card to attach the ComparePicker overlay.
Object.assign(window, { PoliticianCard });
