// LeadsDashboard.jsx — the Producer Co-pilot list screen.
// Header renamed to "Producer Co-pilot". Three insight cards reframed around the
// broadened tool, a segmented control that swaps the WHOLE table per lead type,
// and per-type columns. Clicking any row calls onSelectLead(lead).

const { useState: useDashState, useEffect: useDashEffect } = React;

// ----------------------------------------------------------------- avatar
const LeadAvatar = ({ lead, size = 26, radius }) => {
  const r = radius != null ? radius : Math.round(size * 0.28);
  if (lead.img)
    return <img src={lead.img} alt="" style={{ width: size, height: size, borderRadius: r, objectFit: "cover", flexShrink: 0 }} />;
  return (
    <div style={{
      width: size, height: size, borderRadius: r, background: "var(--helm-ecru)", color: "var(--helm-grey)",
      border: "1px solid var(--helm-dark-ecru)", display: "grid", placeItems: "center", fontFamily: "var(--font-sans)", fontWeight: 700,
      fontSize: Math.round(size * 0.36), flexShrink: 0,
    }}>{CP_initials(lead.name)}</div>
  );
};

// ----------------------------------------------------------------- score pill
const ScorePill = ({ score }) => {
  const p = CP_scoreTier(score);
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 24, borderRadius: 12, background: p.wrap, padding: "2px 12px 2px 2px" }}>
      <span style={{ minWidth: 34, height: 20, borderRadius: 11, background: p.chip, display: "grid", placeItems: "center", padding: "0 9px", fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13, color: p.text }}>{score}</span>
      <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, color: p.text }}>{p.label}</span>
    </span>
  );
};

// ----------------------------------------------------------------- phase chip
const PhaseChip = ({ phase }) => {
  const m = CP_PHASE_META[phase];
  if (!m) return null;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 24, borderRadius: 12, background: m.bg, padding: "0 11px", whiteSpace: "nowrap" }}>
      <span style={{ width: 7, height: 7, borderRadius: "50%", background: m.dot, flexShrink: 0 }} />
      <span style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 12.5, color: m.color }}>{m.label}</span>
    </span>
  );
};

// ----------------------------------------------------------------- header
const CoPilotHeader = ({ active = "Leads" }) => (
  <div style={{ position: "relative", width: "100%", height: 54, flexShrink: 0, display: "flex", alignItems: "center", padding: "0 24px", borderBottom: "1px solid var(--helm-dark-ecru)", background: "var(--helm-white)", zIndex: 5 }}>
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <img src="helm/logo/bannerlife-logo.png" alt="Banner Life" style={{ height: 20, display: "block" }} />
      <div style={{ width: 1, height: 20, background: "var(--helm-dark-ecru)" }} />
      <img src="helm/logo/helm-logotype-darkgreen.svg" alt="Helm" style={{ height: 17, display: "block" }} />
      <span style={{ fontFamily: "var(--font-serif)", fontSize: 15, color: "var(--helm-dark-green)", whiteSpace: "nowrap" }}>Producer Co-pilot</span>
    </div>
    <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 18, fontSize: 13 }}>
      {["Leads", "Campaigns", "Reports"].map((item) => (
        <span key={item} style={{ fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: active === item ? 700 : 500, color: active === item ? "var(--helm-dark-green)" : "var(--helm-dark-grey)", borderBottom: active === item ? "2px solid var(--helm-dark-green)" : "2px solid transparent", padding: "4px 2px" }}>{item}</span>
      ))}
      {window.ProfileMenu ? (
        <window.ProfileMenu initials="MP" bg="var(--helm-dark-green)" fg="var(--helm-white)" size={30}
          name="Morgan Pierce" subtitle="Producer" style={{ marginLeft: 4 }} />
      ) : (
        <div style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--helm-dark-green)", color: "var(--helm-white)", display: "grid", placeItems: "center", fontWeight: 600, fontSize: 12, marginLeft: 4 }}>MP</div>
      )}
    </div>
  </div>
);

// ----------------------------------------------------------------- stat cards
const StatLeadsCard = () => {
  const bars = [
    { m: "Dec", v: 0.46 }, { m: "Jan", v: 0.52 }, { m: "Feb", v: 0.6 },
    { m: "Mar", v: 0.7 }, { m: "Apr", v: 0.82 }, { m: "May", v: 0.96 },
  ];
  return (
    <div style={{ flex: "1 1 0", minWidth: 0, height: 196, borderRadius: 20, background: "var(--helm-orange)", border: "1px solid var(--helm-dark-green)", boxShadow: "4px 8px 0 0 var(--helm-dark-green)", padding: "18px 22px", position: "relative", overflow: "hidden" }}>
      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 800, fontSize: 40, lineHeight: "40px", color: "var(--helm-dark-green)", letterSpacing: "-0.02em" }}>132</div>
      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14, lineHeight: "18px", color: "var(--helm-dark-green)", marginTop: 6 }}>Active leads</div>
      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 12, color: "var(--helm-dark-green)", opacity: 0.7, marginTop: 2 }}>+38 in the last 30 days</div>
      <div style={{ position: "absolute", left: 22, right: 22, bottom: 16, height: 66, display: "flex", alignItems: "flex-end", gap: 8 }}>
        {bars.map((b) => (
          <div key={b.m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <div style={{ width: "100%", height: 48, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
              <div style={{ width: "100%", height: `${b.v * 48}px`, borderRadius: "3px 3px 0 0", background: "var(--helm-dark-orange)" }} />
            </div>
            <div style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 11, color: "var(--helm-dark-green)", opacity: 0.75 }}>{b.m}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

// donut showing the three-type lead mix
const MixDonut = () => {
  const segs = [
    { frac: 0.35, color: "var(--helm-dark-purple)" },  // post-claim bene
    { frac: 0.29, color: "#70B6BA" },                   // pre-claim bene
    { frac: 0.36, color: "var(--helm-chartreuse-2)" },  // policyholder gap
  ];
  const r = 64, c = 2 * Math.PI * r;
  let offset = 0;
  return (
    <svg width="112" height="112" viewBox="0 0 160 160">
      {segs.map((s, i) => {
        const len = s.frac * c;
        const el = <circle key={i} cx="80" cy="80" r={r} fill="none" stroke={s.color} strokeWidth="30" strokeDasharray={`${len - 4} ${c - len + 4}`} strokeDashoffset={-offset} transform="rotate(-90 80 80)" />;
        offset += len;
        return el;
      })}
      <circle cx="80" cy="80" r="44" fill="var(--helm-purple)" />
    </svg>
  );
};

const StatMixCard = () => {
  const legend = [
    { c: "var(--helm-dark-purple)", label: "Post-claim beneficiaries", n: 46 },
    { c: "#70B6BA", label: "Pre-claim beneficiaries", n: 38 },
    { c: "var(--helm-chartreuse-2)", label: "Policy owner gaps", n: 48 },
  ];
  return (
    <div style={{ flex: "1.5 1 0", minWidth: 0, height: 196, borderRadius: 20, background: "var(--helm-purple)", border: "1px solid var(--helm-dark-green)", boxShadow: "4px 8px 0 0 var(--helm-dark-green)", padding: "18px 22px", position: "relative", overflow: "hidden", display: "flex", alignItems: "center", gap: 18 }}>
      <div style={{ flexShrink: 0 }}><MixDonut /></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 15, lineHeight: "19px", color: "var(--helm-dark-green)" }}>Lead mix</div>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 12, color: "var(--helm-dark-green)", opacity: 0.72, marginTop: 2, marginBottom: 12 }}>Three pipelines, one inbox</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
          {legend.map((l) => (
            <div key={l.label} style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ width: 9, height: 9, borderRadius: "50%", background: l.c, flexShrink: 0 }} />
              <span style={{ flex: 1, fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13, color: "var(--helm-dark-green)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.label}</span>
              <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13, color: "var(--helm-dark-green)" }}>{l.n}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const TopScoreRow = ({ lead, onClick }) => {
  const [hover, setHover] = useDashState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", margin: "0 -8px", padding: "0 8px", borderRadius: 10, background: hover ? "rgba(0,29,0,0.06)" : "transparent", transition: "background 120ms ease" }}>
      <LeadAvatar lead={lead} size={28} radius={8} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13.5, lineHeight: "17px", color: "var(--helm-dark-green)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{lead.name}</div>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 11, lineHeight: "14px", color: "var(--helm-dark-green)", opacity: 0.65, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{CP_TYPE_META[lead.type].label}</div>
      </div>
      <span style={{ minWidth: 32, height: 22, borderRadius: 11, background: "var(--helm-dark-green)", color: "var(--helm-lemon)", display: "grid", placeItems: "center", fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13, flexShrink: 0 }}>{lead.score}</span>
    </div>
  );
};

const StatTopCard = ({ onSelectLead }) => {
  const top = [...CP_LEADS].sort((a, b) => b.score - a.score).slice(0, 3);
  return (
    <div style={{ flex: "1 1 0", minWidth: 0, height: 196, borderRadius: 20, background: "var(--helm-chartreuse)", border: "1px solid var(--helm-dark-green)", boxShadow: "4px 8px 0 0 var(--helm-dark-green)", padding: "16px 20px", position: "relative", overflow: "hidden", display: "flex", flexDirection: "column", gap: 9 }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8 }}>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 15, lineHeight: "19px", color: "var(--helm-dark-green)" }}>Top conversion scores</div>
        <div style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 12, color: "var(--helm-dark-green)", opacity: 0.7, whiteSpace: "nowrap" }}>Last 3 days</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 12, justifyContent: "space-between", flex: 1, minHeight: 0 }}>
        {top.map((l) => <TopScoreRow key={l.id} lead={l} onClick={() => onSelectLead && onSelectLead(l)} />)}
      </div>
    </div>
  );
};

// ----------------------------------------------------------------- segmented tabs
const TYPE_ORDER = ["policyholder_gap", "bene_pre", "bene_post"];
const TypeTabs = ({ active, onChange }) => (
  <div style={{ display: "inline-flex", background: "var(--helm-ecru)", border: "1px solid var(--helm-dark-ecru)", borderRadius: 22, padding: 4, gap: 2 }}>
    {TYPE_ORDER.map((t) => {
      const on = active === t;
      const count = CP_leadsByType(t).length;
      return (
        <button key={t} onClick={() => onChange(t)} style={{
          display: "inline-flex", alignItems: "center", gap: 8, height: 36, padding: "0 16px", borderRadius: 18, border: "none",
          background: on ? "var(--helm-dark-green)" : "transparent", color: on ? "var(--helm-white)" : "var(--helm-dark-grey)",
          fontFamily: "var(--font-sans)", fontWeight: on ? 700 : 600, fontSize: 13.5, cursor: "pointer", whiteSpace: "nowrap", transition: "background 140ms ease, color 140ms ease",
        }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: on ? CP_TYPE_META[t].color : "var(--helm-dark-ecru)", flexShrink: 0 }} />
          {CP_TYPE_META[t].tab}
          <span style={{ minWidth: 20, height: 20, borderRadius: 10, padding: "0 6px", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700, background: on ? "rgba(254,252,245,0.18)" : "var(--helm-dark-ecru)", color: on ? "var(--helm-white)" : "var(--helm-dark-grey)" }}>{count}</span>
        </button>
      );
    })}
  </div>
);

// ----------------------------------------------------------------- column configs
const M = CP_money;
const CampaignCell = ({ lead }) => lead.campaign
  ? <CampaignChip c={lead.campaign} />
  : <span style={{ color: "var(--helm-grey)" }}>—</span>;

const COLUMNS = {
  bene_post: {
    grid: "40px 224fr 183fr 157fr 176fr 158fr 174fr 203fr",
    cols: [
      { label: "Beneficiary name", get: (l) => <NameCell lead={l} /> },
      { label: "Policy owner", get: (l) => l.owner },
      { label: "Payout amount", get: (l) => M(l.received) },
      { label: "Payout date", get: (l) => l.payout },
      { label: "Identified need", get: (l) => l.engaged === false
          ? <span title="Not engaged with Helm planning" style={{ color: "var(--helm-grey)", fontWeight: 600 }}>N/A</span>
          : M(l.recCoverage) },
      { label: "Campaign", get: (l) => <CampaignCell lead={l} /> },
      { label: "Conversion score", get: (l) => <ScorePill score={l.score} /> },
    ],
  },
  policyholder_gap: {
    grid: "40px 230fr 150fr 149fr 149fr 162fr 237fr 194fr",
    cols: [
      { label: "Policy owner name", get: (l) => <NameCell lead={l} /> },
      { label: "Policy #", get: (l) => l.policy },
      { label: "Coverage", get: (l) => M(l.currentCoverage) },
      { label: "Coverage gap", get: (l) => M(l.recCoverage - l.currentCoverage) },
      { label: "Campaign", get: (l) => <CampaignCell lead={l} /> },
      { label: "Lead phase", get: (l) => <PhaseChip phase={l.phase} /> },
      { label: "Conversion score", get: (l) => <ScorePill score={l.score} /> },
    ],
  },
  bene_pre: {
    grid: "40px 228fr 190fr 136fr 143fr 157fr 231fr 188fr",
    cols: [
      { label: "Beneficiary name", get: (l) => <NameCell lead={l} /> },
      { label: "Policy owner", get: (l) => l.owner },
      { label: "Relationship", get: (l) => l.relation },
      { label: "Identified need", get: (l) => M(l.recCoverage) },
      { label: "Campaign", get: (l) => <CampaignCell lead={l} /> },
      { label: "Lead phase", get: (l) => <PhaseChip phase={l.phase} /> },
      { label: "Conversion score", get: (l) => <ScorePill score={l.score} /> },
    ],
  },
};

const CampaignChip = ({ c }) => (
  <span title={`Active contact campaign · step ${c.stepN} of ${c.stepTotal}`} style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 21, borderRadius: 11, background: "rgba(255,184,118,0.32)", padding: "0 9px 0 8px", flexShrink: 0, whiteSpace: "nowrap" }}>
    <span className="cp-pulse" style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--helm-dark-orange)", flexShrink: 0 }} />
    <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 11.5, color: "var(--helm-dark-orange)" }}>Day {c.dayN}/{c.dayTotal}</span>
  </span>
);

const NameCell = ({ lead }) => (
  <span style={{ display: "inline-flex", alignItems: "center", gap: 10, minWidth: 0, width: "100%" }}>
    <LeadAvatar lead={lead} size={26} radius={7} />
    <span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", minWidth: 0 }}>{lead.name}</span>
  </span>
);

// ----------------------------------------------------------------- icons
const DropArrow = () => <svg width="11" height="6" viewBox="0 0 12.238 6.09" style={{ flexShrink: 0 }}><path d="M 6.119 6.09 L 0 0 L 12.238 0 Z" fill="var(--helm-grey)" /></svg>;
const Checkbox = ({ checked, indeterminate }) => {
  const on = checked || indeterminate;
  return (
    <span style={{ width: 22, height: 22, borderRadius: 5, flexShrink: 0, border: on ? "none" : "2px solid var(--helm-grey)", background: on ? "var(--helm-dark-green)" : "transparent", display: "grid", placeItems: "center" }}>
      {checked && <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--helm-white)" strokeWidth="3.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 6" /></svg>}
      {!checked && indeterminate && <span style={{ width: 11, height: 2.5, borderRadius: 2, background: "var(--helm-white)" }} />}
    </span>
  );
};

// ----------------------------------------------------------------- table
const BulkBtn = ({ onClick, variant, icon, children }) => {
  const styles = {
    primary: { background: "var(--helm-chartreuse-2)", color: "var(--helm-white)", border: "none" },
    soft: { background: "rgba(254,252,245,0.14)", color: "var(--helm-white)", border: "none" },
    ghost: { background: "transparent", color: "var(--helm-white)", border: "1px solid rgba(254,252,245,0.32)" },
  }[variant];
  return (
    <button onClick={onClick} style={{ display: "inline-flex", alignItems: "center", gap: 7, height: 34, padding: "0 14px", borderRadius: 17, fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13.5, cursor: "pointer", whiteSpace: "nowrap", ...styles }}>
      {icon}{children}
    </button>
  );
};

const LeadsTable = ({ type, onSelectLead, onToast }) => {
  const config = COLUMNS[type];
  const [sel, setSel] = useDashState({});
  const [archived, setArchived] = useDashState({});
  const [hover, setHover] = useDashState(null);
  useDashEffect(() => { setSel({}); }, [type]);

  const rows = CP_leadsByType(type).filter((r) => !archived[r.id]);
  const toggle = (id) => setSel((s) => ({ ...s, [id]: !s[id] }));
  const selIds = rows.filter((r) => sel[r.id]).map((r) => r.id);
  const selCount = selIds.length;
  const allSelected = rows.length > 0 && selCount === rows.length;
  const someSelected = selCount > 0 && !allSelected;
  const toggleAll = () => {
    if (allSelected || someSelected) { setSel({}); return; }
    const m = {}; rows.forEach((r) => (m[r.id] = true)); setSel(m);
  };
  const plural = selCount > 1 ? "s" : "";
  const doEmail = () => onToast(`Drafting emails to ${selCount} lead${plural}…`);
  const doCampaign = () => onToast(`Generating a new campaign for ${selCount} lead${plural}…`);
  const doArchive = () => {
    setArchived((a) => { const n = { ...a }; selIds.forEach((id) => (n[id] = true)); return n; });
    onToast(`Archived ${selCount} lead${plural}`);
    setSel({});
  };
  const rightCols = new Set(config.cols.map((c, i) => (c.align === "right" ? i + 1 : -1)));

  return (
    <div style={{ position: "relative", width: "100%", paddingBottom: selCount > 0 ? 96 : 24 }}>
      {/* header row */}
      <div style={{ display: "grid", gridTemplateColumns: config.grid, columnGap: 9, alignItems: "center", padding: "9px 32px", borderTop: "1px solid var(--helm-dark-ecru)", borderBottom: "1px solid var(--helm-dark-ecru)" }}>
        <div onClick={toggleAll} title="Select all in this tab" style={{ display: "flex", alignItems: "center", gap: 5, cursor: "pointer" }}>
          <Checkbox checked={allSelected} indeterminate={someSelected} /><DropArrow />
        </div>
        {config.cols.map((c, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 5, justifyContent: rightCols.has(i + 1) ? "flex-end" : "flex-start" }}>
            <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 12, color: "var(--helm-grey)", whiteSpace: "nowrap" }}>{c.label}</span>
            <DropArrow />
          </div>
        ))}
      </div>
      {/* data rows */}
      {rows.map((r) => (
        <div key={r.id} onClick={() => onSelectLead && onSelectLead(r)} onMouseEnter={() => setHover(r.id)} onMouseLeave={() => setHover(null)} style={{ display: "grid", gridTemplateColumns: config.grid, columnGap: 9, alignItems: "center", padding: "13px 32px", borderBottom: "1px solid var(--helm-dark-ecru)", cursor: "pointer", background: sel[r.id] ? "rgba(193,201,131,0.16)" : hover === r.id ? "var(--helm-ecru)" : "transparent", transition: "background 120ms ease" }}>
          <div onClick={(e) => { e.stopPropagation(); toggle(r.id); }} style={{ display: "flex", alignItems: "center" }}>
            <Checkbox checked={!!sel[r.id]} />
          </div>
          {config.cols.map((c, i) => (
            <span key={i} style={{ fontFamily: "var(--font-sans)", fontSize: 14, color: "var(--helm-dark-green)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", display: "flex", justifyContent: rightCols.has(i + 1) ? "flex-end" : "flex-start", alignItems: "center" }}>{c.get(r)}</span>
          ))}
        </div>
      ))}

      {/* bulk action bar */}
      {selCount > 0 && (
        <div style={{ position: "fixed", left: "50%", bottom: 26, transform: "translateX(-50%)", zIndex: 30, display: "flex", alignItems: "center", gap: 8, padding: "9px 11px 9px 18px", background: "var(--helm-dark-green)", borderRadius: 30, boxShadow: "0 16px 40px -10px rgba(0,29,0,0.55)" }}>
          <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14, color: "var(--helm-white)", whiteSpace: "nowrap" }}>{selCount} selected</span>
          <span style={{ width: 1, height: 22, background: "rgba(254,252,245,0.22)", margin: "0 5px" }} />
          <BulkBtn onClick={doEmail} variant="soft" icon={<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="4" width="20" height="16" rx="2" /><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" /></svg>}>Email leads</BulkBtn>
          <BulkBtn onClick={doCampaign} variant="primary" icon={<span className="helm-star" style={{ width: 14, height: 14 }} />}>Generate campaign</BulkBtn>
          <BulkBtn onClick={doArchive} variant="ghost" icon={<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="4" rx="1" /><path d="M5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" /></svg>}>Archive</BulkBtn>
          <button onClick={() => setSel({})} title="Clear selection" style={{ width: 34, height: 34, borderRadius: 17, background: "transparent", border: "none", color: "var(--helm-white)", cursor: "pointer", fontSize: 20, lineHeight: 1, display: "grid", placeItems: "center" }}>×</button>
        </div>
      )}
    </div>
  );
};

// ----------------------------------------------------------------- toolbar
const Toolbar = ({ type, newCount }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 32px 14px" }}>
    <span style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 28, lineHeight: "28px", color: "var(--helm-dark-green)" }}>Leads</span>
    <div style={{ flex: 1, maxWidth: 320, minWidth: 160, height: 38, borderRadius: 19, border: "1px solid var(--helm-dark-ecru)", display: "flex", alignItems: "center", gap: 9, padding: "0 20px" }}>
      <img src="helm/icons/search.svg" style={{ width: 15, height: 15, opacity: 0.5 }} />
      <span style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 14, color: "var(--helm-grey)", whiteSpace: "nowrap" }}>Search by anything</span>
    </div>
    <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7, height: 38, borderRadius: 19, background: "var(--helm-lemon)", padding: "0 18px", fontFamily: "var(--font-sans)", color: "var(--helm-dark-green)" }}>
        <span className="helm-star" style={{ width: 13, height: 13 }} />
        <span style={{ fontWeight: 700, fontSize: 14 }}>{newCount}</span>
        <span style={{ fontWeight: 500, fontSize: 14 }}>new this week</span>
      </div>
      <button style={{ background: "transparent", border: "none", padding: 4, lineHeight: 0, color: "var(--helm-dark-grey)" }}>
        <svg width="4" height="18" viewBox="0 0 4 18" fill="currentColor"><circle cx="2" cy="2" r="2" /><circle cx="2" cy="9" r="2" /><circle cx="2" cy="16" r="2" /></svg>
      </button>
    </div>
  </div>
);

// ----------------------------------------------------------------- page
const NEW_COUNTS = { bene_post: 7, policyholder_gap: 9, bene_pre: 5 };
const LeadsDashboard = ({ onSelectLead }) => {
  const [type, setType] = useDashState("policyholder_gap");
  const [toast, setToast] = useDashState(null);
  useDashEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 2800);
    return () => clearTimeout(t);
  }, [toast]);
  const showToast = (msg) => setToast({ msg, id: Date.now() });
  return (
    <div style={{ position: "absolute", inset: 0, background: "var(--helm-white)", display: "flex", flexDirection: "column", overflow: "hidden", fontFamily: "var(--font-sans)" }}>
      <style>{`@keyframes cpPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.35; transform: scale(0.7); } } .cp-pulse { animation: cpPulse 1.6s ease-in-out infinite; } @keyframes cpToastIn { from { opacity: 0; transform: translate(-50%, 10px); } to { opacity: 1; transform: translate(-50%, 0); } }`}</style>
      <CoPilotHeader active="Leads" />
      <div style={{ flex: 1, minHeight: 0, overflowY: "auto" }}>
        <div style={{ display: "flex", gap: 16, padding: "16px 32px 20px" }}>
          <StatLeadsCard />
          <StatMixCard />
          <StatTopCard onSelectLead={onSelectLead} />
        </div>
        <Toolbar type={type} newCount={NEW_COUNTS[type]} />
        <div style={{ padding: "0 32px 16px" }}>
          <TypeTabs active={type} onChange={setType} />
        </div>
        <LeadsTable type={type} onSelectLead={onSelectLead} onToast={showToast} />
      </div>
      {toast && (
        <div key={toast.id} style={{ position: "fixed", left: "50%", top: 70, transform: "translateX(-50%)", zIndex: 40, display: "flex", alignItems: "center", gap: 9, padding: "11px 18px", background: "var(--helm-dark-green)", color: "var(--helm-white)", borderRadius: 22, boxShadow: "0 12px 30px -10px rgba(0,29,0,0.5)", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13.5, animation: "cpToastIn 240ms ease" }}>
          <span className="helm-star" style={{ width: 14, height: 14, color: "var(--helm-chartreuse)" }} />
          {toast.msg}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { LeadsDashboard, CoPilotHeader, ScorePill, PhaseChip, LeadAvatar });
