// template/src/theme/ThemeProvider/tsx
import React, { createContext, useContext, useState, ReactNode } from 'react';
import { ProcessedTheme, processTokens, BrandName } from './tokenProcessor';

// Theme context type
interface ThemeContextType {
  theme: ProcessedTheme;
  themeName: 'light' | 'dark';
  brandName: BrandName;
  toggleTheme: () => void;
  setTheme: (themeName: 'light' | 'dark') => void;
  setBrand: (brandName: BrandName) => void;
  isLoading: boolean;
}

// Create the context
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// ThemeProvider props
interface ThemeProviderProps {
  children: ReactNode;
  initialTheme?: 'light' | 'dark';
  initialBrand?: BrandName;
}

// ThemeProvider component
export const ThemeProvider: React.FC<ThemeProviderProps> = ({ 
  children, 
  initialTheme = 'light',
  initialBrand = 'default' as BrandName
}) => {
  const [themeName, setThemeName] = useState<'light' | 'dark'>(initialTheme);
  const [brandName, setBrandName] = useState<BrandName>(initialBrand);
  
  // Process theme synchronously (no loading state needed)
  const theme = processTokens(brandName, themeName);
  
  const toggleTheme = () => {
    setThemeName(prev => prev === 'light' ? 'dark' : 'light');
  };
  
  const setThemeMode = (newTheme: 'light' | 'dark') => {
    setThemeName(newTheme);
  };
  
  const setBrandMode = (newBrand: BrandName) => {
    setBrandName(newBrand);
  };
  
  const contextValue: ThemeContextType = {
    theme,
    themeName,
    brandName,
    toggleTheme,
    setTheme: setThemeMode,
    setBrand: setBrandMode,
    isLoading: false, // No async loading anymore
  };
  
  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
};

// Custom hook to use theme
export const useTheme = (): ThemeContextType => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};