// insure.jsx - Insure assets individually or bundled + quote comparison (exported to window)
const { useState: useStateI, useMemo: useMemoI, useEffect: useEffectI } = React;

// same-origin call to the real backend (Claude underwriting + real premiums)
const apiI = (path, body) => fetch(path, {
  method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" },
  body: body ? JSON.stringify(body) : undefined,
}).then((r) => (r.ok ? r.json() : null)).catch(() => null);

const RECOMMENDED = {
  vehicle: ["Comprehensive motor", "Third-party liability", "Theft & fire"],
  property: ["Fire & perils", "Burglary", "Public liability"],
  equipment: ["Machinery breakdown", "Fire & perils"],
  electronics: ["All-risks portable", "Theft"],
  inventory: ["Stock throughput", "Burglary"],
  jewelry: ["All-risks valuables", "Worldwide cover"],
  marine: ["Marine cargo", "Transit cover"],
};

// Risk-assessment questions tailored to each kind of property. When several
// assets are bundled, we ask each category's questions once (combined), not per
// item, so a fleet of trucks answers the "vehicle" set a single time.
const RISK_QUESTIONS = {
  vehicle: [
    { id: "parking", q: "Where is it kept overnight?", options: ["Locked garage", "Gated compound", "Street / open"] },
    { id: "use", q: "Primary use", options: ["Private", "Business / haulage", "Ride-hailing"] },
    { id: "tracker", q: "Anti-theft tracker fitted?", options: ["Yes", "No"] },
  ],
  property: [
    { id: "construction", q: "Construction type", options: ["Concrete / block", "Mixed", "Timber / makeshift"] },
    { id: "security", q: "Security on site", options: ["Gated + guard", "Gated only", "None"] },
    { id: "fire", q: "Fire protection", options: ["Alarm + extinguishers", "Extinguishers only", "None"] },
  ],
  equipment: [
    { id: "environment", q: "Operating environment", options: ["Indoor / controlled", "Outdoor / site", "Harsh / industrial"] },
    { id: "age", q: "Age of equipment", options: ["Under 2 years", "2 to 5 years", "Over 5 years"] },
    { id: "maintenance", q: "Serviced under a maintenance contract?", options: ["Yes", "No"] },
  ],
  electronics: [
    { id: "usage", q: "How is it used?", options: ["Home / office only", "Portable / on the go", "Travels abroad"] },
    { id: "antitheft", q: "Anti-theft / find-my enabled?", options: ["Yes", "No"] },
  ],
  inventory: [
    { id: "storage", q: "Where is stock held?", options: ["Warehouse with alarm", "Shop / store", "Open / temporary"] },
    { id: "hazard", q: "Any flammable / hazardous goods?", options: ["None", "Some", "Mostly"] },
  ],
  jewelry: [
    { id: "storage", q: "Where is it kept?", options: ["Bank vault", "Home safe", "At home, unsecured"] },
    { id: "wear", q: "How often is it worn?", options: ["Occasionally", "Regularly", "Daily"] },
    { id: "valuation", q: "Independent valuation available?", options: ["Yes", "No"] },
  ],
  marine: [
    { id: "route", q: "Shipping route", options: ["Domestic", "Regional (West Africa)", "International"] },
    { id: "packaging", q: "Packaging standard", options: ["Containerised", "Palletised", "Loose / bulk"] },
  ],
};

const HIGH_VALUE_KOBO = 5_000_000; // ₦5M+ items need documentary proof of value
// What proof Cova needs for an item, by kind and value.
function proofNeeds(a) {
  const receipt = ["jewelry", "electronics"].includes(a.category) || a.replacement >= HIGH_VALUE_KOBO;
  const photo = ["vehicle", "property", "jewelry", "equipment"].includes(a.category) || a.replacement >= HIGH_VALUE_KOBO;
  return { receipt, photo };
}

function Insure({ assets, profile, userName = "Adebola", preselect, addToast, onDone, onChat, tweaks, panel = [] }) {
  const D = window.VC_DATA;
  const insurable = assets.filter((a) => a.status !== "insured");
  // preselect may be a single asset or an array (a cross-category bundle picked in
  // the VaultLog). An array of 2+ opens straight into bundle mode.
  const preList = Array.isArray(preselect) ? preselect : (preselect ? [preselect] : []);
  const [mode, setMode] = useStateI(preList.length > 1 ? "bundle" : "bundle"); // bundle | individual
  const [selected, setSelected] = useStateI(() => {
    if (preList.length) { const m = {}; preList.forEach((a) => { if (a && a.id) m[a.id] = true; }); return m; }
    const init = {}; insurable.slice(0, 2).forEach((a) => init[a.id] = true); return init;
  });
  const [step, setStep] = useStateI("build"); // build | assess | quotes | payment | done | submitted
  const [chosenQuote, setChosenQuote] = useStateI(null);
  const [assessing, setAssessing] = useStateI(false);
  const [realQuotes, setRealQuotes] = useStateI(null); // quotes from /api/assess (Claude)
  const [assessNote, setAssessNote] = useStateI(null);  // "Cova: Low risk · auto-approved"

  const chosen = assets.filter((a) => selected[a.id]);
  const totalReplace = chosen.reduce((s, a) => s + a.replacement, 0);
  const totalGap = chosen.reduce((s, a) => s + Math.max(0, a.replacement - a.sumInsured), 0);
  // Bundle savings are prorated by asset type + risk (ops-managed, capped ≤10%),
  // not a flat rate — so the number moves with what's actually in the bundle.
  const bundlePct = useMemoI(() => (mode === "bundle" && chosen.length > 1 ? D.bundleDiscount(chosen) : 0), [mode, chosen.map((a) => a.id + ":" + a.replacement).join(","), chosen.length]);

  // Preview quotes come from the LIVE ops-managed panel (add/pause an
  // underwriter in /admin/insurers and this list follows). D.QUOTES is only
  // the offline fallback.
  const panelMeta = useMemoI(() => {
    if (!panel.length) return D.QUOTES;
    return panel.map((p2, i) => ({ insurer: p2.insurer, rating: p2.rating || 4.5, features: (p2.features || []).slice(0, 4), claimDays: 10 + (i % 4) * 2, excess: "10%", badge: null }));
  }, [panel]);
  const quotes = useMemoI(() => {
    const discount = 1 - bundlePct / 100;
    const base = Math.max(totalGap, totalReplace) / 100; // ~1% rate baseline
    const qs = panelMeta.map((q, i) => ({ ...q, premium: Math.round((base * (0.9 + i * 0.07)) * discount / 1000) * 1000 }));
    if (qs[0]) qs[0] = { ...qs[0], badge: qs[0].badge || "Best value" };
    return qs;
  }, [bundlePct, totalGap, totalReplace, panelMeta]);

  const toggle = (id) => setSelected((s) => ({ ...s, [id]: !s[id] }));

  // Submit the tailored risk assessment. Cova (Claude) scores it; most bind
  // instantly with real premiums. High-value / high-risk cases are routed to our
  // underwriting desk for review, but to the customer that just reads as Cova
  // finalising the cover (the flag itself is never surfaced to them).
  const submitAssessment = (answers, proof) => {
    if (!chosen.length || assessing) return;
    setAssessing(true); setRealQuotes(null); setAssessNote(null);
    const primary = [...chosen].sort((a, b) => b.replacement - a.replacement)[0];
    const bundleDisc = 1 - bundlePct / 100;
    apiI("/api/assess", {
      assetIds: chosen.map((a) => a.id), // persist + flag every asset in the bundle
      name: primary && primary.name, category: primary && primary.category, replacement: totalReplace,
      hasReceipt: proof.receiptOk, hasPhoto: proof.photoOk, answers,
    }).then((res) => {
      setAssessing(false);
      if (!res) { setStep("quotes"); return; } // offline -> fall back to mock quotes
      if (res.flagged) { setStep("submitted"); return; } // silently referred to underwriting
      const meta = {}; panelMeta.forEach((q) => { meta[q.insurer] = q; });
      const merged = (res.quotes || []).map((q) => {
        const m = meta[q.insurer] || {};
        return { insurer: q.insurer, premium: Math.round(q.premium * bundleDisc / 1000) * 1000, features: m.features || ["Fire & perils"], rating: m.rating || 4.6, claimDays: m.claimDays || 12, badge: null };
      }).sort((a, b) => a.premium - b.premium);
      if (merged[0]) merged[0].badge = "Best value";
      setRealQuotes(merged);
      setAssessNote(`Cova assessed this ${res.level} risk · auto-approved`);
      setStep("quotes");
    });
  };

  return (
    <div className="vc-page" style={{ padding: "28px 34px 60px", maxWidth: 1180, margin: "0 auto" }}>
      <div>
        <h1 className="display" style={{ fontSize: 32, display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ display: "grid", placeItems: "center", width: 40, height: 40, borderRadius: 13, background: "var(--accent-soft)", color: "var(--accent)" }}><window.Icon name="shield" size={22} /></span>
          Insure your assets
        </h1>
        <p style={{ color: "var(--text-muted)", fontSize: 15, marginTop: 8 }}>Cover items individually, or bundle them into one policy to save. Cova has pre-filled the details from your VaultLog.</p>
      </div>

      {/* mode switch */}
      <div style={{ display: "inline-flex", gap: 4, marginTop: 22, padding: 4, borderRadius: 14, background: "var(--surface-3)", border: "1px solid var(--border)" }}>
        {[["bundle", "layers", "Bundle & save"], ["individual", "shield", "Insure individually"]].map(([id, ic, label]) => (
          <button key={id} onClick={() => setMode(id)} style={{
            display: "inline-flex", alignItems: "center", gap: 8, padding: "10px 18px", borderRadius: 11, fontSize: 14, fontWeight: 700,
            background: mode === id ? "var(--surface)" : "transparent", color: mode === id ? "var(--accent)" : "var(--text-muted)",
            boxShadow: mode === id ? "var(--shadow-sm)" : "none", transition: "all .2s",
          }}><window.Icon name={ic} size={17} />{label}{id === "bundle" && bundlePct > 0 && <span style={{ fontSize: 10, fontWeight: 700, padding: "2px 7px", borderRadius: 999, background: "var(--success-soft)", color: "var(--success)" }}>-{bundlePct}%</span>}</button>
        ))}
      </div>

      <div className="vc-grid" style={{ display: "grid", gridTemplateColumns: "1.4fr 0.85fr", gap: 20, marginTop: 22, alignItems: "start" }}>
        {/* LEFT - pick assets */}
        <div style={{ display: "grid", gap: 12 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".03em" }}>{mode === "bundle" ? "Assets in this bundle" : "Select assets to cover"}</div>
          {insurable.map((a) => {
            const on = !!selected[a.id];
            return (
              <div key={a.id} onClick={() => toggle(a.id)} style={{
                display: "flex", alignItems: "center", gap: 14, padding: 15, borderRadius: 16, cursor: "pointer",
                background: "var(--surface)", border: "1.5px solid " + (on ? "var(--accent)" : "var(--border)"),
                boxShadow: on ? "var(--shadow-glow)" : "var(--shadow-sm)", transition: "all .2s var(--ease)",
              }}>
                <span style={{ display: "grid", placeItems: "center", width: 24, height: 24, borderRadius: 8, background: on ? "var(--accent)" : "var(--surface-3)", color: "#fff", border: on ? "none" : "1px solid var(--border-strong)", transition: "all .2s" }}>{on && <window.Icon name="check" size={15} stroke={3} />}</span>
                <window.AssetThumb category={a.category} size={46} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 15 }}>{a.name}</div>
                  <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 6 }}>
                    {(RECOMMENDED[a.category] || []).slice(0, 2).map((r) => <span key={r} style={{ fontSize: 11, fontWeight: 600, padding: "3px 9px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-ink)" }}>{r}</span>)}
                  </div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono" style={{ fontSize: 15, fontWeight: 700 }}>{D.fmtNaira(a.replacement)}</div>
                  <window.StatusBadge status={a.status} size="sm" />
                </div>
              </div>
            );
          })}
          {insurable.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "var(--text-faint)", border: "1px dashed var(--border-strong)", borderRadius: 16 }}>🎉 Every asset is fully insured.</div>}
        </div>

        {/* RIGHT - sticky summary */}
        <div style={{ position: "sticky", top: 20, padding: 22, borderRadius: 22, background: "linear-gradient(150deg,var(--surface),var(--surface-2))", border: "1px solid var(--border)", boxShadow: "var(--shadow-md)" }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".03em" }}>Cover summary</div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 14, marginBottom: 4 }}>
            <span className="display" style={{ fontSize: 15, color: "var(--accent)" }}>{mode === "bundle" ? "Bundled policy" : chosen.length + " individual policies"}</span>
          </div>
          <SummaryRow k="Assets covered" v={chosen.length} />
          <SummaryRow k="Total value protected" v={D.fmtFull(totalReplace)} />
          <SummaryRow k="Closing exposure of" v={D.fmtFull(totalGap)} c="var(--success)" />
          <div style={{ height: 1, background: "var(--border)", margin: "14px 0" }} />
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontSize: 13.5, color: "var(--text-muted)", fontWeight: 600 }}>Est. annual premium</span>
            <span className="display mono" style={{ fontSize: 26, color: "var(--text)" }}>{D.fmtNaira(quotes[0].premium)}</span>
          </div>
          {mode === "bundle" && chosen.length > 1 && bundlePct > 0 && <div style={{ marginTop: 8, fontSize: 12.5, color: "var(--success)", fontWeight: 700, display: "flex", alignItems: "center", gap: 6 }}><window.Icon name="trend" size={14} />You save ~{bundlePct}% by bundling these {chosen.length} assets</div>}
          <window.Btn size="lg" iconR="arrowR" disabled={chosen.length === 0} style={{ width: "100%", justifyContent: "center", marginTop: 18 }} onClick={() => setStep("assess")}>Get Cova for {mode === "bundle" && chosen.length > 1 ? "these" : "this"}</window.Btn>
          <button onClick={() => onChat("Help me decide what cover I need")} style={{ width: "100%", marginTop: 12, fontSize: 13, fontWeight: 600, color: "var(--accent)", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6 }}><window.Icon name="sparkle" size={14} />Ask Cova to recommend</button>
        </div>
      </div>

      {/* ASSESSMENT overlay, tailored risk questions + proof, then Cova scores it */}
      <window.Overlay open={step === "assess"} onClose={() => setStep("build")} width={720}>
        <AssessStep chosen={chosen} mode={mode} assessing={assessing} onClose={() => setStep("build")} onSubmit={submitAssessment} />
      </window.Overlay>

      {/* QUOTES overlay, real Cova assessment + real premiums */}
      <window.Overlay open={step === "quotes"} onClose={() => setStep("build")} width={760}>
        <QuoteCompare quotes={realQuotes || quotes} note={assessNote} mode={mode} chosen={chosen} onClose={() => setStep("build")} onSelect={(q) => { setChosenQuote(q); setStep("payment"); }} />
      </window.Overlay>

      {/* SUBMITTED overlay, high-value cover quietly routed to underwriting.
          The customer only sees that Cova is finalising it; the flag is internal. */}
      <window.Overlay open={step === "submitted"} onClose={() => setStep("build")} width={460}>
        <SubmittedPanel chosen={chosen} onClose={() => setStep("build")} />
      </window.Overlay>

      {/* PAYMENT overlay */}
      <window.Payment open={step === "payment"} amount={chosenQuote?.premium || 0} label={(mode === "bundle" ? "Bundled policy" : chosen.length + " policies") + " · " + (chosenQuote?.insurer || "")} onClose={() => setStep("quotes")} onSuccess={() => setStep("done")} />

      {/* SUCCESS overlay */}
      <window.Overlay open={step === "done"} onClose={() => { setStep("build"); }} width={460}>
        <PolicyIssued quote={chosenQuote} chosen={chosen} mode={mode} profile={profile} onDone={() => { onDone(chosen.map((a) => a.id), chosenQuote, mode); }} />
      </window.Overlay>
    </div>
  );
}

function SummaryRow({ k, v, c }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "6px 0", fontSize: 13.5 }}>
      <span style={{ color: "var(--text-muted)" }}>{k}</span>
      <span className="mono" style={{ fontWeight: 700, color: c || "var(--text)" }}>{v}</span>
    </div>
  );
}

function QuoteCompare({ quotes, mode, chosen, onClose, onSelect, note }) {
  const D = window.VC_DATA;
  return (
    <div>
      <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <h2 className="display" style={{ fontSize: 22 }}>Compare quotes</h2>
          <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 4 }}>{mode === "bundle" ? "One bundled policy" : chosen.length + " assets"} · matched from {quotes.length} insurers</p>
          {note && <div style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 8, padding: "4px 10px", borderRadius: 999, background: "var(--success-soft)", color: "var(--success)", fontSize: 12, fontWeight: 700 }}><window.Icon name="sparkle" size={13} />{note}</div>}
        </div>
        <button onClick={onClose} style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 999, background: "var(--surface-3)" }}><window.Icon name="close" size={18} /></button>
      </div>
      <div style={{ padding: 22, display: "grid", gap: 12 }}>
        {quotes.map((q, i) => (
          <div key={q.insurer} style={{
            display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr auto", gap: 14, alignItems: "center", padding: 16, borderRadius: 16,
            background: "var(--surface)", border: "1.5px solid " + (q.badge === "Best value" ? "var(--accent)" : "var(--border)"),
            animation: `vc-fade-up .4s var(--ease) ${i * 0.07}s both`, position: "relative",
          }}>
            <div>
              <div style={{ fontWeight: 700, fontSize: 15, display: "flex", alignItems: "center", gap: 8 }}>{q.insurer}{q.badge && <span style={{ fontSize: 10, fontWeight: 700, padding: "2px 8px", borderRadius: 999, background: q.badge === "Best value" ? "var(--accent)" : "var(--accent-soft)", color: q.badge === "Best value" ? "#fff" : "var(--accent-ink)" }}>{q.badge}</span>}</div>
              <div style={{ display: "flex", gap: 5, marginTop: 6, flexWrap: "wrap" }}>{q.features.slice(0, 3).map((f) => <span key={f} style={{ fontSize: 10.5, color: "var(--text-faint)", display: "inline-flex", alignItems: "center", gap: 4 }}><window.Icon name="check" size={11} stroke={3} style={{ color: "var(--success)" }} />{f}</span>)}</div>
            </div>
            <div><div style={{ fontSize: 11, color: "var(--text-faint)" }}>Rating</div><div style={{ fontWeight: 700, fontSize: 14 }}>★ {q.rating}</div></div>
            <div><div style={{ fontSize: 11, color: "var(--text-faint)" }}>Claims in</div><div style={{ fontWeight: 700, fontSize: 14 }}>{q.claimDays} days</div></div>
            <div style={{ textAlign: "right" }}>
              <div className="display mono" style={{ fontSize: 19 }}>{D.fmtNaira(q.premium)}</div>
              <window.Btn size="sm" style={{ marginTop: 6 }} onClick={() => onSelect(q)}>Select</window.Btn>
            </div>
          </div>
        ))}
        <p style={{ textAlign: "center", fontSize: 12, color: "var(--text-faint)", marginTop: 4 }}>All quotes include standard T&Cs · regulated by NAICOM</p>
      </div>
    </div>
  );
}

function PolicyIssued({ quote, chosen, mode, profile = "business", onDone }) {
  const D = window.VC_DATA;
  useEffectI(() => { const t = setTimeout(() => {}, 100); return () => clearTimeout(t); }, []);
  return (
    <div style={{ padding: 32, textAlign: "center" }}>
      <div style={{ position: "relative", width: 92, height: 92, margin: "0 auto", display: "grid", placeItems: "center" }}>
        <div style={{ position: "absolute", inset: 0, borderRadius: 999, background: "var(--success-soft)", animation: "vc-pulse-ring 1.6s ease-out" }} />
        <span style={{ position: "relative", display: "grid", placeItems: "center", width: 72, height: 72, borderRadius: 999, background: "var(--success)", color: "#fff", animation: "vc-scale-in .5s var(--ease) both" }}><window.Icon name="check" size={40} stroke={3} /></span>
      </div>
      <h2 className="display" style={{ fontSize: 26, marginTop: 20 }}>You're covered!</h2>
      <p style={{ fontSize: 15, color: "var(--text-muted)", marginTop: 8 }}>
        {chosen.length} asset{chosen.length > 1 ? "s" : ""} now insured with <b>{quote?.insurer}</b>{mode === "bundle" ? " in one bundle" : ""}.
      </p>
      <div style={{ margin: "20px 0", padding: 16, borderRadius: 16, background: "var(--surface-2)", border: "1px solid var(--border)", display: "flex", justifyContent: "space-between" }}>
        <div style={{ textAlign: "left" }}><div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>Annual premium</div><div className="display mono" style={{ fontSize: 20 }}>{D.fmtFull(quote?.premium || 0)}</div></div>
        <div style={{ textAlign: "right" }}><div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>Policy starts</div><div className="display mono" style={{ fontSize: 20 }}>Today</div></div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        <window.Btn size="lg" variant="soft" icon="download" style={{ width: "100%", justifyContent: "center" }} onClick={() => window.downloadCertificate(chosen.map((a) => ({ ...a, sumInsured: a.replacement, insurer: quote?.insurer, premium: Math.round((quote?.premium || 0) / chosen.length) })), profile, userName, mode === "bundle" ? (chosen.length > 1 ? "Asset bundle" : null) : null)}>Download {mode === "bundle" && chosen.length > 1 ? "bundle " : ""}certificate</window.Btn>
        <window.Btn size="lg" iconR="arrowR" style={{ width: "100%", justifyContent: "center" }} onClick={onDone}>Back to VaultLog</window.Btn>
      </div>
    </div>
  );
}

// Tailored risk assessment. Asks each selected category's questions once, plus
// the documentary proof Cova needs for higher-value items. Nothing here is shown
// until the customer chose to insure, VaultLog itself stays question-free.
function AssessStep({ chosen, mode, assessing, onClose, onSubmit }) {
  const D = window.VC_DATA;
  // unique categories in the selection (bundle = combined question sets)
  const cats = [...new Set(chosen.map((a) => a.category))];
  const needsProof = chosen.filter((a) => { const n = proofNeeds(a); return n.receipt || n.photo; });

  const [answers, setAnswers] = useStateI({});
  const [docs, setDocs] = useStateI({}); // { [assetId]: { receipt:bool, photo:bool } }

  const set = (cat, qid, val) => setAnswers((s) => ({ ...s, [cat + "." + qid]: val }));
  const mark = (id, kind) => setDocs((s) => ({ ...s, [id]: { ...s[id], [kind]: true } }));

  const totalQs = cats.reduce((n, c) => n + (RISK_QUESTIONS[c] || []).length, 0);
  const answered = Object.keys(answers).length;
  const proofDone = needsProof.every((a) => {
    const n = proofNeeds(a), d = docs[a.id] || {};
    return (!n.receipt || d.receipt) && (!n.photo || d.photo);
  });
  const ready = answered >= totalQs && proofDone;

  const handleSubmit = () => {
    // did the customer supply every required receipt / photo?
    const receiptOk = needsProof.every((a) => !proofNeeds(a).receipt || (docs[a.id] || {}).receipt);
    const photoOk = needsProof.every((a) => !proofNeeds(a).photo || (docs[a.id] || {}).photo);
    onSubmit(answers, { receiptOk, photoOk });
  };

  return (
    <div>
      <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <h2 className="display" style={{ fontSize: 22 }}>A few details to tailor your cover</h2>
          <p style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 4 }}>Cova uses these to assess the risk and price {mode === "bundle" && chosen.length > 1 ? "your bundle" : "this cover"} accurately.</p>
        </div>
        <button onClick={onClose} style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 999, background: "var(--surface-3)" }}><window.Icon name="close" size={18} /></button>
      </div>

      <div style={{ padding: 24, maxHeight: "62vh", overflowY: "auto", display: "grid", gap: 22 }}>
        {cats.map((cat) => (
          <div key={cat}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
              <span style={{ display: "grid", placeItems: "center", width: 28, height: 28, borderRadius: 9, background: "var(--accent-soft)", color: "var(--accent)" }}><window.AssetThumb category={cat} size={22} /></span>
              <span style={{ fontWeight: 700, fontSize: 14 }}>{D.CATEGORIES[cat]?.label || cat}</span>
            </div>
            <div style={{ display: "grid", gap: 14 }}>
              {(RISK_QUESTIONS[cat] || []).map((q) => (
                <div key={q.id}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 7 }}>{q.q}</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                    {q.options.map((opt) => {
                      const on = answers[cat + "." + q.id] === opt;
                      return (
                        <button key={opt} onClick={() => set(cat, q.id, opt)} style={{
                          padding: "8px 14px", borderRadius: 999, fontSize: 13, fontWeight: 600, cursor: "pointer",
                          background: on ? "var(--accent)" : "var(--surface-2)", color: on ? "#fff" : "var(--text-muted)",
                          border: "1.5px solid " + (on ? "var(--accent)" : "var(--border)"), transition: "all .15s",
                        }}>{opt}</button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}

        {needsProof.length > 0 && (
          <div>
            <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".03em", marginBottom: 4 }}>Proof &amp; documentation</div>
            <p style={{ fontSize: 12.5, color: "var(--text-muted)", marginBottom: 12 }}>For higher-value items we need a receipt or valuation and a photo to confirm value and condition.</p>
            <div style={{ display: "grid", gap: 10 }}>
              {needsProof.map((a) => {
                const n = proofNeeds(a), d = docs[a.id] || {};
                return (
                  <div key={a.id} style={{ padding: 14, borderRadius: 14, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 10 }}>
                      <window.AssetThumb category={a.category} size={34} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div>
                        <div className="mono" style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{D.fmtNaira(a.replacement)}</div>
                      </div>
                    </div>
                    <div style={{ display: "flex", gap: 8 }}>
                      {n.receipt && <UploadChip label="Receipt / valuation" done={d.receipt} onDone={() => mark(a.id, "receipt")} />}
                      {n.photo && <UploadChip label="Photo" done={d.photo} onDone={() => mark(a.id, "photo")} />}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      <div style={{ padding: "16px 24px", borderTop: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 14 }}>
        <div style={{ flex: 1, fontSize: 12.5, color: "var(--text-faint)" }}>{ready ? "All set, Cova will assess this now." : `${answered}/${totalQs} answered${needsProof.length && !proofDone ? " · proof needed" : ""}`}</div>
        <window.Btn size="lg" iconR="arrowR" disabled={!ready || assessing} onClick={handleSubmit}>{assessing ? "Cova is assessing…" : "Submit for cover"}</window.Btn>
      </div>
    </div>
  );
}

// A simulated upload control. In the prototype, clicking "attaches" a file and
// marks the requirement satisfied; the real app wires this to file storage.
function UploadChip({ label, done, onDone }) {
  return (
    <button onClick={onDone} disabled={done} style={{
      display: "inline-flex", alignItems: "center", gap: 7, padding: "9px 13px", borderRadius: 11, fontSize: 12.5, fontWeight: 600,
      background: done ? "var(--success-soft)" : "var(--surface)", color: done ? "var(--success)" : "var(--accent)",
      border: "1px dashed " + (done ? "var(--success)" : "var(--border-strong)"), cursor: done ? "default" : "pointer",
    }}>
      <window.Icon name={done ? "check" : "doc"} size={14} stroke={done ? 3 : 2} />{done ? `${label} attached` : `Add ${label.toLowerCase()}`}
    </button>
  );
}

// Shown after a high-value submission is quietly routed to underwriting. The
// customer is NOT told they were flagged, only that Cova is finalising terms.
function SubmittedPanel({ chosen, onClose }) {
  const D = window.VC_DATA;
  return (
    <div style={{ padding: 32, textAlign: "center" }}>
      <div style={{ position: "relative", width: 84, height: 84, margin: "0 auto", display: "grid", placeItems: "center" }}>
        <div style={{ position: "absolute", inset: 0, borderRadius: 999, background: "var(--accent-soft)", animation: "vc-pulse-ring 1.8s ease-out" }} />
        <span style={{ position: "relative", display: "grid", placeItems: "center", width: 66, height: 66, borderRadius: 999, background: "linear-gradient(135deg,var(--accent-2),var(--accent))", color: "#fff" }}><window.Icon name="sparkle" size={32} /></span>
      </div>
      <h2 className="display" style={{ fontSize: 24, marginTop: 18 }}>Cova is finalising your cover</h2>
      <p style={{ fontSize: 14.5, color: "var(--text-muted)", marginTop: 10, lineHeight: 1.55 }}>
        Thanks, your details for {chosen.length} asset{chosen.length > 1 ? "s" : ""} worth {D.fmtNaira(chosen.reduce((s, a) => s + a.replacement, 0))} are in.
        Cova is putting the right terms together and we'll notify you the moment your quote is ready, usually within a day.
      </p>
      <div style={{ margin: "18px 0", padding: 14, borderRadius: 14, background: "var(--surface-2)", border: "1px solid var(--border)", fontSize: 12.5, color: "var(--text-muted)", textAlign: "left", display: "flex", gap: 10 }}>
        <window.Icon name="check" size={16} stroke={3} style={{ color: "var(--success)", flexShrink: 0, marginTop: 1 }} />
        Your VaultLog entries stay exactly as they are in the meantime, nothing changes until you accept a quote.
      </div>
      <window.Btn size="lg" style={{ width: "100%", justifyContent: "center" }} onClick={onClose}>Done</window.Btn>
    </div>
  );
}

Object.assign(window, { Insure });
