
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

const ModuleContext = createContext();

export const MODULE_GESTION = 'gestion';
export const MODULE_COMPTABILITE = 'comptabilite';

export const ModuleProvider = ({ children }) => {
  // Initialize from localStorage or default to 'gestion'
  const [currentModule, setCurrentModule] = useState(() => {
    const saved = localStorage.getItem('dataven_current_module');
    return saved || MODULE_GESTION;
  });

  const navigate = useNavigate();
  const location = useLocation();

  // Persist to localStorage whenever module changes
  useEffect(() => {
    localStorage.setItem('dataven_current_module', currentModule);
  }, [currentModule]);

  const changeModule = (newModule) => {
    if (newModule === currentModule) return;
    
    setCurrentModule(newModule);
    
    // Smart Navigation Logic
    if (newModule === MODULE_COMPTABILITE) {
      // If switching TO Compta, go to Compta Dashboard unless already deep in a compta page (unlikely if we are in Gesco mode)
      if (!location.pathname.startsWith('/comptabilite')) {
        // navigate('/comptabilite/dashboard');
        navigate('/home');
      }
    } 
    else if (newModule === MODULE_GESTION) {
      // If switching TO Gesco, go to Main Dashboard if currently in a Compta page
      if (location.pathname.startsWith('/comptabilite')) {
        navigate('/home');
      }
    }
  };

  return (
    <ModuleContext.Provider value={{ currentModule, changeModule }}>
      {children}
    </ModuleContext.Provider>
  );
};

export const useModule = () => {
  const context = useContext(ModuleContext);
  if (!context) {
    throw new Error('useModule must be used within a ModuleProvider');
  }
  return context;
};
