import React, { createContext, useContext, useState, useEffect } from 'react';
import { usePlatform } from '../platform';

const STORAGE_KEY = 'discord-theme';

export const THEMES = {
  LIGHT: 'theme-light',
  DARK: 'theme-dark',
  ASH: 'theme-darker',
  ONYX: 'theme-midnight',
};

export const THEME_LABELS = {
  [THEMES.LIGHT]: 'Light',
  [THEMES.DARK]: 'Dark',
  [THEMES.ASH]: 'Ash',
  [THEMES.ONYX]: 'Onyx',
};

const ThemeContext = createContext();

export function ThemeProvider({ children }) {
  const { settings } = usePlatform();
  const [theme, setTheme] = useState(() => {
    return localStorage.getItem(STORAGE_KEY) || THEMES.DARK;
  });

  // On mount, check settings.json as fallback when localStorage is empty
  useEffect(() => {
    if (!localStorage.getItem(STORAGE_KEY) && settings) {
      settings.get('theme').then((saved) => {
        if (saved && Object.values(THEMES).includes(saved)) {
          setTheme(saved);
        }
      });
    }
  }, []);

  useEffect(() => {
    document.documentElement.className = theme;
    localStorage.setItem(STORAGE_KEY, theme);
    settings?.set('theme', theme);
  }, [theme]);

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

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