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',
};

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

const VALID_THEMES = Object.values(THEMES);

function normalize(value) {
  return VALID_THEMES.includes(value) ? value : THEMES.DARK;
}

const ThemeContext = createContext();

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

  const setTheme = (next) => setThemeState(normalize(next));
  const toggleTheme = () =>
    setThemeState((prev) => (prev === THEMES.DARK ? THEMES.LIGHT : 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 && VALID_THEMES.includes(saved)) {
          setThemeState(saved);
        }
      });
    }
  }, []);

  useEffect(() => {
    // global.css uses [data-theme='dark'] / [data-theme='light']
    const short = theme === THEMES.LIGHT ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', short);
    // keep className in sync for any legacy selectors that rely on it
    document.documentElement.className = theme;
    localStorage.setItem(STORAGE_KEY, theme);
    settings?.set('theme', theme);
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, setTheme, toggleTheme, 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;
}
