'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { BrandConfig, getBrandConfig, saveBrandConfig, resetBrandConfig, defaultBrandConfig } from './brand-config';

interface BrandContextType {
  config: BrandConfig;
  updateConfig: (updates: Partial<BrandConfig>) => void;
  resetConfig: () => void;
  isLoaded: boolean;
}

const BrandContext = createContext<BrandContextType | undefined>(undefined);

export function BrandProvider({ children }: { children: ReactNode }) {
  const [config, setConfig] = useState<BrandConfig>(defaultBrandConfig);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    setConfig(getBrandConfig());
    setIsLoaded(true);
  }, []);

  const updateConfig = (updates: Partial<BrandConfig>) => {
    const newConfig = saveBrandConfig(updates);
    setConfig(newConfig);
  };

  const resetConfigHandler = () => {
    const newConfig = resetBrandConfig();
    setConfig(newConfig);
  };

  return (
    <BrandContext.Provider value={{ config, updateConfig, resetConfig: resetConfigHandler, isLoaded }}>
      {children}
    </BrandContext.Provider>
  );
}

export function useBrand() {
  const context = useContext(BrandContext);
  if (context === undefined) {
    throw new Error('useBrand must be used within a BrandProvider');
  }
  return context;
}
