import {
  createContext,
  useContext,
  useMemo,
  useState,
  type PropsWithChildren,
} from 'react';
import type { AppPageDescriptor, AppStoreSnapshot } from '../types';

type AppStoreContextValue = AppStoreSnapshot & {
  setCurrentPage: (page: AppPageDescriptor) => void;
  setFocusedComponentId: (focusedComponentId: string | null) => void;
};

const defaultPage: AppPageDescriptor = {
  id: 'app-log:live',
  title: 'Codex Live / Codex Live',
  topMenu: 'chat',
  section: 'live',
};

const AppStoreContext = createContext<AppStoreContextValue | null>(null);

export function AppStoreProvider({ children }: PropsWithChildren) {
  const [currentPage, setCurrentPage] = useState<AppPageDescriptor>(defaultPage);
  const [focusedComponentId, setFocusedComponentId] = useState<string | null>(null);

  const value = useMemo<AppStoreContextValue>(
    () => ({
      currentPage,
      focusedComponentId,
      setCurrentPage,
      setFocusedComponentId,
    }),
    [currentPage, focusedComponentId],
  );

  return <AppStoreContext.Provider value={value}>{children}</AppStoreContext.Provider>;
}

export function useAppStoreContext() {
  const context = useContext(AppStoreContext);

  if (!context) {
    throw new Error('useAppStoreContext must be used within an AppStoreProvider.');
  }

  return context;
}
