import { createContext, useContext } from 'react';
import type { ProjectDefinition } from '../../components/Workspace';

export type PreviewContextValue = {
  slug: string | null;
  cwdSlug: string | null;
  url: string | null;
  port: number | null;
  loading: boolean;
  error: string | null;
  stopped: boolean;
  iframeKey: number;
  projects: ProjectDefinition[];
  startServer: (slug: string) => void;
  stopServer: () => void;
  restartServer: () => void;
  refresh: () => void;
  setSelectedSlug: (slug: string | null) => void;
  clearError: () => void;
};

export const PreviewContext = createContext<PreviewContextValue | null>(null);

export const usePreview = () => {
  const ctx = useContext(PreviewContext);
  if (!ctx) throw new Error('usePreview must be used within PreviewProvider');
  return ctx;
};
