// §3.8 Rate Health Dashboard — Completeness, Expiry, Validation

function RateHealth({ user, perms, onAddRate }) {
  const [tab, setTab] = useState("completeness");
  const tabs = [
    { id: "completeness", label: "Completeness" },
    { id: "expiry", label: "Expiry Alerts", count: EXPIRY_ALERTS.length },
    { id: "validation", label: "Quality Validation", count: VALIDATION_RESULTS.filter(r => r.severity === "Error").length },
  ];
  return (
    <div>
      <PageHeader
        title="Rate Health Dashboard"
        sub="Data quality across all terminals · scoped to your access · real-time"
        right={
          <>
            {(perms.edit || perms.admin) && (
              <button className="btn">
                <Icon name="refresh" size={14} />
                Run validation
              </button>
            )}
            <button className="btn"><Icon name="download" size={14} /> Export findings</button>
          </>
        }
      />
      <HealthKPIs />
      <Tabs tabs={tabs} current={tab} onChange={setTab} />
      {tab === "completeness" && <Completeness onAddRate={onAddRate} />}
      {tab === "expiry" && <ExpiryAlerts />}
      {tab === "validation" && <Validation />}
    </div>
  );
}

function HealthKPIs() {
  const totalExpected = COMPLETENESS.length;
  const present = COMPLETENESS.filter(c => c.status === "Present").length;
  const missing = COMPLETENESS.filter(c => c.status === "Missing").length;
  const expiring = COMPLETENESS.filter(c => c.status === "Expiring").length;
  const overallPct = Math.round((present / totalExpected) * 100);
  const errCount = VALIDATION_RESULTS.filter(r => r.severity === "Error").length;
  const warnCount = VALIDATION_RESULTS.filter(r => r.severity === "Warning").length;

  return (
    <div className="grid-4" style={{ marginBottom: 18 }}>
      <div className="kpi">
        <div className="kpi-label">Overall Completeness</div>
        <div className="row gap-12" style={{ alignItems: "center", marginTop: 4 }}>
          <div className="kpi-value">{overallPct}%</div>
          <Ring pct={overallPct} size={48} stroke={5} color="var(--teal)" />
        </div>
        <div className="kpi-delta">{present} / {totalExpected} combinations</div>
      </div>
      <div className="kpi">
        <div className="kpi-label">Missing Rates</div>
        <div className="kpi-value" style={{ color: missing > 5 ? "var(--red)" : "var(--ink)" }}>{missing}</div>
        <div className="kpi-delta down">across 5 terminals · click to add</div>
      </div>
      <div className="kpi">
        <div className="kpi-label">Expiring &lt; 60 days</div>
        <div className="kpi-value" style={{ color: "var(--amber)" }}>{EXPIRY_ALERTS.length}</div>
        <div className="kpi-delta">↑ 2 vs last week</div>
      </div>
      <div className="kpi">
        <div className="kpi-label">Open Validation Issues</div>
        <div className="kpi-value">{VALIDATION_RESULTS.length}</div>
        <div className="kpi-delta">
          <span style={{ color: "var(--red)", fontWeight: 600 }}>{errCount} errors</span>
          <span style={{ margin: "0 4px" }}>·</span>
          <span style={{ color: "var(--amber)" }}>{warnCount} warnings</span>
        </div>
      </div>
    </div>
  );
}

// ============== COMPLETENESS PANEL ==============
function Completeness({ onAddRate }) {
  const [filters, setFilters] = useState({ terminal: "", costType: "", status: "" });

  const rows = COMPLETENESS.filter(r =>
    (!filters.terminal || r.terminal === filters.terminal) &&
    (!filters.costType || r.costType === filters.costType) &&
    (!filters.status || r.status === filters.status)
  );

  // Per-terminal summary cards
  const summaries = Object.entries(COMPLETENESS_SUMMARY).map(([t, s]) => ({
    code: t, name: TERMINAL_BY_CODE[t]?.name, ...s, pct: Math.round((s.present / s.total) * 100)
  })).sort((a, b) => a.pct - b.pct);

  return (
    <div>
      {/* Per-terminal cards */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12, marginBottom: 18 }}>
        {summaries.map(s => (
          <div key={s.code} className="card" style={{ padding: 14 }}>
            <div className="row gap-8" style={{ marginBottom: 8 }}>
              <Ring pct={s.pct} size={40} stroke={4} color={s.pct < 70 ? "var(--red)" : s.pct < 90 ? "var(--amber)" : "var(--green)"} />
              <div style={{ flex: 1 }}>
                <div className="bold tiny" style={{ fontSize: 12 }}>{s.name}</div>
                <div className="mono tiny muted">{s.code}</div>
              </div>
            </div>
            <div className="row gap-6 tiny" style={{ flexWrap: "wrap" }}>
              <span style={{ color: "var(--green)" }}>● {s.present} present</span>
              <span style={{ color: "var(--red)" }}>● {s.missing} missing</span>
              <span style={{ color: "var(--amber)" }}>● {s.expiring} expiring</span>
            </div>
          </div>
        ))}
      </div>

      <div className="filterbar">
        <FilterChipMenu keyLabel="Terminal" value={filters.terminal ? TERMINAL_BY_CODE[filters.terminal]?.name : ""}
          options={Object.keys(COMPLETENESS_SUMMARY).map(t => ({ value: t, label: TERMINAL_BY_CODE[t].name }))}
          onChange={v => setFilters({ ...filters, terminal: v })} />
        <FilterChipMenu keyLabel="Cost Type" value={filters.costType ? COST_TYPES.find(c => c.code === filters.costType)?.name : ""}
          options={COST_TYPES.map(c => ({ value: c.code, label: c.name }))}
          onChange={v => setFilters({ ...filters, costType: v })} />
        <FilterChipMenu keyLabel="Status" value={filters.status} options={["Present", "Missing", "Expiring"]} onChange={v => setFilters({ ...filters, status: v })} />
        <div className="grow" />
        <div className="row gap-12 tiny muted">
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--green)", borderRadius: 50, marginRight: 4 }} />Present</span>
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--red)", borderRadius: 50, marginRight: 4 }} />Missing</span>
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--amber)", borderRadius: 50, marginRight: 4 }} />Expiring</span>
        </div>
      </div>

      <Card title="Expected Coverage Matrix" sub="Cost Type × Equipment Size × Cargo Type · click a Missing row to add rate"
        right={<button className="btn ghost tiny"><Icon name="settings" size={12} /> Edit matrix</button>}>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Terminal</th>
                <th>Cost Type</th>
                <th>Equipment</th>
                <th>Cargo</th>
                <th>Status</th>
                <th>Last Updated</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rows.slice(0, 18).map((r, i) => (
                <tr key={i}
                  onClick={() => r.status === "Missing" && onAddRate && onAddRate({ terminal: r.terminal, costType: r.costType, equipment: r.equipment, cargo: r.cargo })}
                  style={{
                    cursor: r.status === "Missing" ? "pointer" : "default",
                    background: r.status === "Missing" ? "#fef4f4" : r.status === "Expiring" ? "#fdf6e7" : null,
                  }}>
                  <td>
                    <div className="bold tiny">{TERMINAL_BY_CODE[r.terminal]?.name}</div>
                    <div className="tiny muted mono">{r.terminal}</div>
                  </td>
                  <td>{COST_TYPES.find(c => c.code === r.costType)?.name}</td>
                  <td className="mono tiny">{r.equipment}</td>
                  <td className="tiny">{r.cargo}</td>
                  <td>
                    {r.status === "Present" && <span className="tiny" style={{ color: "var(--green)" }}>✓ Present</span>}
                    {r.status === "Missing" && <span className="tiny bold" style={{ color: "var(--red)" }}>✕ Missing</span>}
                    {r.status === "Expiring" && <span className="tiny" style={{ color: "var(--amber)" }}>⚠ Expiring in {r.expiryDays}d</span>}
                  </td>
                  <td className="mono tiny muted">{r.lastUpdated || "—"}</td>
                  <td>
                    {r.status === "Missing" && <button className="btn tiny" style={{ height: 24, fontSize: 11 }}><Icon name="plus" size={10} /> Add</button>}
                    {r.status === "Expiring" && <button className="btn tiny" style={{ height: 24, fontSize: 11 }}><Icon name="refresh" size={10} /> Renew</button>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

// ============== EXPIRY PANEL ==============
function ExpiryAlerts() {
  const [window, setWindow] = useState(60);
  const expired = [
    { id: "R-09988", terminal: "CNXMG", costType: "Reefer Plug In/Out", expiry: "2025-04-30", days: -14, focal: "—" },
    { id: "R-09974", terminal: "JPYOK", costType: "Storage", expiry: "2025-05-01", days: -13, focal: "Sato T." },
  ];
  const within = EXPIRY_ALERTS.filter(a => a.days <= window);

  return (
    <div>
      <div className="filterbar">
        <span className="tiny muted">Alert window</span>
        <div className="row gap-4" style={{ background: "var(--paper)", padding: 3, borderRadius: 4 }}>
          {[30, 60, 90].map(w => (
            <button key={w} onClick={() => setWindow(w)}
              style={{ padding: "4px 10px", border: 0, borderRadius: 3, background: window === w ? "#fff" : "transparent", fontWeight: window === w ? 600 : 400, color: window === w ? "var(--ink)" : "var(--ink-mute)", cursor: "pointer", fontSize: 12 }}>{w} days</button>
          ))}
        </div>
        <div className="grow" />
        <div className="row gap-12 tiny muted">
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--red)", borderRadius: 50, marginRight: 4 }} />≤ 14 days</span>
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "var(--amber)", borderRadius: 50, marginRight: 4 }} />15–30 days</span>
          <span><span style={{ display: "inline-block", width: 8, height: 8, background: "#d8a83a", borderRadius: 50, marginRight: 4 }} />31–60 days</span>
        </div>
        <button className="btn ghost"><Icon name="bell" size={14} /> Notification settings</button>
      </div>

      <Card title="Rates approaching expiry" sub={`${within.length} active rate(s) within ${window} days · auto-emailed to Rate Focal at 60/30/7 day intervals`}>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Rate ID</th>
                <th>Terminal</th>
                <th>Cost Type</th>
                <th>Equip / Cargo</th>
                <th className="num">Rate</th>
                <th>Expiry</th>
                <th>Days Left</th>
                <th>Assigned Focal</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {within.sort((a, b) => a.days - b.days).map(r => {
                const color = r.days <= 14 ? "var(--red)" : r.days <= 30 ? "var(--amber)" : "#d8a83a";
                return (
                  <tr key={r.id}>
                    <td className="mono tiny bold">{r.id}</td>
                    <td>
                      <div className="bold tiny">{r.terminalName}</div>
                      <div className="tiny muted mono">{r.terminal}</div>
                    </td>
                    <td>{r.costType}</td>
                    <td className="tiny"><span className="mono">{r.equipment}</span> · {r.cargo}</td>
                    <td className="num mono">{fmt.num(r.rate)} {r.ccy}</td>
                    <td className="mono tiny">{r.expiry}</td>
                    <td>
                      <div className="row gap-6">
                        <span style={{ width: 8, height: 8, background: color, borderRadius: 50 }} />
                        <span className="mono tiny" style={{ color, fontWeight: 600 }}>{r.days}d</span>
                      </div>
                    </td>
                    <td className="tiny">{r.focal}</td>
                    <td className="row gap-4">
                      <button className="btn tiny" style={{ height: 24, fontSize: 11 }}><Icon name="copy" size={10} /> Renew</button>
                      <button className="btn ghost tiny" style={{ height: 24 }}><Icon name="bell" size={10} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>

      <div style={{ marginTop: 16 }}>
        <Card title="Expired rates" sub="Past expiry · no active successor · these terminals are operating without a current rate">
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Rate ID</th><th>Terminal</th><th>Cost Type</th><th>Expired</th><th>Days overdue</th><th>Assigned Focal</th><th></th></tr></thead>
              <tbody>
                {expired.map(r => (
                  <tr key={r.id} style={{ background: "#fef4f4" }}>
                    <td className="mono tiny bold">{r.id}</td>
                    <td className="mono tiny">{r.terminal}</td>
                    <td>{r.costType}</td>
                    <td className="mono tiny">{r.expiry}</td>
                    <td><span className="tiny bold mono" style={{ color: "var(--red)" }}>{Math.abs(r.days)}d ago</span></td>
                    <td className="tiny">{r.focal}</td>
                    <td><button className="btn tiny" style={{ height: 24, fontSize: 11 }}><Icon name="plus" size={10} /> Add new rate</button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </div>
    </div>
  );
}

// ============== VALIDATION PANEL ==============
function Validation() {
  const [severity, setSeverity] = useState("");
  const rows = VALIDATION_RESULTS.filter(r => !severity || r.severity === severity);
  const errCount = VALIDATION_RESULTS.filter(r => r.severity === "Error").length;
  const warnCount = VALIDATION_RESULTS.filter(r => r.severity === "Warning").length;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 16 }}>
      <div>
        <div className="filterbar">
          <div className="row gap-4" style={{ background: "var(--paper)", padding: 3, borderRadius: 4 }}>
            {[
              { v: "", l: `All ${VALIDATION_RESULTS.length}` },
              { v: "Error", l: `Errors ${errCount}`, c: "var(--red)" },
              { v: "Warning", l: `Warnings ${warnCount}`, c: "var(--amber)" },
            ].map(s => (
              <button key={s.v} onClick={() => setSeverity(s.v)}
                style={{ padding: "4px 10px", border: 0, borderRadius: 3, background: severity === s.v ? "#fff" : "transparent", fontWeight: severity === s.v ? 600 : 400, color: severity === s.v ? (s.c || "var(--ink)") : "var(--ink-mute)", cursor: "pointer", fontSize: 12 }}>{s.l}</button>
            ))}
          </div>
          <div className="grow" />
          <span className="tiny muted mono">Last run: 2025-05-13 14:08 · 1,284 rates scanned</span>
          <button className="btn primary"><Icon name="refresh" size={14} /> Run validation</button>
        </div>

        <Card title="Open findings" sub="Errors block save · warnings allow save with notice">
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Rule</th>
                  <th>Severity</th>
                  <th>Terminal</th>
                  <th>Target</th>
                  <th>Detail</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {rows.map((r, i) => (
                  <tr key={i} style={{ background: r.severity === "Error" ? "#fef4f4" : "#fdf6e7" }}>
                    <td className="mono tiny">
                      <div className="bold">{r.rule}</div>
                      <div className="muted">{r.name}</div>
                    </td>
                    <td>
                      {r.severity === "Error" && <Pill className="rejected">Error</Pill>}
                      {r.severity === "Warning" && <Pill status="Pending">Warning</Pill>}
                    </td>
                    <td className="mono tiny">{r.terminal}</td>
                    <td className="tiny mono">{r.target}</td>
                    <td className="tiny muted" style={{ maxWidth: 320 }}>{r.detail}</td>
                    <td className="row gap-4">
                      {r.rule === "QV-02" && <button className="btn tiny" style={{ height: 24, fontSize: 11, color: "var(--teal)" }}>Auto-fix</button>}
                      <button className="btn ghost tiny" style={{ height: 24, fontSize: 11 }}>View record</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      </div>

      <Card title="Validation Rules" sub="Server-side enforcement">
        <div style={{ padding: "4px 0" }}>
          {VALIDATION_RULES.map((r, i) => (
            <div key={r.id} style={{ padding: "10px 14px", borderTop: i === 0 ? 0 : "1px solid var(--line)" }}>
              <div className="row gap-6">
                <span className="mono bold tiny">{r.id}</span>
                <span className="bold tiny">{r.name}</span>
                <span style={{ marginLeft: "auto", color: r.severity === "Error" ? "var(--red)" : "var(--amber)" }} className="tiny">{r.severity === "Error" ? "Blocks save" : "Warns"}</span>
              </div>
              <div className="tiny muted" style={{ marginTop: 4, lineHeight: 1.45 }}>{r.desc}</div>
            </div>
          ))}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { RateHealth });
