'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { AlertTriangle, BookOpen, CheckCircle2, Cloud, Copy, DatabaseBackup, ExternalLink, Gauge, HardDrive, ListChecks, RefreshCw, ShieldCheck, Terminal, Timer, Wifi, Activity, CalendarClock, Link2 } from 'lucide-react';
import { Badge, Button } from '@/components/ui/Primitives';
import { SectionCard } from '@/components/hermes-shell';
import { api, type HermesOpsInstance, type HermesOpsSnapshot } from '@/lib/api';
import { getHermesOpsHistory, recordHermesOpsSnapshot, type HermesOpsHistoryEntry } from '@/lib/hermes-ops-history';

function boolTone(value: boolean): 'success' | 'error' {
  return value ? 'success' : 'error';
}

function boolText(value: boolean) {
  return value ? 'OK' : 'Needs attention';
}

function formatDate(value: string | null) {
  if (!value) return 'unknown';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return new Intl.DateTimeFormat('en', {
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
  }).format(date);
}

function StatusRow({ label, value, ok }: { label: string; value: string; ok: boolean }) {
  return (
    <div className="flex items-center justify-between gap-3 rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] px-3 py-2">
      <span className="text-sm text-[var(--bl-text-secondary)]">{label}</span>
      <Badge variant={boolTone(ok)}>{value}</Badge>
    </div>
  );
}

// SSH command per instance. Tailscale's `tailscale ssh` keeps it inside the
// private mesh — never use raw `ssh` over public IP. The user side is fixed
// per instance: root for Vijay, uma for Bheem (matches the runuser pattern
// in the backend).
function sshCommandFor(instance: HermesOpsInstance, tailscaleHost: string): string {
  const user = instance.id === 'bheem' ? 'uma' : 'root';
  return `tailscale ssh ${user}@${tailscaleHost}`;
}

function InstanceCard({ instance, tailscaleIp }: { instance: HermesOpsInstance; tailscaleIp: string | null }) {
  const score = [
    instance.gateway.active,
    instance.gateway.enabled,
    instance.dashboard.active,
    instance.backup.timer.active,
    instance.backup.repo.clean,
    instance.google.workspaceToken,
  ].filter(Boolean).length;

  return (
    <article className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-4 shadow-[var(--bl-shadow-sm)]">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div>
          <div className="flex items-center gap-2">
            <Gauge className="h-4 w-4 text-[var(--bl-accent)]" />
            <h3 className="font-semibold text-[var(--bl-text-primary)]">{instance.label}</h3>
          </div>
          <p className="mt-1 text-xs text-[var(--bl-text-secondary)]">{instance.hermesHome}</p>
        </div>
        <Badge variant={score === 6 ? 'success' : score >= 4 ? 'warning' : 'error'}>{score}/6 healthy</Badge>
      </div>

      <div className="mt-4 grid gap-2">
        <StatusRow label={instance.gateway.service} value={boolText(instance.gateway.active)} ok={instance.gateway.active} />
        <StatusRow label="Auto-start enabled" value={instance.gateway.enabled ? 'enabled' : 'disabled'} ok={instance.gateway.enabled} />
        <StatusRow label="Private dashboard" value={boolText(instance.dashboard.active)} ok={instance.dashboard.active} />
        <StatusRow label="10-minute backup timer" value={boolText(instance.backup.timer.active)} ok={instance.backup.timer.active} />
        <StatusRow label="Google Workspace token" value={boolText(instance.google.workspaceToken)} ok={instance.google.workspaceToken} />
      </div>

      <div className="mt-4 grid gap-3 text-sm text-[var(--bl-text-secondary)] md:grid-cols-2">
        <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-3">
          <div className="flex items-center gap-2 text-[var(--bl-text-primary)]">
            <DatabaseBackup className="h-4 w-4" />
            Backup repo
          </div>
          <p className="mt-2 break-words">HEAD {instance.backup.repo.head ?? 'unknown'}</p>
          <p className="break-words">Last commit {formatDate(instance.backup.repo.lastCommitAt)}</p>
          <p>{instance.backup.repo.clean ? 'Clean working tree' : 'Uncommitted changes present'}</p>
        </div>
        <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-3">
          <div className="flex items-center gap-2 text-[var(--bl-text-primary)]">
            <HardDrive className="h-4 w-4" />
            Restore payload
          </div>
          <p className="mt-2">{instance.backup.restoredFileCount ?? 'unknown'} tracked files</p>
          <p>{instance.backup.restoredCronJobs ?? 'unknown'} cron job definitions</p>
          <p className="break-words">{instance.backup.repo.size ?? 'size unknown'}</p>
        </div>
      </div>

      <div className="mt-4 flex flex-wrap gap-2">
        <Button asChild variant="secondary" size="sm">
          <a href={instance.dashboard.url} target="_blank" rel="noreferrer">
            Open dashboard <ExternalLink className="ml-2 h-4 w-4" />
          </a>
        </Button>
        <Button variant="ghost" size="sm" onClick={() => void navigator.clipboard.writeText(instance.dashboard.url)}>
          <Copy className="mr-2 h-4 w-4" />
          Copy URL
        </Button>
        {tailscaleIp ? (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => void navigator.clipboard.writeText(sshCommandFor(instance, tailscaleIp))}
            title={sshCommandFor(instance, tailscaleIp)}
          >
            <Terminal className="mr-2 h-4 w-4" />
            Copy SSH command
          </Button>
        ) : null}
        <Button asChild variant="ghost" size="sm">
          {/* Deep link into the Task Ledger pre-filtered to this instance.
              `?instance=<id>` is read by HermesInstanceProvider on mount and
              wins over the localStorage selection for this navigation. */}
          <Link href={`/hermes/tasks?instance=${instance.id}`}>
            <ListChecks className="mr-2 h-4 w-4" />
            View tasks
          </Link>
        </Button>
        <Button asChild variant="ghost" size="sm">
          <a href="https://github.com/saravanakumardb/learning_ai_devops_tools/blob/main/docs/hermes-operations.md" target="_blank" rel="noreferrer">
            <BookOpen className="mr-2 h-4 w-4" />
            Open runbook
          </a>
        </Button>
      </div>
    </article>
  );
}

// Severity-tagged warnings (Phase 6 polish). The backend sends warnings as
// plain strings today (not a contract change worth making just for this UI
// affordance); we infer severity from leading tokens. Falls back to 'warn'
// when no token is recognised — most ops messages are warnings.
type Severity = 'info' | 'warn' | 'critical';
const SEVERITY_ORDER: Severity[] = ['critical', 'warn', 'info'];

function classifyWarning(message: string): Severity {
  const upper = message.toUpperCase();
  if (upper.startsWith('CRITICAL') || upper.startsWith('ERROR') || upper.startsWith('FATAL')) return 'critical';
  if (upper.startsWith('INFO') || upper.startsWith('OK')) return 'info';
  return 'warn';
}

function severityVariant(s: Severity): 'error' | 'warning' | 'info' {
  if (s === 'critical') return 'error';
  if (s === 'warn') return 'warning';
  return 'info';
}

function RecentAlerts({ alerts }: { alerts: string[] }) {
  const [filter, setFilter] = useState<Severity | 'all'>('all');
  const tagged = useMemo(
    () => alerts.map((message, idx) => ({ id: `${idx}-${message}`, message, severity: classifyWarning(message) })),
    [alerts],
  );
  const counts = useMemo(() => {
    const acc: Record<Severity, number> = { info: 0, warn: 0, critical: 0 };
    for (const a of tagged) acc[a.severity]++;
    return acc;
  }, [tagged]);
  const visible = filter === 'all' ? tagged : tagged.filter((a) => a.severity === filter);

  return (
    <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="flex items-center gap-2 text-sm font-medium text-[var(--bl-text-primary)]">
          <AlertTriangle className="h-4 w-4 text-[var(--bl-warning)]" />
          Recent sanitized alerts
        </div>
        <div className="flex flex-wrap gap-1" role="radiogroup" aria-label="Severity filter">
          {(['all', ...SEVERITY_ORDER] as const).map((opt) => {
            const active = filter === opt;
            const label = opt === 'all'
              ? `All (${tagged.length})`
              : `${opt} (${counts[opt]})`;
            return (
              <button
                key={opt}
                type="button"
                role="radio"
                aria-checked={active}
                onClick={() => setFilter(opt)}
                className={`rounded-full border px-2 py-0.5 text-xs ${active ? 'border-[var(--bl-accent)] bg-[var(--bl-accent)] text-[var(--bl-text-on-accent,white)]' : 'border-[var(--bl-border)] bg-[var(--bl-surface-card)] text-[var(--bl-text-secondary)] hover:border-[var(--bl-accent)]'}`}
              >
                {label}
              </button>
            );
          })}
        </div>
      </div>
      <div className="mt-3 space-y-2">
        {visible.length ? visible.map((a) => (
          <div key={a.id} className="flex items-start gap-2 rounded-xl bg-[var(--bl-surface-card)] px-3 py-2 text-sm text-[var(--bl-text-secondary)]">
            <Badge variant={severityVariant(a.severity)}>{a.severity}</Badge>
            <span className="min-w-0 break-words">{a.message}</span>
          </div>
        )) : (
          <div className="rounded-xl bg-[var(--bl-surface-card)] px-3 py-2 text-sm text-[var(--bl-text-secondary)]">No alerts at this severity.</div>
        )}
      </div>
    </div>
  );
}

// Tiny inline sparkline — no chart library, just an SVG polyline. Width
// scales to fill its parent; height is fixed. `values` is rendered in
// order; if all values are equal the line sits in the middle.
function Sparkline({ values, accent = 'var(--bl-accent)' }: { values: number[]; accent?: string }) {
  if (values.length < 2) return <div className="h-8 text-xs text-[var(--bl-text-tertiary)]">Need ≥2 samples for a trend.</div>;
  const min = Math.min(...values);
  const max = Math.max(...values);
  const span = max - min || 1;
  const points = values.map((v, i) => {
    const x = (i / (values.length - 1)) * 100;
    const y = 100 - ((v - min) / span) * 100;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg className="h-8 w-full" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
      <polyline points={points} fill="none" stroke={accent} strokeWidth="2" vectorEffect="non-scaling-stroke" />
    </svg>
  );
}

function TrendCards({ history }: { history: HermesOpsHistoryEntry[] }) {
  if (history.length === 0) {
    return (
      <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4 text-sm text-[var(--bl-text-secondary)]">
        No history yet. Trend cards populate after the first one or two refreshes (we keep up to 24 in localStorage).
      </div>
    );
  }
  const warningSeries = history.map((h) => h.warningCount);
  const healthySeries = history.map((h) => h.healthyInstances);

  // Backup-freshness in minutes-since-last-commit, per instance, latest entry only.
  const latest = history.at(-1)!;
  const nowMs = Date.now();
  const backupRows = Object.entries(latest.backupFreshness).map(([instance, iso]) => ({
    instance,
    minutesAgo: iso ? Math.max(0, Math.round((nowMs - new Date(iso).getTime()) / 60_000)) : null,
  }));

  return (
    <div className="grid gap-4 xl:grid-cols-3">
      <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
        <div className="flex items-center justify-between text-sm">
          <span className="font-medium text-[var(--bl-text-primary)]">Warning volume</span>
          <Badge variant={latest.warningCount === 0 ? 'success' : 'warning'}>{latest.warningCount} now</Badge>
        </div>
        <p className="mt-1 text-xs text-[var(--bl-text-tertiary)]">Last {history.length} refresh{history.length === 1 ? '' : 'es'}</p>
        <div className="mt-3"><Sparkline values={warningSeries} accent="var(--bl-warning)" /></div>
      </div>

      <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
        <div className="flex items-center justify-between text-sm">
          <span className="font-medium text-[var(--bl-text-primary)]">Healthy instances</span>
          <Badge variant={latest.healthyInstances >= 2 ? 'success' : 'warning'}>{latest.healthyInstances}/2 now</Badge>
        </div>
        <p className="mt-1 text-xs text-[var(--bl-text-tertiary)]">Trend across recent refreshes</p>
        <div className="mt-3"><Sparkline values={healthySeries} accent="var(--bl-success)" /></div>
      </div>

      <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
        <div className="flex items-center justify-between text-sm">
          <span className="font-medium text-[var(--bl-text-primary)]">Backup freshness</span>
          <Badge variant="info">Per instance</Badge>
        </div>
        <ul className="mt-3 space-y-2 text-sm">
          {backupRows.map(({ instance, minutesAgo }) => {
            const stale = minutesAgo === null || minutesAgo > 30;
            return (
              <li key={instance} className="flex items-center justify-between gap-2">
                <span className="text-[var(--bl-text-secondary)]">{instance}</span>
                <Badge variant={stale ? 'warning' : 'success'}>
                  {minutesAgo === null ? 'unknown' : `${minutesAgo}m ago`}
                </Badge>
              </li>
            );
          })}
          {backupRows.length === 0 ? (
            <li className="text-[var(--bl-text-secondary)]">No instances reported.</li>
          ) : null}
        </ul>
      </div>
    </div>
  );
}

export function HermesOpsPanel() {
  const [snapshot, setSnapshot] = useState<HermesOpsSnapshot | null>(null);
  const [previousSnapshot, setPreviousSnapshot] = useState<HermesOpsSnapshot | null>(null);
  const [history, setHistory] = useState<HermesOpsHistoryEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const latestSnapshotRef = useRef<HermesOpsSnapshot | null>(null);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const nextSnapshot = await api.getHermesOps();
      setPreviousSnapshot(latestSnapshotRef.current);
      latestSnapshotRef.current = nextSnapshot;
      setSnapshot(nextSnapshot);
      // Record the snapshot in client-side rolling history (last 24).
      // Used by the trend cards below.
      setHistory(recordHermesOpsSnapshot(nextSnapshot));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to load Hermes operations status');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // Seed from localStorage so the trend cards aren't empty on first paint.
    setHistory(getHermesOpsHistory());
    void load();
    const id = window.setInterval(() => void load(), 60_000);
    return () => window.clearInterval(id);
  }, []);

  const allHealthy = useMemo(() => snapshot ? snapshot.warnings.length === 0 : false, [snapshot]);
  const snapshotDiff = useMemo(() => {
    if (!snapshot || !previousSnapshot) return null;

    const previousHealthyInstances = previousSnapshot.instances.filter((instance) =>
      instance.gateway.active &&
      instance.dashboard.active &&
      instance.backup.timer.active &&
      instance.backup.repo.clean &&
      instance.google.workspaceToken
    ).length;

    const currentHealthyInstances = snapshot.instances.filter((instance) =>
      instance.gateway.active &&
      instance.dashboard.active &&
      instance.backup.timer.active &&
      instance.backup.repo.clean &&
      instance.google.workspaceToken
    ).length;

    return {
      healthyInstances: currentHealthyInstances - previousHealthyInstances,
      warnings: snapshot.warnings.length - previousSnapshot.warnings.length,
      activeSessions: snapshot.activeSessions.active - previousSnapshot.activeSessions.active,
      activeDashboards: snapshot.instances.filter((instance) => instance.dashboard.active).length - previousSnapshot.instances.filter((instance) => instance.dashboard.active).length,
      activeBackupTimers: snapshot.instances.filter((instance) => instance.backup.timer.active).length - previousSnapshot.instances.filter((instance) => instance.backup.timer.active).length,
    };
  }, [previousSnapshot, snapshot]);
  const healthyInstances = snapshot
    ? snapshot.instances.filter((instance) =>
      instance.gateway.active &&
      instance.dashboard.active &&
      instance.backup.timer.active &&
      instance.backup.repo.clean &&
      instance.google.workspaceToken
    ).length
    : 0;
  const activeDashboards = snapshot ? snapshot.instances.filter((instance) => instance.dashboard.active).length : 0;
  const activeBackupTimers = snapshot ? snapshot.instances.filter((instance) => instance.backup.timer.active).length : 0;

  return (
    <SectionCard
      title="Live Recovery and Dashboard Status"
      subtitle="Real VM status for Vijay/root and Bheem/Uma: gateways, private dashboards, backups, Google auth, and restore payload health."
      actions={(
        <div className="flex flex-wrap items-center gap-2">
          {snapshot ? <Badge variant={allHealthy ? 'success' : 'warning'}>{allHealthy ? 'All green' : `${snapshot.warnings.length} warning(s)`}</Badge> : null}
          <Button variant="ghost" size="sm" onClick={() => void load()} disabled={loading}>
            <RefreshCw className={`mr-2 h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
        </div>
      )}
    >
      {error ? (
        <div className="rounded-2xl border border-[var(--bl-danger)]/30 bg-[var(--bl-danger)]/10 p-4 text-sm text-[var(--bl-danger)]">
          {error}
        </div>
      ) : null}

      {snapshot ? (
        <div className="space-y-5">
          {snapshotDiff ? (
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center justify-between gap-3">
                <div>
                  <p className="text-sm font-medium text-[var(--bl-text-primary)]">Since previous refresh</p>
                  <p className="text-xs text-[var(--bl-text-secondary)]">Snapshot movement compared with the last poll.</p>
                </div>
                <Badge variant="neutral">Delta view</Badge>
              </div>
              <div className="mt-3 grid gap-3 md:grid-cols-5">
                {[
                  { label: 'Healthy instances', value: snapshotDiff.healthyInstances },
                  { label: 'Active dashboards', value: snapshotDiff.activeDashboards },
                  { label: 'Active backups', value: snapshotDiff.activeBackupTimers },
                  { label: 'Active sessions', value: snapshotDiff.activeSessions },
                  { label: 'Warnings', value: snapshotDiff.warnings },
                ].map((item) => (
                  <div key={item.label} className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                    <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">{item.label}</p>
                    <p className={`mt-2 text-2xl font-semibold ${item.value > 0 ? 'text-[var(--bl-success)]' : item.value < 0 ? 'text-[var(--bl-danger)]' : 'text-[var(--bl-text-primary)]'}`}>
                      {item.value > 0 ? '+' : ''}{item.value}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          ) : null}

          <div className="grid gap-3 md:grid-cols-4">
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <ShieldCheck className="h-4 w-4" />
                Healthy instances
              </div>
              <p className="mt-2 text-2xl font-semibold text-[var(--bl-text-primary)]">{healthyInstances}/2</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <Activity className="h-4 w-4" />
                Active dashboards
              </div>
              <p className="mt-2 text-2xl font-semibold text-[var(--bl-text-primary)]">{activeDashboards}/2</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <CalendarClock className="h-4 w-4" />
                Active backup timers
              </div>
              <p className="mt-2 text-2xl font-semibold text-[var(--bl-text-primary)]">{activeBackupTimers}/2</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <AlertTriangle className="h-4 w-4" />
                Open warnings
              </div>
              <p className="mt-2 text-2xl font-semibold text-[var(--bl-text-primary)]">{snapshot.warnings.length}</p>
            </div>
          </div>

          <div className="grid gap-3 md:grid-cols-4">
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <Wifi className="h-4 w-4" />
                Tailscale IP
              </div>
              <p className="mt-2 break-words text-lg font-semibold text-[var(--bl-text-primary)]">{snapshot.tailscaleIp ?? 'unknown'}</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <Cloud className="h-4 w-4" />
                Emergency Drive
              </div>
              <p className="mt-2 break-words text-lg font-semibold text-[var(--bl-text-primary)]">{snapshot.emergencyDriveUpload.active ? 'active' : 'inactive'}</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <Timer className="h-4 w-4" />
                Next Drive bundle
              </div>
              <p className="mt-2 break-words text-base font-semibold leading-6 text-[var(--bl-text-primary)]">{snapshot.emergencyDriveUpload.nextRun ?? 'unknown'}</p>
            </div>
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm text-[var(--bl-text-secondary)]">
                <ShieldCheck className="h-4 w-4" />
                Generated
              </div>
              <p className="mt-2 break-words text-lg font-semibold text-[var(--bl-text-primary)]">{formatDate(snapshot.generatedAt)}</p>
            </div>
          </div>

          <div className="grid gap-4 xl:grid-cols-[1.2fr_0.8fr]">
            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm font-medium text-[var(--bl-text-primary)]">
                <Activity className="h-4 w-4 text-[var(--bl-accent)]" />
                Active Hermes sessions
              </div>
              <div className="mt-3 grid gap-3 md:grid-cols-3">
                <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                  <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Running now</p>
                  <p className="mt-2 text-2xl font-semibold text-[var(--bl-text-primary)]">{snapshot.activeSessions.active}</p>
                </div>
                <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                  <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Last updated</p>
                  <p className="mt-2 text-sm font-medium text-[var(--bl-text-primary)]">{snapshot.activeSessions.updatedAt ? formatDate(snapshot.activeSessions.updatedAt) : 'unknown'}</p>
                </div>
                <div className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                  <p className="text-xs uppercase tracking-[0.2em] text-[var(--bl-text-tertiary)]">Interpretation</p>
                  <p className="mt-2 text-sm text-[var(--bl-text-secondary)]">Counted from Hermes CLI processes outside the gateway daemons.</p>
                </div>
              </div>
            </div>

            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm font-medium text-[var(--bl-text-primary)]">
                <CalendarClock className="h-4 w-4 text-[var(--bl-accent)]" />
                Cron job state
              </div>
              <div className="mt-3 space-y-2">
                {snapshot.cronJobs.map((job) => (
                  <div key={job.name} className="rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3">
                    <div className="flex items-center justify-between gap-2">
                      <p className="font-medium text-[var(--bl-text-primary)]">{job.label}</p>
                      <Badge variant={job.active ? 'success' : 'error'}>{job.active ? 'active' : 'inactive'}</Badge>
                    </div>
                    <p className="mt-2 text-xs text-[var(--bl-text-secondary)]">Next: {job.nextRun ?? 'unknown'}</p>
                    <p className="text-xs text-[var(--bl-text-secondary)]">Last: {job.lastRun ?? 'unknown'}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {snapshot.warnings.length ? (
            <div className="rounded-2xl border border-[var(--bl-warning)]/40 bg-[var(--bl-warning)]/10 p-4">
              <div className="flex items-center gap-2 font-medium text-[var(--bl-text-primary)]">
                <AlertTriangle className="h-4 w-4 text-[var(--bl-warning)]" />
                Recovery warnings
              </div>
              <div className="mt-3 grid gap-2 md:grid-cols-2">
                {snapshot.warnings.map((warning) => (
                  <div key={warning} className="rounded-xl bg-[var(--bl-surface-card)] px-3 py-2 text-sm text-[var(--bl-text-secondary)]">{warning}</div>
                ))}
              </div>
            </div>
          ) : (
            <div className="flex items-center gap-2 rounded-2xl border border-[var(--bl-success)]/30 bg-[var(--bl-success)]/10 p-4 text-sm text-[var(--bl-text-secondary)]">
              <CheckCircle2 className="h-4 w-4 text-[var(--bl-success)]" />
              Vijay and Bheem recovery paths are healthy.
            </div>
          )}

          <div className="grid gap-4 xl:grid-cols-[1fr_1fr]">
            <RecentAlerts alerts={snapshot.recentAlerts} />

            <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4">
              <div className="flex items-center gap-2 text-sm font-medium text-[var(--bl-text-primary)]">
                <Link2 className="h-4 w-4 text-[var(--bl-accent)]" />
                Quick links
              </div>
              <div className="mt-3 space-y-2">
                {snapshot.quickLinks.map((link) => (
                  <a
                    key={link.href}
                    href={link.href}
                    target="_blank"
                    rel="noreferrer"
                    className="block rounded-xl border border-[var(--bl-border)] bg-[var(--bl-surface-card)] p-3 hover:border-[var(--bl-accent)]"
                  >
                    <p className="font-medium text-[var(--bl-text-primary)]">{link.label}</p>
                    <p className="mt-1 text-sm text-[var(--bl-text-secondary)]">{link.description}</p>
                  </a>
                ))}
              </div>
            </div>
          </div>

          <TrendCards history={history} />

          <div className="grid gap-4 xl:grid-cols-2">
            {snapshot.instances.map((instance) => (
              <InstanceCard key={instance.id} instance={instance} tailscaleIp={snapshot.tailscaleIp} />
            ))}
          </div>

          <div className="text-sm text-[var(--bl-text-secondary)]">
            Disaster recovery details live in{' '}
            <Link href="/hermes/settings" className="text-[var(--bl-accent)] hover:underline">Hermes settings</Link>
            {' '}and the tracked runbook in <span className="font-mono text-xs">docs/hermes-disaster-recovery.md</span>.
          </div>
        </div>
      ) : (
        <div className="rounded-2xl border border-[var(--bl-border)] bg-[var(--bl-surface-muted)] p-4 text-sm text-[var(--bl-text-secondary)]">
          Loading live Hermes operations status...
        </div>
      )}
    </SectionCard>
  );
}
