import { useMemo, useCallback } from 'react';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceView } from 'officerdev';
import { useDashboardState } from 'state/useDashboardState';
import { useIsMobile } from 'hooks/useIsMobile';
import { useGlobal } from 'hooks/useGlobal';
import { defaultLayout } from './defaultLayout';
import { TabList } from './TabList';
import { TabPreview } from './TabPreview';

const PROMPT_PREFIX = `You are a browser assistant. The user has connected Chrome tabs via the Officer Browser Relay. You have a 'browser' tool — use it to list tabs, take screenshots, navigate, evaluate JavaScript, and get page info. When asked about a page, take a screenshot first.`;

export const BrowserScreen = () => {
  const isMobile = useIsMobile();
  const [selectedId, setSelectedId] = useGlobal<string | null>('BROWSER_SELECTED_TAB', null);
  const workspace = useDashboardState<LayoutNode>('screens/browser', defaultLayout);

  const components: PanelComponents = useMemo(
    () => ({
      'browser-tabs': TabList,
      'browser-preview': TabPreview,
    }),
    [],
  );

  const mobilePanelId = isMobile && selectedId ? 'browser-preview' : undefined;
  const onMobileBack = useCallback(() => setSelectedId(null), [setSelectedId]);

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceView
        workspace={workspace}
        locked
        components={components}
        promptPrefix={PROMPT_PREFIX}
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={mobilePanelId ? () => onMobileBack() : undefined}
      />
    </div>
  );
};
