import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import type { Project } from '../types';

interface ProjectContextType {
  currentProject: Project | null;
  setCurrentProject: (project: Project | null) => void;
  clearProject: () => void;
}

const ProjectContext = createContext<ProjectContextType | null>(null);

const PROJECT_STORAGE_KEY = 'project_memory_current_project';

export function ProjectProvider({ children }: { children: ReactNode }) {
  const [currentProject, setCurrentProjectState] = useState<Project | null>(null);

  // Load from localStorage on mount
  useEffect(() => {
    const stored = localStorage.getItem(PROJECT_STORAGE_KEY);
    if (stored) {
      try {
        setCurrentProjectState(JSON.parse(stored));
      } catch {
        localStorage.removeItem(PROJECT_STORAGE_KEY);
      }
    }
  }, []);

  const setCurrentProject = (project: Project | null) => {
    setCurrentProjectState(project);
    if (project) {
      localStorage.setItem(PROJECT_STORAGE_KEY, JSON.stringify(project));
    } else {
      localStorage.removeItem(PROJECT_STORAGE_KEY);
    }
  };

  const clearProject = () => {
    setCurrentProjectState(null);
    localStorage.removeItem(PROJECT_STORAGE_KEY);
  };

  return (
    <ProjectContext.Provider value={{ currentProject, setCurrentProject, clearProject }}>
      {children}
    </ProjectContext.Provider>
  );
}

export function useProject() {
  const context = useContext(ProjectContext);
  if (!context) {
    throw new Error('useProject must be used within a ProjectProvider');
  }
  return context;
}
