import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

export interface NavigationState {
  previousRoute?: string;
  focusGroupId?: string;
  focusGroupTab?: 'setup' | 'review' | 'participants';
  isNewFocusGroup?: boolean;
  focusGroupData?: any;
  folderId?: string; // For persona list folder context
}

interface NavigationContextType {
  navigationState: NavigationState;
  setNavigationState: (state: NavigationState) => void;
  clearNavigationState: () => void;
  setPreviousRoute: (route: string, additionalData?: Partial<NavigationState>) => void;
}

const NavigationContext = createContext<NavigationContextType | undefined>(undefined);

const NAVIGATION_STORAGE_KEY = 'synthetic-society-navigation-state';

export const NavigationProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [navigationState, setNavigationState] = useState<NavigationState>(() => {
    try {
      const stored = localStorage.getItem(NAVIGATION_STORAGE_KEY);
      return stored ? JSON.parse(stored) : {};
    } catch {
      return {};
    }
  });

  useEffect(() => {
    localStorage.setItem(NAVIGATION_STORAGE_KEY, JSON.stringify(navigationState));
  }, [navigationState]);

  const setPreviousRoute = (route: string, additionalData?: Partial<NavigationState>) => {
    setNavigationState({
      ...navigationState,
      previousRoute: route,
      ...additionalData
    });
  };

  const clearNavigationState = () => {
    setNavigationState({});
    localStorage.removeItem(NAVIGATION_STORAGE_KEY);
  };

  return (
    <NavigationContext.Provider 
      value={{ 
        navigationState, 
        setNavigationState, 
        clearNavigationState, 
        setPreviousRoute 
      }}
    >
      {children}
    </NavigationContext.Provider>
  );
};

export const useNavigation = (): NavigationContextType => {
  const context = useContext(NavigationContext);
  if (!context) {
    throw new Error('useNavigation must be used within a NavigationProvider');
  }
  return context;
};