import { createContext, type ReactNode, useContext, useMemo, useState } from "react";

interface WorkspaceContextValue {
  workspaceId: "PERSONAL" | "AI_SALES_CRM";
  setWorkspaceId: (id: "PERSONAL" | "AI_SALES_CRM") => void;
}

const WorkspaceContext = createContext<WorkspaceContextValue | null>(null);

export function WorkspaceProvider({ children }: { children: ReactNode }) {
  const [workspaceId, setWorkspaceIdState] = useState<"PERSONAL" | "AI_SALES_CRM">("PERSONAL");

  const setWorkspaceId = (id: "PERSONAL" | "AI_SALES_CRM") => {
    setWorkspaceIdState(id);
    // Persist to localStorage
    if (typeof window !== "undefined") {
      localStorage.setItem("workspace_id", id);
    }
  };

  // Initialize from localStorage
  if (typeof window !== "undefined") {
    const saved = localStorage.getItem("workspace_id") as "PERSONAL" | "AI_SALES_CRM" | null;
    if (saved && (saved === "PERSONAL" || saved === "AI_SALES_CRM")) {
      setWorkspaceIdState(saved);
    }
  }

  const value = useMemo(() => ({ workspaceId, setWorkspaceId }), [workspaceId]);

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

export function useWorkspace() {
  const context = useContext(WorkspaceContext);
  if (!context) {
    throw new Error("useWorkspace must be used within WorkspaceProvider");
  }
  return context;
}
