// Tenants view — Mossad is single-tenant per session today, so there's exactly one tenant
// card to show. Its name/branding come from the TENANTS fixture (tenant-data.jsx), but every
// number below is computed live from the alerts/cases/SARs/customers already loaded for the
// logged-in tenant — nothing here is a static number anymore.

function statusPill(status) {
  if (status === "healthy")    return { cls: "pill low",  label: "Healthy" };
  if (status === "watch")      return { cls: "pill med",  label: "Watch" };
  if (status === "attention")  return { cls: "pill high", label: "Attention" };
  if (status === "onboarding") return { cls: "pill info", label: "Onboarding" };
  return { cls: "pill", label: status };
}

// Sparkline tuned for the tenant card — wider, with axis baseline.
function TenantSpark({ data, color, height = 56 }) {
  if (!data.length) return null;
  const max = Math.max(...data, 1);
  const min = 0;
  const W = 320, H = height, P = 4;
  const pts = data.map((v, i) => {
    const x = P + (i / (data.length - 1)) * (W - P * 2);
    const y = H - P - ((v - min) / (max - min || 1)) * (H - P * 2);
    return [x, y];
  });
  const d = pts.map((p, i) => (i === 0 ? "M" : "L") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join(" ");
  const area = `${d} L ${pts[pts.length - 1][0].toFixed(1)} ${H - P} L ${pts[0][0].toFixed(1)} ${H - P} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" width="100%" height={H}>
      <defs>
        <linearGradient id={`g-${color.replace(/[^a-z0-9]/gi,"")}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"  stopColor={color} stopOpacity="0.22" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      <path d={area} fill={`url(#g-${color.replace(/[^a-z0-9]/gi,"")})`} />
      <path d={d} stroke={color} strokeWidth="1.6" fill="none"
            strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.2" fill={color} />
    </svg>
  );
}

// Real 30-day alert volume, bucketed by day from the alerts already loaded for this tenant.
function alertVolumeByDay(alerts, days = 30) {
  const buckets = [];
  const keys = [];
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setDate(start.getDate() - (days - 1));
  for (let i = 0; i < days; i++) {
    const d = new Date(start);
    d.setDate(d.getDate() + i);
    keys.push(d.toISOString().slice(0, 10));
    buckets.push(0);
  }
  const index = new Map(keys.map((k, i) => [k, i]));
  alerts.forEach(a => {
    const ts = a.opened || a._raw?.created_at;
    if (!ts) return;
    const day = new Date(ts).toISOString().slice(0, 10);
    const i = index.get(day);
    if (i != null) buckets[i] += 1;
  });
  return buckets;
}

// Real current severity mix — a snapshot, not a fake 12-month trend.
function severityMix(alerts) {
  const mix = { low: 0, med: 0, high: 0, severe: 0 };
  alerts.forEach(a => {
    if (a.severity === "critical") mix.severe += 1;
    else if (a.severity === "high") mix.high += 1;
    else if (a.severity === "med" || a.severity === "medium") mix.med += 1;
    else mix.low += 1;
  });
  return mix;
}

function SeverityMixBar({ mix }) {
  const order = [
    { k: "low", label: "Low", color: "var(--risk-low)" },
    { k: "med", label: "Medium", color: "var(--risk-med)" },
    { k: "high", label: "High", color: "oklch(56% 0.20 35)" },
    { k: "severe", label: "Critical", color: "var(--risk-high)" },
  ];
  const total = order.reduce((s, o) => s + mix[o.k], 0) || 1;
  return (
    <div>
      <div style={{ display: "flex", height: 10, borderRadius: 4, overflow: "hidden", border: "1px solid var(--border)" }}>
        {order.map(o => (
          <div key={o.k} title={`${o.label} · ${mix[o.k]}`}
               style={{ width: `${(mix[o.k] / total) * 100}%`, background: o.color }} />
        ))}
      </div>
      <div style={{ display: "flex", gap: 12, marginTop: 6, flexWrap: "wrap" }}>
        {order.map(o => (
          <span key={o.k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, color: "var(--fg-3)" }}>
            <span className="dot" style={{ background: o.color, margin: 0 }} />
            {o.label} <span className="mono" style={{ color: "var(--fg-2)" }}>{mix[o.k]}</span>
          </span>
        ))}
      </div>
    </div>
  );
}

// Health status derived from real numbers instead of an editorial fixture label.
function deriveStatus(stats) {
  if (stats.severityMix.severe > 0 || stats.highRisk > 20) return "attention";
  if (stats.highRisk > 0) return "watch";
  return "healthy";
}

function TenantCard({ tenant, stats }) {
  const isDark = document.documentElement.dataset.theme === "dark";
  const accent = isDark ? tenant.colorDark : tenant.color;
  const sp = statusPill(deriveStatus(stats));

  return (
    <div className="card" style={{ display: "flex", flexDirection: "column", maxWidth: 460 }}>
      {/* Header */}
      <div style={{
        padding: "14px 16px",
        borderBottom: "1px solid var(--border)",
        display: "flex", alignItems: "center", gap: 12,
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: 8,
          background: accent, color: "#fff",
          display: "grid", placeItems: "center",
          fontSize: 16, fontWeight: 600,
          boxShadow: "inset 0 0 0 1px rgba(255,255,255,.16)",
          flexShrink: 0,
        }}>{tenant.initial}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: "-0.01em" }}>{tenant.name}</div>
          <div style={{ color: "var(--fg-3)", fontSize: 11.5, marginTop: 1 }}>
            {tenant.sector} · since {tenant.since}
          </div>
        </div>
        <span className={sp.cls}>
          <span className="dot" style={{ background: "currentColor", marginRight: 4 }} />
          {sp.label}
        </span>
      </div>

      {/* KPI grid — real */}
      <div style={{
        display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
        borderBottom: "1px solid var(--border)",
      }}>
        {[
          { label: "Customers", value: stats.customersLabel },
          { label: "Open alerts", value: stats.openAlerts },
          { label: "High-risk", value: stats.highRisk, c: stats.highRisk > 10 ? "var(--risk-high)" : "var(--fg)" },
          { label: "SARs · MTD", value: stats.sarsMtd },
        ].map((k, i) => (
          <div key={i} style={{
            padding: "12px 14px",
            borderRight: i < 3 ? "1px solid var(--border)" : "0",
          }}>
            <div style={{ fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.04em", textTransform: "uppercase", fontWeight: 500 }}>
              {k.label}
            </div>
            <div className="mono" style={{ fontSize: 18, fontWeight: 500, marginTop: 2, color: k.c || "var(--fg)", letterSpacing: "-0.02em" }}>
              {k.value}
            </div>
          </div>
        ))}
      </div>

      {/* Alert volume sparkline — real, bucketed from live alerts */}
      <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
        <div style={{ display: "flex", alignItems: "center", marginBottom: 4 }}>
          <span style={{ fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.04em", textTransform: "uppercase", fontWeight: 500 }}>
            Alert volume · 30d
          </span>
        </div>
        <TenantSpark data={stats.alertsByDay} color={accent} height={48} />
      </div>

      {/* Current severity mix — real snapshot, not a 12-month fixture */}
      <div style={{ padding: "12px 16px" }}>
        <div style={{ fontSize: 10, color: "var(--fg-3)", letterSpacing: "0.04em", textTransform: "uppercase", fontWeight: 500, marginBottom: 8 }}>
          Alert severity mix · current
        </div>
        <SeverityMixBar mix={stats.severityMix} />
      </div>
    </div>
  );
}

function TenantsView({ data }) {
  const tenant = TENANTS[0];
  const alerts = data?.alerts || [];
  const customers = data?.customers || [];
  const sars = data?.sars || [];

  const stats = React.useMemo(() => {
    const now = new Date();
    const openAlerts = alerts.filter(a => a.status === "open").length;
    const highRisk = alerts.filter(a => a.severity === "high" || a.severity === "critical").length;
    const sarsMtd = sars.filter(s => {
      const d = new Date(s.created_at);
      return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth();
    }).length;
    return {
      customersLabel: customers.length.toLocaleString() + (customers.length === 500 ? "+" : ""),
      openAlerts,
      highRisk,
      sarsMtd,
      alertsByDay: alertVolumeByDay(alerts),
      severityMix: severityMix(alerts),
    };
  }, [alerts, customers, sars]);

  return (
    <div style={{ padding: 18, overflow: "auto", flex: 1 }}>
      <div style={{ display: "flex", alignItems: "flex-end", marginBottom: 16, gap: 10 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>Tenants</h1>
          <div style={{ color: "var(--fg-3)", fontSize: 12.5, marginTop: 4 }}>
            1 fintech on Mossad · {stats.customersLabel} customers monitored
          </div>
        </div>
      </div>

      <TenantCard tenant={tenant} stats={stats} />
    </div>
  );
}

Object.assign(window, { TenantsView });
