import { useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useConsoleSession } from '../../../hooks/useConsoleSession';
import type { ConsoleStatus } from '../../../lib/ssh-console-types';
import { TerminalView, type TerminalViewHandle } from './console/TerminalView';
import { ConsoleHeader } from './console/ConsoleHeader';
import { MobileKeyboardBar } from './console/MobileKeyboardBar';
import { ScrollToBottomButton } from './console/ScrollToBottomButton';
import { useViewportNarrow } from '../../layout/TopBar';

export function ConsoleTab({ taskId }: { taskId: number }) {
  const { data: status } = useQuery<ConsoleStatus>({
    queryKey: ['console-status', taskId],
    queryFn: async () => {
      const r = await fetch(`/api/local/tasks/${taskId}/console/status`);
      return r.ok ? r.json() : { active: false };
    },
    refetchInterval: 5000,
  });
  const session = useConsoleSession(taskId);
  const terminalRef = useRef<TerminalViewHandle>(null);
  // 768px = Tailwind md breakpoint. Below this we consider the user to be on
  // a phone/tablet without a physical keyboard, so the on-screen keyboard bar
  // and scroll-to-bottom FAB become useful.
  const compactMode = useViewportNarrow(768);

  return (
    <div className="flex flex-col flex-1 min-h-0">
      <ConsoleHeader state={session.state} status={status ?? null} />
      <div className="flex-1 min-h-0 relative">
        <TerminalView ref={terminalRef} session={session} />
        {compactMode && <ScrollToBottomButton terminalRef={terminalRef} />}
      </div>
      {compactMode && <MobileKeyboardBar session={session} />}
    </div>
  );
}
