// insight.jsx - Cova Insight: portfolio risk overview + Cova recommendations
const { useMemo: useMemoIn } = React;

function buildInsight(assets, claims) {
  const D = window.VC_DATA;
  const p = D.portfolio(assets);
  // portfolio risk score: coverage gap weight + asset risk mix + lapsing.
  // Factors are kept so Cova's chat can explain the score in plain language.
  const highRisk = assets.filter((a) => ["marine", "jewelry"].includes(a.category) || a.replacement >= 100000000);
  const factors = {
    base: 20,
    gapPoints: Math.round((1 - p.covered) * 45),
    mixPoints: Math.min(18, highRisk.length * 6),
    lapsingPoints: Math.min(12, (p.counts.lapsing || 0) * 6),
    highRiskCount: highRisk.length,
    lapsingCount: p.counts.lapsing || 0,
  };
  let score = factors.base + factors.gapPoints + factors.mixPoints + factors.lapsingPoints;
  score = Math.min(95, Math.max(8, score));
  const level = score >= 60 ? "High" : score >= 35 ? "Elevated" : "Healthy";

  const recs = [];
  const uninsured = assets.filter((a) => a.status === "uninsured");
  const partial = assets.filter((a) => a.status === "partial");
  const lapsing = assets.filter((a) => a.status === "lapsing");
  const unbundled = assets.filter((a) => !a.bundle && a.insurer);
  if (uninsured.length) recs.push({ icon: "alert", tone: "danger", title: `${uninsured.length} asset${uninsured.length > 1 ? "s" : ""} fully exposed`, detail: `${uninsured.map((a) => a.name).slice(0, 2).join(", ")}${uninsured.length > 2 ? " +" + (uninsured.length - 2) : ""} - ${D.fmtNaira(uninsured.reduce((s, a) => s + a.replacement, 0))} at risk with no cover.`, action: "Insure now", chat: "Insure my uninsured assets" });
  if (partial.length) recs.push({ icon: "trend", tone: "warning", title: `${D.fmtNaira(partial.reduce((s, a) => s + a.replacement - a.sumInsured, 0))} underinsurance gap`, detail: `${partial.length} asset${partial.length > 1 ? "s are" : " is"} insured below replacement cost - claims would be scaled down proportionally.`, action: "Close the gap", chat: "Close my coverage gap" });
  if (lapsing.length) recs.push({ icon: "clock", tone: "warning", title: `${lapsing.length} polic${lapsing.length > 1 ? "ies" : "y"} lapsing soon`, detail: `${lapsing.map((a) => a.name).join(", ")} - renew before expiry to keep your claim-free streak and cashback.`, action: "Renew", chat: "Renew my lapsing policies" });
  if (unbundled.length >= 2) recs.push({ icon: "layers", tone: "accent", title: `Bundle ${unbundled.length} standalone policies`, detail: `Combining them into one policy could save ~18% in premium and simplify renewals.`, action: "Bundle & save", chat: "Bundle my assets" });
  recs.push({ icon: "doc", tone: "accent", title: "Keep valuations current", detail: "Two assets have no recent valuation report. Updated values prevent claim disputes.", action: "Ask Cova", chat: "How do I update my asset valuations?" });

  return { p, score, level, recs, factors };
}

const INSIGHT_ICONS = { alert: 1, trend: 1, clock: 1, layers: 1, doc: 1, shield: 1, vault: 1, quote: 1, sparkle: 1, claim: 1, flag: 1, bell: 1 };

function Insight({ assets, claims, profile, onChat, onNav }) {
  const D = window.VC_DATA;
  const { t } = window.useT();
  const local = useMemoIn(() => buildInsight(assets, claims), [assets, claims]);

  // Live read: Cova (Claude) scores the persisted portfolio server-side.
  // The local heuristic paints instantly; the live result swaps in when ready.
  const [live, setLive] = React.useState(null);
  React.useEffect(() => {
    let on = true;
    fetch("/api/insight").then((r) => (r.ok ? r.json() : null)).then((d) => {
      if (on && d && typeof d.score === "number") setLive(d);
    }).catch(() => {});
    return () => { on = false; };
  }, [assets.length]);

  const p = local.p;
  const score = live ? live.score : local.score;
  const level = live ? live.level : local.level;
  const recs = live && Array.isArray(live.recs) && live.recs.length
    ? live.recs.map((r) => ({ ...r, icon: INSIGHT_ICONS[r.icon] ? r.icon : "sparkle" }))
    : local.recs;
  const narrative = live && live.narrative;
  const color = level === "High" ? "var(--danger)" : level === "Elevated" ? "var(--warning)" : "var(--success)";
  const animScore = window.useCountUp(score, 1300, [score]);

  const byCat = useMemoIn(() => {
    const m = {};
    assets.forEach((a) => {
      if (!m[a.category]) m[a.category] = { value: 0, exposed: 0 };
      m[a.category].value += a.replacement;
      m[a.category].exposed += Math.max(0, a.replacement - a.sumInsured);
    });
    return Object.entries(m).sort((a, b) => b[1].exposed - a[1].exposed);
  }, [assets]);

  // Activity feed: real events from the server when available, else a light default.
  const feed = (live && Array.isArray(live.feed) && live.feed.length
    ? live.feed.map((f) => ({ ...f, icon: INSIGHT_ICONS[f.icon] ? f.icon : "sparkle" }))
    : [
      { icon: "sparkle", text: "Auto-assessed your latest asset addition - risk profile updated.", time: "Just now" },
      { icon: "shield", text: `Verified ${assets.filter((a) => a.insurer).length} active policies against insurer records.`, time: "Today" },
    ]);

  return (
    <div className="vc-page" style={{ padding: "28px 34px 60px", maxWidth: 1280, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
        <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="eye" size={22} /></span>
            Cova Insight
          </h1>
          <p style={{ color: "var(--text-muted)", fontSize: 15, marginTop: 8 }}>{t("in.subtitle")}</p>
        </div>
        <window.Btn icon="sparkle" onClick={() => onChat("Explain my risk score")}>{t("in.askScore")}</window.Btn>
      </div>

      {/* score hero */}
      <div className="vc-grid" style={{ display: "grid", gridTemplateColumns: "auto 1fr 1fr", gap: 26, alignItems: "center", marginTop: 24, padding: 26, borderRadius: 24, background: "linear-gradient(135deg,var(--surface),var(--surface-2))", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)" }}>
        <div style={{ position: "relative", width: 168, height: 168 }}>
          {/* overflow:visible so the arc's soft glow renders fully instead of
              being clipped at the SVG box (which read as a "bleed"). r reduced a
              touch to keep the ring comfortably inside its 168px frame. */}
          <svg width="168" height="168" viewBox="0 0 168 168" style={{ transform: "rotate(-90deg)", overflow: "visible" }}>
            <circle cx="84" cy="84" r="68" fill="none" stroke="var(--surface-3)" strokeWidth="14" />
            <circle cx="84" cy="84" r="68" fill="none" stroke={color} strokeWidth="14" strokeLinecap="round"
              strokeDasharray={2 * Math.PI * 68} strokeDashoffset={2 * Math.PI * 68 * (1 - animScore / 100)}
              style={{ filter: `drop-shadow(0 2px 7px color-mix(in srgb, ${color} 55%, transparent))` }} />
          </svg>
          <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", textAlign: "center" }}>
            <div>
              <div className="display mono" style={{ fontSize: 44, lineHeight: 1, color }}>{Math.round(animScore)}</div>
              <div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 700, marginTop: 3 }}>{t("in.riskScore")}</div>
            </div>
          </div>
        </div>
        <div>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 13px", borderRadius: 999, background: level === "Healthy" ? "var(--success-soft)" : level === "Elevated" ? "var(--warning-soft)" : "var(--danger-soft)", color, fontSize: 13, fontWeight: 700 }}>
            <span style={{ width: 7, height: 7, borderRadius: 9, background: color }} />{level === "Healthy" ? "Healthy portfolio" : level + " risk portfolio"}
          </span>
          <p style={{ fontSize: 14.5, color: "var(--text-muted)", lineHeight: 1.55, marginTop: 12, maxWidth: 340 }}>
            {narrative || (level === "Healthy" ? "Your cover broadly matches your exposure. Keep renewals on time to stay here." :
              level === "Elevated" ? "A few gaps are inflating your risk. The actions on the right would bring your score down fast." :
              "Significant exposure detected. Cova recommends acting on the items listed - most can be fixed in minutes.")}
          </p>
          {live && (
            <span title={live.source === "claude" ? "Scored live by Cova (Claude)" : "Scored by Cova"} style={{ display: "inline-flex", alignItems: "center", gap: 6, marginTop: 10, fontSize: 11, fontWeight: 700, color: "var(--accent)" }}>
              <window.Icon name="sparkle" size={12} />Cova live assessment
            </span>
          )}
          <div style={{ display: "flex", gap: 20, marginTop: 16, flexWrap: "wrap" }}>
            <div><div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>{t("in.protected")}</div><div className="display mono" style={{ fontSize: 20, color: "var(--success)" }}>{Math.round(p.covered * 100)}%</div></div>
            <div><div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>{t("in.exposedValue")}</div><div className="display mono" style={{ fontSize: 20, color: p.gap ? "var(--danger)" : "var(--success)" }}>{D.fmtNaira(p.gap)}</div></div>
            <div><div style={{ fontSize: 11.5, color: "var(--text-faint)", fontWeight: 600 }}>{t("in.assets")}</div><div className="display mono" style={{ fontSize: 20 }}>{assets.length}</div></div>
          </div>
        </div>
        {/* exposure by category */}
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".03em", marginBottom: 12 }}>{t("in.exposureByCategory")}</div>
          <div style={{ display: "grid", gap: 10 }}>
            {byCat.slice(0, 4).map(([cat, v]) => (
              <div key={cat}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 4 }}>
                  <span style={{ fontWeight: 600 }}>{D.CATEGORIES[cat]?.label || cat}</span>
                  <span className="mono" style={{ color: v.exposed ? "var(--danger)" : "var(--success)" }}>{v.exposed ? D.fmtNaira(v.exposed) + " exposed" : "covered"}</span>
                </div>
                <div style={{ height: 8, borderRadius: 999, background: "var(--surface-3)", overflow: "hidden", display: "flex" }}>
                  <div style={{ width: (v.value ? (v.value - v.exposed) / v.value * 100 : 0) + "%", background: "var(--success)" }} />
                  <div style={{ width: (v.value ? v.exposed / v.value * 100 : 0) + "%", background: "var(--danger)" }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="vc-grid" style={{ display: "grid", gridTemplateColumns: "1.25fr 0.75fr", gap: 16, marginTop: 16, alignItems: "start" }}>
        {/* recommendations */}
        <div style={{ display: "grid", gap: 12 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".03em" }}>{t("in.recommended")}</div>
          {recs.map((r, i) => {
            const tone = r.tone === "danger" ? ["var(--danger)", "var(--danger-soft)"] : r.tone === "warning" ? ["var(--warning)", "var(--warning-soft)"] : ["var(--accent)", "var(--accent-soft)"];
            return (
              <div key={r.title} style={{ display: "flex", gap: 14, padding: 18, borderRadius: 18, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)", animation: `vc-fade-up .5s var(--ease) ${i * 0.07}s both` }}>
                <span style={{ display: "grid", placeItems: "center", width: 42, height: 42, borderRadius: 12, flexShrink: 0, background: tone[1], color: tone[0] }}><window.Icon name={r.icon} size={20} /></span>
                {/* Text spans the full width, with the action button beneath it —
                    so nothing is squeezed into a narrow column. Every card gets the
                    same primary CTA (they're all equally actionable). */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 700, fontSize: 15 }}>{r.title}</div>
                  <div style={{ fontSize: 13, color: "var(--text-muted)", lineHeight: 1.5, marginTop: 4 }}>{r.detail}</div>
                  <window.Btn size="sm" style={{ marginTop: 14 }} onClick={() => onChat(r.chat)}>{r.action}</window.Btn>
                </div>
              </div>
            );
          })}
        </div>

        {/* Cova activity feed */}
        <div style={{ padding: 20, borderRadius: 20, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)", position: "sticky", top: 20 }}>
          <h3 className="display" style={{ fontSize: 16.5, display: "flex", alignItems: "center", gap: 8 }}><window.Icon name="sparkle" size={17} style={{ color: "var(--accent)" }} />{t("in.busy")}</h3>
          <div style={{ display: "grid", gap: 14, marginTop: 16 }}>
            {feed.map((f, i) => (
              <div key={i} style={{ display: "flex", gap: 11 }}>
                <span style={{ display: "grid", placeItems: "center", width: 30, height: 30, borderRadius: 999, flexShrink: 0, background: "var(--accent-soft)", color: "var(--accent)" }}><window.Icon name={f.icon} size={14} /></span>
                <div>
                  <div style={{ fontSize: 13, lineHeight: 1.45 }}>{f.text}</div>
                  <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>{f.time}</div>
                </div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 18, padding: 14, borderRadius: 14, background: "var(--accent-soft)", border: "1px solid var(--accent)" }}>
            <div style={{ fontSize: 12.5, color: "var(--accent-ink)", fontWeight: 600, lineHeight: 1.5 }}>Cova auto-assesses most risks instantly. High-value or unusual cases go to our human underwriters - you'll see their verdict here.</div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Insight, buildInsight });
