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

export type Theme = 'skeen' | 'homenest' | 'clasico';

interface ThemeContextValue {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);

const STORAGE_KEY = 'skeen-theme';
const THEME_ORDER: Theme[] = ['skeen', 'homenest', 'clasico'];

function getInitialTheme(): Theme {
  if (typeof window === 'undefined') return 'skeen';
  const stored = window.localStorage.getItem(STORAGE_KEY) as Theme | null;
  if (stored === 'skeen' || stored === 'homenest' || stored === 'clasico') return stored;
  return 'skeen';
}

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setThemeState] = useState<Theme>(getInitialTheme);

  const setTheme = (next: Theme) => {
    setThemeState(next);
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(STORAGE_KEY, next);
      document.documentElement.setAttribute('data-theme', next);
    }
  };

  const toggleTheme = () => {
    const idx = THEME_ORDER.indexOf(theme);
    setTheme(THEME_ORDER[(idx + 1) % THEME_ORDER.length]);
  };

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

export function useTheme() {
  const ctx = useContext(ThemeContext);
  if (!ctx) throw new Error('useTheme must be used within ThemeProvider');
  return ctx;
}
