/* Fleet — Devon Fleet ops dashboard (admin/owner). Read-only monitor of the
   background com.e31claude.* automations over window.FLEET. Health banner +
   worst-first job list, with a "publisher stale" guard. */

const { Card: FleetCard, Eyebrow: FleetEyebrow } = window.Ds1Threshold_e046d3;

const MONO = "ui-monospace, SFMono-Regular, Menlo, 'Roboto Mono', monospace";
const STATUS = {
  green:  { dot: "var(--status-sold-solid)",    fg: "var(--status-sold-fg)",    label: "Healthy" },
  yellow: { dot: "var(--status-pending-solid)", fg: "var(--status-pending-fg)", label: "Degraded" },
  red:    { dot: "var(--status-lost-solid)",    fg: "var(--status-lost-fg)",    label: "Down" },
  gray:   { dot: "var(--text-faint)",           fg: "var(--text-muted)",        label: "Idle" },
};

function StaleStrip({ ms }) {
  const mins = Math.max(2, Math.round(ms / 60000));
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "16px 22px", borderRadius: "var(--radius-xl)", background: "var(--status-pending-bg)", border: "1px solid var(--status-pending-solid)", marginBottom: 16 }}>
      <Icon name="TriangleAlert" size={22} color="var(--status-pending-fg)" />
      <div>
        <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--status-pending-fg)" }}>Monitor stale — fleet status may be out of date</div>
        <div style={{ fontSize: "var(--text-xs)", color: "var(--status-pending-fg)", opacity: 0.85, marginTop: 2 }}>The publisher (fleetpublish) last reported {mins}m ago. Treat the statuses below as suspect until it recovers.</div>
      </div>
    </div>
  );
}

function HealthBanner({ overall, counts, stale, syncMs }) {
  const level = stale ? "stale" : overall.level;
  const accent = level === "green" ? "var(--status-sold-solid)" : level === "yellow" ? "var(--status-pending-solid)" : level === "red" ? "var(--status-lost-solid)" : "var(--text-faint)";
  const icon = level === "green" ? "CircleCheck" : level === "stale" ? "CloudOff" : level === "red" ? "OctagonAlert" : "TriangleAlert";
  const headline = stale ? "Status unavailable"
    : overall.level === "green" ? "All systems healthy"
    : overall.level === "yellow" ? `${overall.count} service${overall.count > 1 ? "s" : ""} need attention`
    : `${overall.count} service${overall.count > 1 ? "s" : ""} down`;
  const sync = Math.max(0, Math.round((Date.now() - syncMs) / 1000));
  const syncLabel = sync < 60 ? sync + "s ago" : Math.round(sync / 60) + "m ago";

  return (
    <div style={{ background: "var(--surface-hero)", borderRadius: "var(--radius-2xl)", padding: "26px 28px", marginBottom: 24, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, position: "relative", overflow: "hidden" }}>
      <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 5, background: accent }} />
      <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
        <div style={{ width: 60, height: 60, flexShrink: 0, borderRadius: "var(--radius-xl)", background: "rgba(255,255,255,0.08)", display: "flex", alignItems: "center", justifyContent: "center", color: accent, boxShadow: `0 0 0 4px ${accent}22` }}>
          <Icon name={icon} size={30} />
        </div>
        <div>
          <FleetEyebrow tone="inverse" size="2xs" style={{ marginBottom: 6 }}>Devon Fleet · Automation Health</FleetEyebrow>
          <h1 style={{ margin: 0, fontSize: "var(--text-3xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "#fff" }}>{headline}</h1>
          <div style={{ display: "flex", gap: 16, marginTop: 10, flexWrap: "wrap" }}>
            {[["green", counts.green], ["yellow", counts.yellow], ["red", counts.red], ["gray", counts.gray]].map(([s, n]) => (
              <span key={s} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: "var(--text-xs)", color: "rgba(255,255,255,0.82)", fontWeight: 600 }}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: STATUS[s].dot }} />
                <span style={{ fontVariantNumeric: "tabular-nums" }}>{n}</span> {STATUS[s].label}
              </span>
            ))}
          </div>
        </div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 8 }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "6px 12px", borderRadius: "var(--radius-full)", background: "rgba(255,255,255,0.1)" }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: stale ? "var(--status-pending-solid)" : "var(--status-sold-solid)", boxShadow: stale ? "none" : "0 0 0 3px rgba(16,185,129,0.25)" }} />
          <span style={{ fontSize: "var(--text-2xs)", fontWeight: 600, color: "rgba(255,255,255,0.85)", textTransform: "uppercase", letterSpacing: "0.08em" }}>Updated {syncLabel}</span>
        </div>
        <span style={{ fontSize: "var(--text-2xs)", color: "rgba(255,255,255,0.45)", fontFamily: MONO }}>refresh · 60s</span>
      </div>
    </div>
  );
}

function FleetRow({ r }) {
  const c = STATUS[r.status] || STATUS.gray;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "240px 132px 110px 1fr 84px", gap: 16, alignItems: "center", padding: "13px 22px", borderBottom: "1px solid var(--border-subtle)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, minWidth: 0 }}>
        <span style={{ width: 10, height: 10, flexShrink: 0, borderRadius: "50%", background: c.dot, boxShadow: r.status === "gray" ? "none" : `0 0 0 3px ${c.dot}22` }} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: "var(--text-sm)", fontWeight: 700, color: "var(--text-primary)" }}>{r.name}</div>
          <div style={{ fontSize: "var(--text-2xs)", color: "var(--text-faint)", fontFamily: MONO, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</div>
        </div>
      </div>
      <div>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: "var(--text-2xs)", fontWeight: 600, color: "var(--text-secondary)", background: "var(--surface-sunken)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-full)", padding: "3px 10px" }}>
          <Icon name="Clock" size={11} color="var(--text-faint)" />{r.schedule}
        </span>
      </div>
      <div style={{ fontSize: "var(--text-xs)", color: "var(--text-muted)", fontVariantNumeric: "tabular-nums" }}>{window.FLEET.relTime(r.last_activity)}</div>
      <div style={{ fontFamily: MONO, fontSize: "var(--text-xs)", color: c.fg, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.detail}</div>
      <div style={{ textAlign: "right", fontSize: "var(--text-2xs)", fontFamily: MONO, color: "var(--text-faint)", fontVariantNumeric: "tabular-nums" }}>
        {r.loaded ? (r.pid ? "pid " + r.pid : "exit " + r.last_exit) : "unloaded"}
      </div>
    </div>
  );
}

function Fleet() {
  const FLEET = window.FLEET;
  const stale = FLEET.publisherStale();
  const rows = FLEET.sortedWorstFirst();

  return (
    <div style={{ maxWidth: "var(--content-max)", margin: "0 auto" }}>
      <div style={{ marginBottom: 22 }}>
        <h1 style={{ margin: 0, fontSize: "var(--text-2xl)", fontWeight: 700, letterSpacing: "-0.02em", color: "var(--text-primary)" }}>Devon Fleet</h1>
        <p style={{ margin: "4px 0 0", fontSize: "var(--text-sm)", color: "var(--text-muted)" }}>Background automation monitor · {FLEET.total} jobs on com.e31claude.*</p>
      </div>

      {stale && <StaleStrip ms={Date.now() - FLEET.maxUpdated()} />}
      <HealthBanner overall={FLEET.overall()} counts={FLEET.counts()} stale={stale} syncMs={FLEET.maxUpdated()} />

      <FleetCard padding="none" style={{ overflow: "hidden" }}>
        <div style={{ display: "grid", gridTemplateColumns: "240px 132px 110px 1fr 84px", gap: 16, padding: "10px 22px", background: "var(--surface-sunken)", borderBottom: "1px solid var(--border-subtle)" }}>
          {["Service", "Schedule", "Last Activity", "Detail", "Process"].map((h, i) => (
            <FleetEyebrow key={h} size="2xs" style={{ textAlign: i === 4 ? "right" : "left" }}>{h}</FleetEyebrow>
          ))}
        </div>
        {rows.map((r) => <FleetRow key={r.label} r={r} />)}
      </FleetCard>
    </div>
  );
}

window.Fleet = Fleet;
