import React, { createContext, useContext, useMemo } from 'react';
import { useColorScheme } from 'react-native';
import type { ThemeTokens } from './tokens';
import { presetThemes, lightTheme, darkTheme } from './presets';
import { useSettingsStore } from '../store/settingsStore';

/**
 * ThemeProvider + useTheme（plan.md「1.2 ThemeProvider」）。
 *
 * - 读取 settingsStore.themeMode（'light' | 'dark' | 'system'）
 * - 'system' 时跟随 useColorScheme()
 * - 解析出实际 ThemeTokens 并通过 Context 下发
 */

interface ThemeContextValue {
  theme: ThemeTokens;
  isDark: boolean;
}

const ThemeContext = createContext<ThemeContextValue>({ theme: lightTheme, isDark: false });

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const themeMode = useSettingsStore(s => s.themeMode);
  const systemColorScheme = useColorScheme();

  const { theme, isDark } = useMemo(() => {
    const resolved = themeMode === 'system'
      ? (systemColorScheme === 'dark' ? 'dark' : 'light')
      : themeMode;
    const tokens = presetThemes[resolved] ?? lightTheme;
    return { theme: tokens, isDark: resolved === 'dark' };
  }, [themeMode, systemColorScheme]);

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

export function useTheme(): ThemeContextValue {
  return useContext(ThemeContext);
}

export { lightTheme, darkTheme, presetThemes };
export { createCommonStyles } from './commonStyles';
export { CATEGORY_PALETTE, getCategoryColor, CHANNEL_BRAND_COLORS } from './palette';
export type { ThemeTokens } from './tokens';
