// theme.jsx — ライト/ダーク対応のテーマコンテキスト

const LIGHT = {
  ink: '#0A0A0A', ink2: '#1a1a1a', ink3: '#3A3A3C', ink4: '#8E8E93',
  line: '#E5E5EA', lineSoft: '#EFEEE9',
  bg: '#F7F6F2', bgCard: '#FFFFFF', bgSoft: '#EFEEE9',
  primary: '#2E7D52', primarySoft: '#E3F0E8',
  purple: '#6B46C1', purple2: '#7C3AED', orange: '#C65D1E',
  danger: '#C0392B',
  shadow: '0 1px 3px rgba(0,0,0,0.04)',
  shadowLg: '0 10px 30px rgba(0,0,0,0.08)',
};

const DARK = {
  ink: '#F5F5F7', ink2: '#E8E8ED', ink3: '#A1A1A6', ink4: '#636366',
  line: '#2A2A2C', lineSoft: '#1C1C1E',
  bg: '#0A0A0B', bgCard: '#17171A', bgSoft: '#1C1C1E',
  primary: '#5BB68A', primarySoft: '#1B3226',
  purple: '#B794F4', purple2: '#A78BFA', orange: '#F3934E',
  danger: '#FF6B5A',
  shadow: '0 1px 3px rgba(0,0,0,0.3)',
  shadowLg: '0 10px 30px rgba(0,0,0,0.4)',
};

const ThemeContext = React.createContext(LIGHT);
const useT = () => React.useContext(ThemeContext);

function ThemeProvider({ children }) {
  const [mode, setMode] = React.useState(() => {
    try {
      const saved = localStorage.getItem('echo.theme');
      if (saved) return saved;
      // OS設定に従う
      if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        return 'dark';
      }
    } catch (e) {}
    return 'light';
  });

  React.useEffect(() => {
    try { localStorage.setItem('echo.theme', mode); } catch (e) {}
    const colors = mode === 'dark' ? DARK : LIGHT;
    document.body.style.background = colors.bg;
    document.body.style.color = colors.ink;
    // iOS の上部ノッチ/ステータスバー色をテーマに同期
    const meta = document.querySelector('meta[name="theme-color"]');
    if (meta) meta.setAttribute('content', colors.bg);
    // iOSホーム画面起動時のステータスバースタイル
    const statusStyle = document.querySelector('meta[name="apple-mobile-web-app-status-bar-style"]');
    if (statusStyle) {
      statusStyle.setAttribute('content', mode === 'dark' ? 'black-translucent' : 'default');
    }
  }, [mode]);

  const theme = mode === 'dark' ? { ...DARK, mode, setMode } : { ...LIGHT, mode, setMode };
  return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
}

Object.assign(window, { ThemeContext, ThemeProvider, useT, LIGHT, DARK });
