// Main App — routing + Tweaks

const { useState, useEffect, useCallback } = React;

const THEMES = {
  minimal: {
    name: 'ミニマルホワイト',
    bg: '#FAFAF7',
    bgSecondary: '#F5F0E8',
    bgAccent: '#EAF3F9',
    accent: '#4A7EA5',
    accentLight: '#7BAEC8',
    text: '#2C2C2A',
    textMuted: '#7A7A72',
    border: '#E8E4DC',
    shadow: 'rgba(74,126,165,0.12)',
  },
  beige: {
    name: 'ウォームベージュ',
    bg: '#F8F3EA',
    bgSecondary: '#EEE5D8',
    bgAccent: '#DFF0F5',
    accent: '#8B6F5E',
    accentLight: '#B89A8A',
    text: '#2C2820',
    textMuted: '#7A6E62',
    border: '#DDD5C8',
    shadow: 'rgba(139,111,94,0.12)',
  },
  blue: {
    name: 'エアリーブルー',
    bg: '#EEF5FA',
    bgSecondary: '#E0EDF5',
    bgAccent: '#F8F4EE',
    accent: '#2E6E9E',
    accentLight: '#5A9EC8',
    text: '#1A2C3A',
    textMuted: '#4A6278',
    border: '#C5DDE8',
    shadow: 'rgba(46,110,158,0.15)',
  },
};

function TweaksPanel({ tweaks, setTweaks, visible }) {
  if (!visible) return null;
  return (
    <div style={{
      position: 'fixed', bottom: 24, right: 24, zIndex: 9999,
      background: '#fff', border: '1px solid #E0E0E0', borderRadius: 14,
      padding: '20px 22px', boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
      minWidth: 220,
    }}>
      <p style={{ fontSize: 13, fontWeight: 700, color: '#333', marginBottom: 14, letterSpacing: '0.05em' }}>Tweaks</p>

      <p style={{ fontSize: 11, color: '#888', marginBottom: 8 }}>カラーテーマ</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 18 }}>
        {Object.entries(THEMES).map(([key, th]) => (
          <button key={key} onClick={() => {
            const next = { ...tweaks, theme: key };
            setTweaks(next);
            window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
          }} style={{
            padding: '8px 12px', borderRadius: 8, border: `1.5px solid ${tweaks.theme === key ? th.accent : '#E0E0E0'}`,
            background: tweaks.theme === key ? th.bgAccent : '#FAFAFA',
            cursor: 'pointer', fontSize: 12, color: tweaks.theme === key ? th.accent : '#555',
            fontWeight: tweaks.theme === key ? 600 : 400, textAlign: 'left',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <div style={{ width: 14, height: 14, borderRadius: '50%', background: th.accent, flexShrink: 0 }} />
            {th.name}
          </button>
        ))}
      </div>

      <p style={{ fontSize: 11, color: '#888', marginBottom: 8 }}>見出しフォント</p>
      <div style={{ display: 'flex', gap: 6 }}>
        {[['serif', '明朝体'], ['sans', 'ゴシック体']].map(([val, label]) => (
          <button key={val} onClick={() => {
            const next = { ...tweaks, fontStyle: val };
            setTweaks(next);
            window.parent.postMessage({ type: '__edit_mode_set_keys', edits: next }, '*');
          }} style={{
            flex: 1, padding: '7px 0', borderRadius: 6, border: `1.5px solid ${tweaks.fontStyle === val ? '#4A7EA5' : '#E0E0E0'}`,
            background: tweaks.fontStyle === val ? '#EAF3F9' : '#FAFAFA',
            cursor: 'pointer', fontSize: 12, color: tweaks.fontStyle === val ? '#4A7EA5' : '#555',
            fontFamily: val === 'serif' ? "'Noto Serif JP', serif" : "'Noto Sans JP', sans-serif",
          }}>{label}</button>
        ))}
      </div>
    </div>
  );
}

function App() {
  const saved = (() => { try { return JSON.parse(localStorage.getItem('ribe_page') || '{}'); } catch { return {}; } })();
  const [page, setPageRaw] = useState(saved.page || 'home');
  const [tweaksVisible, setTweaksVisible] = useState(false);

  const defaultTweaks = /*EDITMODE-BEGIN*/{"theme": "minimal", "fontStyle": "serif"}/*EDITMODE-END*/;
  const [tweaks, setTweaks] = useState(() => {
    try { return { ...defaultTweaks, ...JSON.parse(localStorage.getItem('ribe_tweaks') || '{}') }; } catch { return defaultTweaks; }
  });

  const setPage = useCallback((p) => {
    setPageRaw(p);
    localStorage.setItem('ribe_page', JSON.stringify({ page: p }));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  useEffect(() => {
    localStorage.setItem('ribe_tweaks', JSON.stringify(tweaks));
  }, [tweaks]);

  // Tweaks toggle
  useEffect(() => {
    const handler = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksVisible(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksVisible(false);
    };
    window.addEventListener('message', handler);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', handler);
  }, []);

  const theme = THEMES[tweaks.theme] || THEMES.minimal;
  const headingFont = tweaks.fontStyle === 'sans' ? "'Noto Sans JP', sans-serif" : "'Noto Serif JP', serif";

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, fontFamily: "'Noto Sans JP', sans-serif", color: theme.text }}>
      <style>{`
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { margin: 0; }
        h1, h2, h3 { font-family: ${headingFont} !important; }
        @media (max-width: 640px) {
          .nav-desktop { display: none !important; }
          .nav-mobile { display: flex !important; }
          table td { font-size: 12px !important; }
        }
      `}</style>

      <Nav currentPage={page} setPage={setPage} theme={theme} />

      <main>
        {page === 'home' && <HomePage setPage={setPage} theme={theme} />}
        {page === 'profile' && <ProfilePage theme={theme} />}
        {page === 'learn' && <LearnPage theme={theme} />}
        {page === 'books' && <BooksPage theme={theme} />}
        {page === 'review' && <ReviewPage theme={theme} />}
      </main>

      <Footer theme={theme} />
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} visible={tweaksVisible} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
