// screens-2.jsx — Analysis, Coverage Insights screens
const { useState: u2S, useEffect: u2E, useMemo: u2M, useRef: u2R } = React;

// ════════════════════════════════════════════════════════════════
// SCREEN 4: AI ANALYSIS COMPLETE — policy table with AI insights
// ════════════════════════════════════════════════════════════════
const PURPOSE_OPTIONS = [
"Income replacement", "Mortgage payoff", "College tuition",
"Childcare support", "Car payoff", "Funeral expenses"];


const PolicyRow = ({ policy, idx, expanded, onToggle, purposes, togglePurpose, density }) => {
  const verified = policy.verified;
  const pad = density === "compact" ? "14px 20px" : "20px 24px";
  return (
    <div style={{
      border: "1px solid var(--helm-dark-ecru)", borderRadius: 12,
      background: "var(--helm-white)", overflow: "hidden",
      transition: "border-color .2s",
      borderColor: expanded ? "var(--helm-dark-green)" : "var(--helm-dark-ecru)"
    }}>
      <div onClick={onToggle} style={{
        padding: pad, display: "flex", alignItems: "center", gap: 18,
        cursor: "pointer"
      }}>
        <CarrierLogo name={policy.carrier} size="md" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 16, fontWeight: 600,
            color: "var(--helm-dark-green)", marginBottom: 2 }}>
            {policy.coverage}
          </div>
          <div style={{ fontSize: 13, opacity: 0.65, fontFamily: "var(--font-sans)" }}>
            Policy #{policy.policyNumber} · {policy.coverageType}
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
          {verified ?
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "6px 12px", borderRadius: 999,
            background: "var(--helm-soft-chartreuse)", color: "var(--helm-white)",
            fontSize: 12, fontWeight: 600
          }}>
              <svg width="12" height="12" viewBox="0 0 16 12" fill="currentColor">
                <path d="M5.6 11.6L0 6l1.2-1.2L5.6 9.2 14.8 0 16 1.2z" />
              </svg>
              Verified
            </div> :

          <div style={{
            display: "inline-flex", alignItems: "center", gap: 6,
            padding: "6px 12px", borderRadius: 999,
            background: "var(--helm-orange)", color: "var(--helm-dark-green)",
            fontSize: 12, fontWeight: 600
          }}>
              <span style={{ fontSize: 14, lineHeight: 1 }}>!</span>
              Needs review
            </div>
          }
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
          style={{ transform: expanded ? "rotate(180deg)" : "none", transition: "transform .2s" }}>
            <path d="M6 9l6 6 6-6" />
          </svg>
        </div>
      </div>

      {expanded &&
      <div style={{
        padding: density === "compact" ? "0 20px 18px 116px" : "4px 24px 24px 124px",
        display: "flex", flexDirection: "column", gap: 18,
        background: "var(--helm-white)",
        animation: "helmFadeIn .3s ease"
      }}>
          {/* AI summary */}
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
              <StarIcon size={18} />
              <span style={{ fontSize: 13, fontWeight: 600 }}>Helm's analysis</span>
              {policy.summary == null &&
            <span style={{ fontSize: 12, opacity: .6 }}>· generating…</span>
            }
            </div>
            <p style={{ lineHeight: "28px",
            margin: 0, color: "var(--helm-dark-green)", fontFamily: "Geist", fontSize: "18px" }} data-comment-anchor="edcbe2472f-p-83-13">
              {policy.summary ||
            <span style={{ display: "inline-flex", gap: 6, opacity: .5 }}>
                  <span className="shimmer" style={{ width: 240, height: 14, borderRadius: 4 }} />
                  <span className="shimmer" style={{ width: 180, height: 14, borderRadius: 4 }} />
                </span>
            }
            </p>
          </div>

          {/* Key facts grid */}
          <div style={{
          display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16,
          padding: "16px 0", borderTop: "1px solid var(--helm-dark-ecru)",
          borderBottom: "1px solid var(--helm-dark-ecru)", fontFamily: "Geist"
        }} data-comment-anchor="494f14cf1c-div-95-11">
            {[
          ["Face amount", policy.faceAmount],
          ["Premium", policy.premium],
          ["Term", policy.term],
          ["Beneficiaries", policy.beneficiaries]].
          map(([k, v]) =>
          <div key={k}>
                <div style={{ fontSize: 11, fontWeight: 500, opacity: 0.6, textTransform: "uppercase", letterSpacing: "0.06em" }}>{k}</div>
                <div style={{ fontFamily: "var(--font-sans)", marginTop: 4, fontWeight: "400", fontSize: "16px" }}>{v}</div>
              </div>
          )}
          </div>

          {/* Purposes */}
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 10 }}>
              What is this policy for? <span style={{ opacity: 0.6, fontWeight: 400 }}>Tap to confirm.</span>
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {PURPOSE_OPTIONS.map((p) =>
            <Chip key={p} selected={purposes.includes(p)} onClick={() => togglePurpose(idx, p)}>
                  {p}
                </Chip>
            )}
            </div>
          </div>

          {/* Flag if any */}
          {policy.flag &&
        <div style={{
          padding: "14px 18px", borderRadius: 12,
          background: "rgba(255,184,118,0.18)",
          border: "1px solid var(--helm-orange)",
          display: "flex", gap: 12, alignItems: "flex-start"
        }}>
              <div style={{ fontSize: 18, lineHeight: 1, marginTop: 2 }}>⚐</div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 2 }}>Worth knowing</div>
                <div style={{ fontFamily: "var(--font-sans)", fontSize: 15, lineHeight: "22px" }} data-comment-anchor="9d4d06173a-div-138-17">{policy.flag}</div>
              </div>
            </div>
        }
        </div>
      }
    </div>);

};

const AnalysisScreen = ({ policies, setPolicies, onAdvance, onAddAnother, density, onStepClick }) => {
  const [expanded, setExpanded] = u2S(0); // first row expanded
  const togglePurpose = (idx, p) => {
    setPolicies((prev) => prev.map((pol, i) => {
      if (i !== idx) return pol;
      const has = pol.purposes.includes(p);
      return { ...pol, purposes: has ? pol.purposes.filter((x) => x !== p) : [...pol.purposes, p] };
    }));
  };
  const allDone = policies.every((p) => p.purposes.length > 0);
  const pad = density === "compact" ? "32px 56px" : "48px 64px";

  return (
    <main style={{ flex: 1, padding: pad, background: "var(--helm-white)", overflow: "auto" }}>
      <div style={{ maxWidth: 820 }}>
        <StepBreadcrumb steps={["Add policies", "Review", "Coverage map"]} current={1} onStepClick={onStepClick} />
        <h1 style={{ fontFamily: "var(--font-serif)", fontSize: 48, lineHeight: "52px", fontWeight: 600,
          letterSpacing: "-0.015em", margin: "32px 0 12px" }}>
          Your policies, in plain English.
        </h1>
        <p style={{ lineHeight: "30px",
          margin: 0, opacity: 0.8, maxWidth: 620, fontFamily: "Geist", fontSize: "18px" }}>
          Helm read each document and pulled out the parts that matter. Confirm what each one's
          really for — that's how we'll build your coverage map.
        </p>

        <div style={{ marginTop: 36, display: "flex", flexDirection: "column", gap: 12 }}>
          {policies.map((p, i) =>
          <PolicyRow key={i} idx={i} policy={p} expanded={expanded === i}
          onToggle={() => setExpanded(expanded === i ? -1 : i)}
          purposes={p.purposes} togglePurpose={togglePurpose}
          density={density} />
          )}
        </div>

        <div style={{ marginTop: 36, display: "flex", gap: 12, alignItems: "center" }}>
          <Button variant="primary" onClick={onAdvance}>
            {allDone ? "Continue →" : "Continue without confirming"}
          </Button>
          <Button variant="secondary" onClick={onAddAnother || onAdvance}>Add another policy</Button>
        </div>
      </div>
    </main>);

};

// ════════════════════════════════════════════════════════════════
// SANKEY — 4-column flow: Policy → Beneficiary → Purpose → Account
// rows: [{ source, beneficiary, purpose, account, amount }]
// ════════════════════════════════════════════════════════════════
const Sankey = ({ rows }) => {
  if (!rows || rows.length === 0) {
    return (
      <div style={{ padding: 40, textAlign: "center", color: "var(--helm-dark-grey)",
        fontFamily: "var(--font-sans)", fontSize: 14 }}>
        Add a policy to see your coverage map.
      </div>
    );
  }

  // Aggregate by each column
  const aggregate = (key) => {
    const m = new Map();
    rows.forEach(r => m.set(r[key], (m.get(r[key]) || 0) + r.amount));
    return [...m.entries()];
  };
  const sources = aggregate("source");
  const benes = aggregate("beneficiary");
  const accounts = aggregate("account");

  // Layout — 4 columns
  const W = 1040, GAP = 8;
  const colX = {
    srcStart: 0,    srcEnd: 160,
    beneStart: 320, beneEnd: 460,
    purStart: 620,  purEnd: 760,
    accStart: 920,  accEnd: 1040,
  };
  const total = sources.reduce((a, [, v]) => a + v, 0) || 1;

  const totalH = 460;
  const scale = (v) => (v / total) * (totalH - GAP * Math.max(sources.length, benes.length, rows.length, accounts.length));

  // Bright destination palette per beneficiary (drives the row tint)
  const benePalette = [
    { light: "#FFE4CB", base: "#FFB876", deep: "#D38D54" },   // peach/orange
    { light: "#CFEDF1", base: "#A1DCE2", deep: "#70B6BA" },   // sky blue
    { light: "#E5F0AE", base: "#C0C983", deep: "#8D9933" },   // soft chartreuse
    { light: "#E2D7F4", base: "#C6B3EB", deep: "#9888BF" },   // soft purple
  ];
  const beneOrder = benes.map(([k]) => k);
  const colorForBene = (b) => benePalette[beneOrder.indexOf(b) % benePalette.length];

  // Position columns stacked
  const stackPositions = (entries) => {
    const m = new Map();
    let y = 0;
    entries.forEach(([k, v]) => {
      const h = scale(v);
      m.set(k, { y, h, v });
      y += h + GAP;
    });
    return m;
  };
  const srcPos = stackPositions(sources);
  const benePos = stackPositions(benes);
  const accPos = stackPositions(accounts);

  // Order rows by beneficiary, then policy — so same-color ribbons stack
  const ordered = [...rows].sort((a, b) => {
    const ba = beneOrder.indexOf(a.beneficiary);
    const bb = beneOrder.indexOf(b.beneficiary);
    if (ba !== bb) return ba - bb;
    return a.source.localeCompare(b.source);
  });

  // Track running offsets per node, plus mid-column "purpose row" y for each row
  const srcOff = new Map();
  const beneInOff = new Map();
  const beneOutOff = new Map();
  const accOff = new Map();
  let midY = 0;

  const segments = []; // each row → 3 segments + purpose label
  ordered.forEach((r, idx) => {
    const h = scale(r.amount);
    const sp = srcPos.get(r.source);
    const bp = benePos.get(r.beneficiary);
    const ap = accPos.get(r.account);

    const sO = srcOff.get(r.source) || 0;
    const biO = beneInOff.get(r.beneficiary) || 0;
    const boO = beneOutOff.get(r.beneficiary) || 0;
    const aO = accOff.get(r.account) || 0;

    const ySrcA = sp.y + sO,        ySrcB = ySrcA + h;
    const yBnIA = bp.y + biO,       yBnIB = yBnIA + h;
    const yBnOA = bp.y + boO,       yBnOB = yBnOA + h;
    const yMidA = midY,             yMidB = midY + h;
    const yAccA = ap.y + aO,        yAccB = yAccA + h;

    const c = colorForBene(r.beneficiary);

    // Seg 1: src right edge → bene left
    const cx1 = (colX.srcEnd + colX.beneStart) / 2;
    const seg1 = `M${colX.srcEnd},${ySrcA} C${cx1},${ySrcA} ${cx1},${yBnIA} ${colX.beneStart},${yBnIA} L${colX.beneStart},${yBnIB} C${cx1},${yBnIB} ${cx1},${ySrcB} ${colX.srcEnd},${ySrcB} Z`;
    // Seg 2: bene right → mid (purpose row)
    const cx2 = (colX.beneEnd + colX.purStart) / 2;
    const seg2 = `M${colX.beneEnd},${yBnOA} C${cx2},${yBnOA} ${cx2},${yMidA} ${colX.purStart},${yMidA} L${colX.purStart},${yMidB} C${cx2},${yMidB} ${cx2},${yBnOB} ${colX.beneEnd},${yBnOB} Z`;
    // Seg 3 (mid band, where purpose label sits): straight rectangle
    const seg3 = `M${colX.purStart},${yMidA} L${colX.purEnd},${yMidA} L${colX.purEnd},${yMidB} L${colX.purStart},${yMidB} Z`;
    // Seg 4: mid → account (extends fully across the account column)
    const cx3 = (colX.purEnd + colX.accStart) / 2;
    const seg4 = `M${colX.purEnd},${yMidA} C${cx3},${yMidA} ${cx3},${yAccA} ${colX.accStart},${yAccA} L${colX.accEnd},${yAccA} L${colX.accEnd},${yAccB} L${colX.accStart},${yAccB} C${cx3},${yAccB} ${cx3},${yMidB} ${colX.purEnd},${yMidB} Z`;

    segments.push({
      key: `s-${idx}`,
      seg1, seg2, seg3, seg4,
      colorBase: c.base, colorDeep: c.deep, colorLight: c.light,
      midY: yMidA, midH: h,
      purpose: r.purpose, amount: r.amount,
      g1: `g1-${idx}`, g2: `g2-${idx}`, g4: `g4-${idx}`,
    });

    srcOff.set(r.source, sO + h);
    beneInOff.set(r.beneficiary, biO + h);
    beneOutOff.set(r.beneficiary, boO + h);
    accOff.set(r.account, aO + h);
    midY += h + GAP;
  });

  const fmtAmt = (v) => `$${Math.round(v / 1000).toLocaleString()}K`;
  const labelStyle = { fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500, fill: "var(--helm-dark-green)" };
  const amtStyle = { fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, fill: "var(--helm-dark-green)" };
  const headerStyle = { fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, fill: "var(--helm-dark-grey)",
    textTransform: "uppercase", letterSpacing: "0.08em" };

  // Per-bene full-row tint band (across beneficiary column)
  const beneBandPad = 0;

  return (
    <div>
      <svg viewBox={`-20 -36 ${W + 40} ${Math.max(totalH, midY) + 80}`} style={{ width: "100%", height: "auto", display: "block", overflow: "visible" }}>
        <defs>
          {segments.map(s => (
            <React.Fragment key={`gf-${s.key}`}>
              {/* policy → bene: ecru → bright base */}
              <linearGradient id={s.g1} x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor="#F0E9CB" stopOpacity="0.9" />
                <stop offset="100%" stopColor={s.colorLight} stopOpacity="0.85" />
              </linearGradient>
              {/* bene → purpose: light → base */}
              <linearGradient id={s.g2} x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor={s.colorLight} stopOpacity="0.9" />
                <stop offset="100%" stopColor={s.colorBase} stopOpacity="0.9" />
              </linearGradient>
              {/* purpose → account: base → deep */}
              <linearGradient id={s.g4} x1="0" x2="1" y1="0" y2="0">
                <stop offset="0%" stopColor={s.colorBase} stopOpacity="0.9" />
                <stop offset="100%" stopColor={s.colorDeep} stopOpacity="0.95" />
              </linearGradient>
            </React.Fragment>
          ))}
        </defs>

        {/* Column headers */}
        <text x={(colX.srcStart + colX.srcEnd) / 2} y={-18} textAnchor="middle" style={headerStyle}>Policies</text>
        <text x={(colX.beneStart + colX.beneEnd) / 2} y={-18} textAnchor="middle" style={headerStyle}>Beneficiaries</text>
        <text x={(colX.purStart + colX.purEnd) / 2} y={-18} textAnchor="middle" style={headerStyle}>Purposes</text>
        <text x={(colX.accStart + colX.accEnd) / 2} y={-18} textAnchor="middle" style={headerStyle}>Accounts</text>

        {/* Source rectangles — pale ecru */}
        {sources.map(([k, v]) => {
          const p = srcPos.get(k);
          const carrier = k.split(" · ")[0];
          return (
            <g key={`src-${k}`}>
              <rect x={colX.srcStart} y={p.y} width={colX.srcEnd - colX.srcStart} height={p.h} fill="#F0E9CB" rx={3} />
              <text x={colX.srcStart + 12} y={p.y + 22} style={labelStyle}>{carrier}</text>
              <text x={colX.srcStart + 12} y={p.y + 42} style={amtStyle}>{fmtAmt(v)}</text>
            </g>
          );
        })}

        {/* Ribbon segment 1: src → bene */}
        <g>{segments.map(s => <path key={`s1-${s.key}`} d={s.seg1} fill={`url(#${s.g1})`} />)}</g>

        {/* Beneficiary "node" tint bands — full-color block per beneficiary */}
        {benes.map(([k, v]) => {
          const p = benePos.get(k);
          const c = colorForBene(k);
          return (
            <g key={`bn-${k}`}>
              <rect x={colX.beneStart} y={p.y - beneBandPad} width={colX.beneEnd - colX.beneStart} height={p.h + beneBandPad * 2}
                fill={c.light} rx={3} />
              <text x={colX.beneStart + 12} y={p.y + 22} style={labelStyle}>{k}</text>
              <text x={colX.beneStart + 12} y={p.y + 42} style={amtStyle}>{fmtAmt(v)}</text>
            </g>
          );
        })}

        {/* Ribbon segment 2: bene → purpose row */}
        <g>{segments.map(s => <path key={`s2-${s.key}`} d={s.seg2} fill={`url(#${s.g2})`} />)}</g>

        {/* Mid band (purpose strip) — solid base color so labels read on it */}
        <g>{segments.map(s => <path key={`s3-${s.key}`} d={s.seg3} fill={s.colorBase} fillOpacity="0.65" />)}</g>

        {/* Purpose labels on the mid band */}
        {segments.map(s => (
          <g key={`pl-${s.key}`}>
            <text x={(colX.purStart + colX.purEnd) / 2} y={s.midY + s.midH / 2 - 2} textAnchor="middle" style={labelStyle}>
              {s.purpose}
            </text>
            <text x={(colX.purStart + colX.purEnd) / 2} y={s.midY + s.midH / 2 + 16} textAnchor="middle" style={amtStyle}>
              {fmtAmt(s.amount)}
            </text>
          </g>
        ))}

        {/* Ribbon segment 4: mid → account */}
        <g>{segments.map(s => <path key={`s4-${s.key}`} d={s.seg4} fill={`url(#${s.g4})`} />)}</g>

        {/* Account labels (right side, on the ribbon end) */}
        {accounts.map(([k, v]) => {
          const p = accPos.get(k);
          return (
            <g key={`acc-${k}`}>
              <text x={colX.accEnd - 12} y={p.y + 22} textAnchor="end" style={labelStyle}>{k}</text>
              <text x={colX.accEnd - 12} y={p.y + 42} textAnchor="end" style={amtStyle}>{fmtAmt(v)}</text>
            </g>
          );
        })}
      </svg>
    </div>
  );
};

const InsightsScreen = ({ policies, onAdvance, density, onStepClick }) => {
  // Map purposes → financial account they flow into
  const accountFor = (purpose) => {
    const cash = ["Mortgage payoff", "Childcare support", "Funeral expenses", "Car payoff"];
    return cash.includes(purpose) ? "Bank account" : "Helm Cash";
  };

  // Build sankey rows: policy → beneficiary → purpose → account
  const rows = u2M(() => {
    const out = [];
    policies.forEach((p) => {
      const beneList = p.beneficiariesDetail || [{ name: "Estate", pct: 100 }];
      const purposes = p.purposes.length > 0 ? p.purposes : ["Income replacement"];
      const perPurpose = (p.faceAmountNum || 100000) / purposes.length;
      purposes.forEach((purpose) => {
        beneList.forEach((b) => {
          out.push({
            source: `${p.carrier} · $${(p.faceAmountNum / 1000).toFixed(0)}K`,
            beneficiary: b.name,
            purpose,
            account: accountFor(purpose),
            amount: perPurpose * (b.pct / 100)
          });
        });
      });
    });
    return out;
  }, [policies]);

  const total = policies.reduce((a, p) => a + (p.faceAmountNum || 0), 0);
  const pad = density === "compact" ? "32px 56px" : "48px 64px";

  return (
    <main style={{ flex: 1, padding: pad, background: "var(--helm-white)", overflow: "auto" }}>
      <div style={{ maxWidth: 860 }}>
        <StepBreadcrumb steps={["Add policies", "Review", "Coverage map"]} current={2} onStepClick={onStepClick} />
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", margin: "32px 0 12px" }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 500, opacity: 0.6, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>
              Your coverage map
            </div>
            <h1 style={{ fontFamily: "var(--font-serif)", fontSize: 48, lineHeight: "52px",
              fontWeight: 600, letterSpacing: "-0.015em", margin: 0 }}>
              Where your protection flows.
            </h1>
          </div>
          <div style={{ textAlign: "right", flexShrink: 0, marginLeft: 24 }}>
            <div style={{ fontSize: 12, fontWeight: 500, opacity: 0.6, textTransform: "uppercase", letterSpacing: "0.08em" }}>
              Total coverage
            </div>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: 40, lineHeight: "44px", fontWeight: 600, letterSpacing: "-0.02em" }}>
              ${(total / 1000).toLocaleString()}K
            </div>
          </div>
        </div>

        <div style={{
          marginTop: 28, padding: 32,
          background: "var(--helm-white)", border: "1px solid var(--helm-dark-ecru)",
          borderRadius: 16, boxShadow: "4px 4px 0 0 var(--helm-dark-green)"
        }}>
          <Sankey rows={rows} />
        </div>

        {/* Stat tiles */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginTop: 24 }}>
          {[
          ["Policies on file", policies.length],
          ["Purposes assigned", new Set(rows.map((r) => r.purpose)).size],
          ["People protected", new Set(rows.map((r) => r.beneficiary)).size]].
          map(([k, v]) =>
          <div key={k} style={{
            padding: "20px 22px", background: "var(--helm-ecru)",
            borderRadius: 12
          }}>
              <div style={{ fontSize: 11, fontWeight: 500, opacity: 0.6, textTransform: "uppercase", letterSpacing: "0.06em" }}>{k}</div>
              <div style={{ fontFamily: "var(--font-sans)", fontSize: 32, fontWeight: 600, marginTop: 6, letterSpacing: "-0.02em" }}>{v}</div>
            </div>
          )}
        </div>

        <div style={{ marginTop: 36, display: "flex", gap: 12 }}>
          <Button variant="primary-purple" onClick={onAdvance}>Record my guidance →</Button>
          <Button variant="secondary" onClick={onAdvance}>Schedule a call with my agent</Button>
        </div>
      </div>
    </main>);

};

window.AnalysisScreen = AnalysisScreen;
window.InsightsScreen = InsightsScreen;
window.Sankey = Sankey;
window.PURPOSE_OPTIONS = PURPOSE_OPTIONS;