// Dashboard screen — at-a-glance stat row, on-air-now card grid, and a
// system-health panel. Mirrors DashboardScreen.tsx: a success state (stat
// row + two-column grid) plus the loading/error states the live screen
// falls back to while the API request is in flight or fails.
(function () {
  const NS = window.ChicoryTVDesignSystem_eb3b61;
  const { Card, Stat, Badge, StatusDot, ChannelLogo, ProgressBar, Button, Spinner } = NS;
  const Ico = window.Ico;
  const mono = { fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" };

  const STATS = [
    { label: "Channels", value: "24", icon: <Ico n="Tv" s={15} /> },
    { label: "Active playouts", value: "22", icon: <Ico n="ListVideo" s={15} /> },
    { label: "On air", value: "4", icon: <Ico n="Radio" s={15} /> },
    { label: "Libraries", value: "7", icon: <Ico n="Library" s={15} /> },
  ];

  const ON_AIR = [
    { num: "1.1", name: "Toon Classics", title: "Tom & Jerry — The Cat Concerto", pct: 48, remain: 14 },
    { num: "2.1", name: "News 24", title: "World Tonight — Evening bulletin", pct: 34, remain: 27 },
    { num: "4.2", name: "Retro Radio", title: "80s Block — Synthpop hour", pct: 51, remain: 19 },
    { num: "9.1", name: "Kids Corner", title: "Sesame Street — Episode 4102", pct: 82, remain: 6 },
  ];

  // status mirrors ErsatzTV.Application/Health/Mapper.cs: pass | fail | warn | info
  const HEALTH = [
    { title: "FFmpeg", detail: "7.1.1 detected on PATH", status: "pass" },
    { title: "Media sources", detail: "5 of 5 libraries reachable", status: "pass" },
    { title: "Transcode folder", detail: "/config/transcode is writable", status: "pass" },
    { title: "HDHomeRun tuners", detail: "2 tuners idle, 2 in use", status: "pass" },
    { title: "Disk space", detail: "/config at 88% capacity", status: "warn" },
    { title: "Plex integration", detail: "Not configured", status: "info" },
  ];

  function healthIconStatus(status) {
    if (status === "fail") return "error";
    if (status === "warn") return "warn";
    if (status === "info") return "idle";
    return "ok";
  }

  function healthIconName(status) {
    const s = healthIconStatus(status);
    if (s === "error" || s === "warn") return "TriangleAlert";
    if (s === "idle") return "Info";
    return "Check";
  }

  function summarizeHealth(checks) {
    const failed = checks.filter((c) => c.status === "fail").length;
    const warned = checks.filter((c) => c.status === "warn").length;
    if (failed > 0) return { label: `${failed} failing`, status: "error" };
    if (warned > 0) return { label: `${warned} warning${warned === 1 ? "" : "s"}`, status: "warn" };
    return { label: "Healthy", status: "ok" };
  }

  function OnAirCard({ ch }) {
    return (
      <div style={{ display: "grid", gap: 10, border: "1px solid var(--border-hairline)", borderRadius: "var(--radius-md)", background: "var(--ctv-bg-sunken)", padding: 12 }}>
        <div style={{ display: "grid", gridTemplateColumns: "auto minmax(0,1fr) auto", alignItems: "center", gap: 8 }}>
          <ChannelLogo name={ch.name} size={34} />
          <div style={{ minWidth: 0, display: "grid", gap: 2 }}>
            <code style={{ ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-secondary)" }}>{ch.num}</code>
            <strong style={{ font: "var(--weight-medium) var(--text-sm)/1.2 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ch.name}</strong>
          </div>
          <Badge tone="accent" dot>On air</Badge>
        </div>
        <p style={{ margin: 0, font: "var(--text-xs)/1.3 var(--font-sans)", color: "var(--text-primary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{ch.title}</p>
        <ProgressBar value={ch.pct} />
        <div style={{ display: "flex", justifyContent: "space-between", gap: 8, ...mono, font: "var(--text-2xs)/1 var(--font-mono)", color: "var(--text-disabled)" }}>
          <span>{ch.pct}% elapsed</span>
          <span>{ch.remain}m to next</span>
        </div>
      </div>
    );
  }

  function HealthPanel() {
    const summary = summarizeHealth(HEALTH);
    return (
      <Card
        title={<h2 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>System health</h2>}
        subtitle="Backend health checks"
        actions={<Button size="sm" variant="secondary" startIcon={<Ico n="RefreshCw" s={14} />}>Refresh health</Button>}
        padded={false}
      >
        <div>
          {HEALTH.map((h, i) => {
            const rowStatus = healthIconStatus(h.status);
            const colorVar = { ok: "var(--status-ok)", warn: "var(--status-warn)", error: "var(--status-error)", idle: "var(--text-secondary)" }[rowStatus];
            return (
              <div key={h.title} style={{ display: "grid", gridTemplateColumns: "auto auto minmax(0,1fr) auto", alignItems: "center", gap: 8, minHeight: 46, padding: "0 12px", borderTop: i ? "1px solid var(--border-hairline)" : "none" }}>
                <span style={{ width: 24, height: 24, display: "inline-flex", alignItems: "center", justifyContent: "center", borderRadius: "var(--radius-xs)", background: "var(--surface-selected)", color: colorVar }}>
                  <Ico n={healthIconName(h.status)} s={15} />
                </span>
                <strong style={{ font: "var(--weight-medium) var(--text-xs)/1 var(--font-sans)", color: "var(--text-primary)", whiteSpace: "nowrap" }}>{h.title}</strong>
                <span style={{ font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{h.detail}</span>
                <StatusDot status={rowStatus} />
              </div>
            );
          })}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", borderTop: "1px solid var(--border-hairline)", padding: "8px 12px" }}>
          <StatusDot status={summary.status} label={summary.label} />
        </div>
      </Card>
    );
  }

  function DashboardLoadingState() {
    return (
      <Card>
        <div style={{ minHeight: 220, display: "flex", alignItems: "center", justifyContent: "center", gap: 8, color: "var(--text-secondary)" }}>
          <Spinner size={20} tone="accent" />
          <span style={{ font: "var(--text-sm)/1 var(--font-sans)" }}>Loading dashboard</span>
        </div>
      </Card>
    );
  }

  function DashboardErrorState() {
    return (
      <Card
        title={<h2 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>Dashboard unavailable</h2>}
        subtitle="Live API request failed"
      >
        <div style={{ display: "grid", gap: 6, border: "1px solid var(--status-error)", borderRadius: "var(--radius-md)", background: "var(--ctv-error-soft)", padding: 12 }}>
          <span style={{ font: "var(--weight-semibold) var(--text-xs)/1 var(--font-sans)", letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--status-error)" }}>API request failed</span>
          <strong style={{ font: "var(--text-sm)/1.3 var(--font-sans)", color: "var(--text-primary)" }}>GET /api/dashboard returned 504 Gateway Timeout</strong>
        </div>
      </Card>
    );
  }

  function Dashboard() {
    const [state, setState] = React.useState("success");

    const StateSwitcher = () => (
      <div style={{ display: "inline-flex", gap: 2, padding: 2, borderRadius: "var(--radius-sm)", background: "var(--ctv-bg-sunken)", border: "1px solid var(--border-hairline)" }}>
        {[{ v: "success", l: "Live data" }, { v: "loading", l: "Loading" }, { v: "error", l: "Error" }].map((o) => {
          const on = o.v === state;
          return (
            <button key={o.v} type="button" onClick={() => setState(o.v)}
              style={{ display: "inline-flex", alignItems: "center", height: 26, padding: "0 11px", border: "none", borderRadius: "var(--radius-xs)", cursor: "pointer", background: on ? "var(--ctv-surface-3)" : "transparent", color: on ? "var(--text-primary)" : "var(--text-secondary)", font: `${on ? "var(--weight-medium)" : "var(--weight-normal)"} var(--text-xs)/1 var(--font-sans)` }}>
              {o.l}
            </button>
          );
        })}
      </div>
    );

    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 20px", borderBottom: "1px solid var(--border-hairline)", flex: "0 0 auto", minHeight: 58 }}>
          <StateSwitcher />
          <span style={{ flex: 1 }} />
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, font: "var(--text-xs)/1 var(--font-sans)", color: "var(--text-secondary)" }}>
            <StatusDot status="live" size={7} /><span style={mono}>4</span> on air
          </span>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "16px 20px" }}>
          {state === "loading" && <DashboardLoadingState />}
          {state === "error" && <DashboardErrorState />}
          {state === "success" && (
            <div style={{ display: "grid", gap: 16 }}>
              <section aria-label="At a glance" style={{ display: "grid", gridTemplateColumns: "repeat(4,minmax(0,1fr))", gap: 16 }}>
                {STATS.map((s) => (
                  <Card key={s.label}><Stat label={s.label} value={s.value} icon={s.icon} /></Card>
                ))}
              </section>

              <section style={{ display: "grid", gridTemplateColumns: "minmax(0,2fr) minmax(260px,1fr)", gap: 16, alignItems: "start" }}>
                <Card
                  title={<h2 style={{ margin: 0, font: "var(--weight-semibold) var(--text-md)/1.2 var(--font-sans)", color: "var(--text-primary)" }}>On air now</h2>}
                  subtitle="Current programmes by channel"
                  actions={<Badge tone="accent" dot>{ON_AIR.length} on air</Badge>}
                >
                  <div style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 10 }}>
                    {ON_AIR.map((ch) => <OnAirCard key={ch.num} ch={ch} />)}
                  </div>
                </Card>

                <HealthPanel />
              </section>
            </div>
          )}
        </div>
      </div>
    );
  }

  window.CTVDashboard = Dashboard;
})();
