import { useQuery } from '@tanstack/react-query';
import type { DetailTabId } from '../../lib/urlState';

export interface DetailTab {
  id: DetailTabId;
  labelKey: string; // resolves against the 'detail' i18n namespace
}

/** All detail tabs in display order. Browser/SSH are conditional — see
 *  useVisibleDetailTabs. */
export const LOCAL_TABS: DetailTab[] = [
  { id: 'overview', labelKey: 'tabs.overview' },
  { id: 'activity', labelKey: 'tabs.activity' },
  { id: 'files', labelKey: 'tabs.files' },
  { id: 'trace', labelKey: 'tabs.trace' },
  { id: 'browser', labelKey: 'tabs.browser' },
  { id: 'ssh', labelKey: 'tabs.ssh' },
];

/**
 * The detail tabs visible for a task. Browser and SSH only appear while their
 * session is live (so the tab carries the live signal). Single source of truth
 * shared by the detail panel and the tablet chat header so the two never
 * disagree. The console-status / task-session queries are keyed the same as the
 * ones BrowserTab/ConsoleTab use, so react-query dedupes — no extra fetch.
 */
export function useVisibleDetailTabs(taskId: number | null | undefined): DetailTab[] {
  const { data: consoleStatus } = useQuery<{ active: boolean }>({
    queryKey: ['console-status', taskId],
    queryFn: async () => {
      const r = await fetch(`/api/local/tasks/${taskId}/console/status`);
      return r.ok ? r.json() : { active: false };
    },
    enabled: taskId != null,
    refetchInterval: 5000,
  });
  const { data: browserSession } = useQuery<{ available: boolean }>({
    queryKey: ['task-session', taskId],
    queryFn: async () => {
      const r = await fetch(`/api/local/browser/sessions/task-session/${taskId}`);
      return r.ok ? r.json() : { available: false };
    },
    enabled: taskId != null,
    refetchInterval: 5000,
  });
  const showSsh = consoleStatus?.active === true;
  const showBrowser = browserSession?.available === true;
  return LOCAL_TABS.filter(
    (t) => (t.id !== 'ssh' || showSsh) && (t.id !== 'browser' || showBrowser),
  );
}
