"use client";

import { useState } from "react";
import { AuditLogDrawer } from "@/components/mission-control/AuditLogDrawer";
import { GlobalAgentRoster } from "@/components/mission-control/GlobalAgentRoster";
import { MissionControlPanel } from "@/components/mission-control/MissionControlPanel";
import { Button } from "@/components/ui/button";
import { useSessions } from "@/hooks/useMissionControl";

const DEFAULT_PANEL_SLOTS = ["panel-1", "panel-2", "panel-3", "panel-4"] as const;

export function MissionControlLayout(): React.JSX.Element {
  const { sessions } = useSessions();
  const [selectedSessionId, setSelectedSessionId] = useState<string>();

  // First panel: selected session (from roster click) or first available session
  const firstPanelSessionId = selectedSessionId ?? sessions[0]?.id;
  const panelSessionIds = [firstPanelSessionId, undefined, undefined, undefined] as const;

  return (
    <section className="flex h-full min-h-0 flex-col overflow-hidden" aria-label="Mission Control">
      <header className="mb-3 flex items-center justify-end">
        <AuditLogDrawer
          trigger={
            <Button variant="outline" size="sm">
              Audit Log
            </Button>
          }
        />
      </header>

      <div className="grid min-h-0 flex-1 gap-4 xl:grid-cols-[280px_minmax(0,1fr)]">
        <aside className="h-full min-h-0">
          <GlobalAgentRoster
            onSelectSession={setSelectedSessionId}
            {...(selectedSessionId !== undefined ? { selectedSessionId } : {})}
          />
        </aside>
        <main className="h-full min-h-0 overflow-hidden">
          <MissionControlPanel panels={DEFAULT_PANEL_SLOTS} panelSessionIds={panelSessionIds} />
        </main>
      </div>
    </section>
  );
}
