import { useEffect, useState } from 'react';
import type { ConnState } from '../../../../hooks/useConsoleSession';
import type { ConsoleStatus } from '../../../../lib/ssh-console-types';

function fmtElapsed(ms: number): string {
  const total = Math.floor(ms / 1000);
  const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
  if (h) return `${h}h ${m}m`;
  if (m) return `${m}m ${s}s`;
  return `${s}s`;
}

export function ConsoleHeader({ state, status }: { state: ConnState; status: ConsoleStatus | null }) {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);

  if (state.kind === 'no_session') {
    return <div className="px-3 py-2 text-sm text-slate-500">No active console — AI will open one when needed.</div>;
  }
  if (state.kind === 'connecting' || state.kind === 'replaying') {
    return <div className="px-3 py-2 text-sm text-amber-600">{state.kind === 'connecting' ? 'Connecting…' : 'Restoring scrollback…'}</div>;
  }
  if (state.kind === 'disconnected') {
    return <div className="px-3 py-2 text-sm text-red-700 dark:text-red-300">Disconnected ({state.reason ?? 'unknown'}).</div>;
  }
  const startedAt = status?.started_at ? new Date(status.started_at).getTime() : now;
  const lastAt = status?.last_activity_at ? new Date(status.last_activity_at).getTime() : now;
  return (
    <div className="px-3 py-2 text-sm text-slate-700 border-b border-slate-200 flex items-center gap-3">
      <span className="text-green-600">● Connected</span>
      <span className="text-slate-500">conn {status?.connection_id ?? '—'}</span>
      <span className="text-slate-500">uptime {fmtElapsed(now - startedAt)}</span>
      <span className="text-slate-500">idle {fmtElapsed(now - lastAt)}</span>
      {!state.canWrite && <span className="ml-auto rounded bg-slate-100 px-2 py-0.5 text-xs">viewer (read-only)</span>}
    </div>
  );
}
