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

export const BrowserScreen = () => {
  const isMobile = useIsMobile();
  const [selectedId, setSelectedId] = useGlobal<string | null>('BROWSER_SELECTED_TAB', null);
  const workspace = useWorkspacesState<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}
        mobilePanelId={mobilePanelId}
        onMobilePanelChange={mobilePanelId ? () => onMobileBack() : undefined}
      />
    </div>
  );
};
