import { createContext, useCallback, useContext, useState } from "react";

export interface CodePreviewPayload {
  id: string;
  code: string;
  language: string;
  lineCount: number;
  title?: string;
  subtitle?: string;
}

interface CodePreviewContextValue {
  activeCode: CodePreviewPayload | null;
  openCodePreview: (payload: CodePreviewPayload) => void;
  closeCodePreview: () => void;
}

const CodePreviewContext = createContext<CodePreviewContextValue | null>(null);

export function CodePreviewProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [activeCode, setActiveCode] = useState<CodePreviewPayload | null>(
    null,
  );

  const openCodePreview = useCallback((payload: CodePreviewPayload) => {
    setActiveCode(payload);
  }, []);

  const closeCodePreview = useCallback(() => {
    setActiveCode(null);
  }, []);

  return (
    <CodePreviewContext.Provider
      value={{ activeCode, openCodePreview, closeCodePreview }}
    >
      {children}
    </CodePreviewContext.Provider>
  );
}

export function useCodePreview() {
  const ctx = useContext(CodePreviewContext);
  if (!ctx) {
    throw new Error(
      "useCodePreview must be used within CodePreviewProvider",
    );
  }
  return ctx;
}
