import { useCallback } from 'react';
import type { LayoutNode, AppRegistryMap, PanelComponents } from './types';
import { updateSizes, collectPanelConfigs } from './layout-utils';
import { WorkspaceProvider, inertInteraction } from './WorkspaceContext';
import { WorkspaceRenderer } from './WorkspaceRenderer';
import { useAppRegistry } from '../../AppRegistry/useAppRegistry';

type WorkspaceLayoutProps = {
  layout: LayoutNode;
  onLayoutChange: (layout: LayoutNode | ((prev: LayoutNode) => LayoutNode)) => void;
  registry?: AppRegistryMap;
  components?: PanelComponents;
  cwd?: string;
  noHeader?: boolean;
};

const noop = () => {};

// No mobile props. This renderer had `isMobile`/`mobilePanelId`/`onMobileBack` pass-throughs that none of
// its ten call sites ever set, so the mobile collapse they feed was permanently off here — and being
// optional, that read as a feature rather than the dead wiring it was. `WorkspaceView` is where mobile
// collapse actually happens, and it passes those to `WorkspaceRenderer` itself.
export const WorkspaceLayout = ({ layout, onLayoutChange, registry: registryProp, components, cwd, noHeader }: WorkspaceLayoutProps) => {
  const { registry: globalRegistry } = useAppRegistry();
  const registry = registryProp ?? globalRegistry;

  // An updater, for the same reason `WorkspaceView`'s eight mutations are: `WorkspaceRenderer` debounces
  // this by 500 ms, so a tree computed here is 500 ms stale by the time it is written.
  const handleResized = useCallback(
    (groupId: string, sizes: number[]) => {
      onLayoutChange((prev) => updateSizes(prev, groupId, sizes));
    },
    [onLayoutChange],
  );

  // No workspace identity: this is the locked/preview renderer, used for job detail panes, settings and
  // dashboard previews. It is not a dashboard and not a screen, and a panel that asks should be told so
  // rather than handed something that parses.
  return (
    <WorkspaceProvider value={{ workspace: null, cwd: cwd ?? '~', panelConfigs: collectPanelConfigs(layout), ...inertInteraction, isMobile: false, onMobileBack: null }}>
      <WorkspaceRenderer
        layout={layout}
        registry={registry}
        components={components}
        noHeader={noHeader}
        onSetApp={noop}
        onSplit={noop}
        onRemove={noop}
        onResized={handleResized}
      />
    </WorkspaceProvider>
  );
};
