// dashboard.jsx - overview (exported to window)
const { useMemo: useMemoD } = React;

function Dashboard({ assets, claims = [], profile, userName, onChat, onNav }) {
  const D = window.VC_DATA;
  const { t } = window.useT();
  const claimList = claims; // real claims only; no mock fallback
  const firstName = (userName || "").trim().split(/\s+/)[0] || "there"; // greet by first name; neutral fallback if unknown
  // Time-of-day greeting: morning (<12), afternoon (12-17), evening (17+).
  const hour = new Date().getHours();
  const greetKey = hour < 12 ? "dash.greeting.morning" : hour < 17 ? "dash.greeting" : "dash.greeting.evening";
  const p = useMemoD(() => D.portfolio(assets), [assets]);
  const renewals = assets.filter((a) => a.renews).sort((a, b) => (a.renews > b.renews ? 1 : -1)).slice(0, 4);
  const byCat = useMemoD(() => {
    const m = {};
    assets.forEach((a) => { m[a.category] = (m[a.category] || 0) + a.replacement; });
    return Object.entries(m).sort((a, b) => b[1] - a[1]);
  }, [assets]);

  return (
    <div className="vc-page" style={{ padding: "28px 34px 60px", maxWidth: 1280, margin: "0 auto" }}>
      {/* greeting */}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 16 }}>
        <div>
          <p style={{ color: "var(--text-muted)", fontSize: 15, fontWeight: 600 }}>{t(greetKey, { name: firstName })}</p>
          <h1 className="display" style={{ fontSize: 32, marginTop: 4 }}>{profile === "business" ? t("dash.titleBiz") : t("dash.titlePersonal")}</h1>
        </div>
        <window.Btn icon="sparkle" onClick={() => onChat("What should I prioritise on my cover today?")}>{t("common.askCova")}</window.Btn>
      </div>

      {/* stat row */}
      <div className="vc-grid-2" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14, marginTop: 22 }}>
        <KpiCard icon="shield" label={t("dash.kpi.activePolicies")} value={assets.filter((a) => a.insurer).length} tone="accent" onClick={() => onNav("vaultlog")} />
        <KpiCard icon="vault" label={t("dash.kpi.sumInsured")} value={D.fmtNaira(p.insured)} onClick={() => onNav("vaultlog")} />
        <KpiCard icon={p.gap ? "alert" : "check"} label={t("dash.kpi.gap")} value={D.fmtNaira(p.gap)} tone={p.gap ? "danger" : "success"} onClick={() => onChat("Close my coverage gap")} />
        <KpiCard icon="claim" label={t("dash.kpi.openClaims")} value={claimList.filter((c) => c.status !== "Settled").length} onClick={() => onNav("claims")} />
      </div>

      <div className="vc-grid" style={{ display: "grid", gridTemplateColumns: "1.1fr 1fr 1fr", gap: 16, marginTop: 16 }}>
        {/* coverage breakdown */}
        <Panel title={t("dash.coverageHealth")} action={t("dash.openVaultlog")} onAction={() => onNav("vaultlog")}>
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <window.CoverageRing pct={p.covered} size={118} sub={t("dash.protected")} />
            <div style={{ flex: 1, display: "grid", gap: 9 }}>
              <Legend color="var(--success)" label={t("dash.legend.insured")} n={p.counts.insured} />
              <Legend color="var(--warning)" label={t("dash.legend.underinsured")} n={p.counts.partial + p.counts.lapsing} />
              <Legend color="var(--danger)" label={t("dash.legend.uninsured")} n={p.counts.uninsured} />
            </div>
          </div>
        </Panel>

        {/* value by category */}
        <Panel title={t("dash.valueByCategory")}>
          <div style={{ display: "grid", gap: 11 }}>
            {byCat.map(([cat, val], i) => {
              const max = byCat[0][1];
              return (
                <div key={cat}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5 }}>
                    <span style={{ fontWeight: 600 }}>{D.CATEGORIES[cat]?.label || cat}</span>
                    <span className="mono" style={{ color: "var(--text-muted)" }}>{D.fmtNaira(val)}</span>
                  </div>
                  <div style={{ height: 8, borderRadius: 999, background: "var(--surface-3)", overflow: "hidden" }}>
                    <div style={{ height: "100%", width: (val / max * 100) + "%", borderRadius: 999, background: `oklch(0.6 0.13 ${D.CATEGORIES[cat]?.hue || 260})`, animation: `vc-grow .9s var(--ease) ${i * 0.08}s both` }} />
                  </div>
                </div>
              );
            })}
            <style>{`@keyframes vc-grow{from{transform:scaleX(0);transform-origin:left}to{transform:scaleX(1)}}`}</style>
          </div>
        </Panel>

        {/* renewals */}
        <Panel title={t("dash.upcomingRenewals")} action={t("common.all")} onAction={() => onNav("vaultlog")}>
          <div style={{ display: "grid", gap: 10 }}>
            {renewals.map((a) => (
              <div key={a.id} style={{ display: "flex", alignItems: "center", gap: 11 }}>
                <window.AssetThumb category={a.category} size={36} radius={10} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{a.insurer}</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div className="mono" style={{ fontSize: 12.5, fontWeight: 600 }}>{a.renews}</div>
                  {a.status === "lapsing" && <span style={{ fontSize: 10.5, fontWeight: 700, color: "var(--warning)" }}>{t("dash.soon")}</span>}
                </div>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      {/* chat CTA banner */}
      <div style={{ marginTop: 16, position: "relative", overflow: "hidden", borderRadius: 24, padding: "26px 30px", background: "linear-gradient(120deg,var(--accent),var(--accent-2))", display: "flex", flexWrap: "wrap", gap: 14, alignItems: "center", justifyContent: "space-between", boxShadow: "var(--shadow-glow)" }}>
        <div style={{ position: "absolute", right: -40, top: -40, width: 200, height: 200, borderRadius: 999, background: "rgba(255,255,255,.12)" }} />
        <div style={{ position: "relative" }}>
          <h3 className="display" style={{ fontSize: 22, color: "#fff" }}>{t("dash.ctaTitle")}</h3>
          <p style={{ color: "rgba(255,255,255,.9)", fontSize: 14.5, marginTop: 6 }}>{t("dash.ctaSub")}</p>
        </div>
        <window.Btn size="lg" style={{ background: "#fff", color: "var(--accent-ink)", position: "relative" }} icon="sparkle" onClick={() => onChat("I want to insure something new")}>{t("dash.ctaBtn")}</window.Btn>
      </div>

      {/* recent claims */}
      <Panel title={t("dash.recentClaims")} action={t("dash.trackAll")} onAction={() => onNav("claims")} style={{ marginTop: 16 }}>
        <div style={{ display: "grid", gap: 10 }}>
          {claimList.length === 0 && <div style={{ padding: "18px 14px", borderRadius: 13, background: "var(--surface-2)", border: "1px solid var(--border)", fontSize: 13, color: "var(--text-faint)", textAlign: "center" }}>No claims yet. If something happens, just tell Cova and I'll start the claim.</div>}
          {claimList.slice(0, 3).map((c) => (
            <div key={c.id} onClick={() => onNav("claims")} style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr auto", gap: 12, alignItems: "center", padding: "11px 14px", borderRadius: 13, background: "var(--surface-2)", cursor: "pointer", border: "1px solid var(--border)" }}>
              <div><div style={{ fontWeight: 700, fontSize: 13.5 }}>{c.asset}</div><div className="mono" style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{c.id}</div></div>
              <span style={{ fontSize: 13, color: "var(--text-muted)" }}>{c.type}</span>
              <span className="mono" style={{ fontSize: 13.5, fontWeight: 700 }}>{D.fmtNaira(c.loss)}</span>
              <span style={{ fontSize: 11.5, fontWeight: 700, padding: "5px 11px", borderRadius: 999, background: c.status === "Settled" ? "var(--success-soft)" : "var(--accent-soft)", color: c.status === "Settled" ? "var(--success)" : "var(--accent-ink)" }}>{c.status}</span>
            </div>
          ))}
        </div>
      </Panel>
    </div>
  );
}

function KpiCard({ icon, label, value, tone, onClick }) {
  const [h, setH] = React.useState(false);
  const c = tone === "danger" ? "var(--danger)" : tone === "success" ? "var(--success)" : tone === "accent" ? "var(--accent)" : "var(--text)";
  return (
    <div onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{ padding: 18, borderRadius: 18, background: "var(--surface)", border: "1px solid var(--border)", cursor: "pointer", boxShadow: h ? "var(--shadow-md)" : "var(--shadow-sm)", transform: h ? "translateY(-2px)" : "none", transition: "all .2s var(--ease)" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span style={{ display: "grid", placeItems: "center", width: 38, height: 38, borderRadius: 11, background: tone === "danger" ? "var(--danger-soft)" : tone === "success" ? "var(--success-soft)" : "var(--accent-soft)", color: c }}><window.Icon name={icon} size={19} /></span>
        <window.Icon name="arrowUpR" size={16} style={{ color: h ? "var(--accent)" : "var(--text-faint)" }} />
      </div>
      <div className="display mono" style={{ fontSize: "clamp(19px, 5.6vw, 26px)", marginTop: 14, color: c, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{value}</div>
      <div style={{ fontSize: 13, color: "var(--text-muted)", fontWeight: 600, marginTop: 2 }}>{label}</div>
    </div>
  );
}

function Panel({ title, action, onAction, children, style = {} }) {
  return (
    <div style={{ padding: 20, borderRadius: 20, background: "var(--surface)", border: "1px solid var(--border)", boxShadow: "var(--shadow-sm)", ...style }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <h3 className="display" style={{ fontSize: 16.5 }}>{title}</h3>
        {action && <button onClick={onAction} style={{ fontSize: 13, fontWeight: 700, color: "var(--accent)", display: "inline-flex", alignItems: "center", gap: 4 }}>{action}<window.Icon name="arrowR" size={13} /></button>}
      </div>
      {children}
    </div>
  );
}

function Legend({ color, label, n }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
      <span style={{ width: 11, height: 11, borderRadius: 4, background: color }} />
      <span style={{ fontSize: 13.5, color: "var(--text-muted)", flex: 1 }}>{label}</span>
      <span className="mono" style={{ fontSize: 14, fontWeight: 700 }}>{n}</span>
    </div>
  );
}

Object.assign(window, { Dashboard });
