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

const CompanyContext = createContext();

export const useCompany = () => {
  const context = useContext(CompanyContext);
  if (!context) {
    throw new Error('useCompany must be used within a CompanyProvider');
  }
  return context;
};

const AVAILABLE_COMPANIES = [
  { id: 'c1', name: 'Acme Corp' },
  { id: 'c2', name: 'Tech Solutions' },
  { id: 'c3', name: 'Global Services' }
];

export const CompanyProvider = ({ children }) => {
  const [currentCompany, setCurrentCompany] = useState(() => {
    const saved = localStorage.getItem('currentCompany');
    return saved ? JSON.parse(saved) : AVAILABLE_COMPANIES[0];
  });

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

  const switchCompany = (companyId) => {
    const company = AVAILABLE_COMPANIES.find(c => c.id === companyId);
    if (company) {
      setCurrentCompany(company);
    }
  };

  return (
    <CompanyContext.Provider value={{ 
      currentCompany, 
      switchCompany, 
      availableCompanies: AVAILABLE_COMPANIES 
    }}>
      {children}
    </CompanyContext.Provider>
  );
};
