// app.jsx — main app v2

const { useState: useSApp, useEffect: useEApp, useMemo: useMApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "brandName": "Investire Ragionato",
  "accent": "blue"
}/*EDITMODE-END*/;

function useTweaks(defaults) {
  const [tweaks, setTweaks] = useSApp(defaults);
  const setTweak = (k, v) => {
    let edits;
    if (typeof k === 'object') edits = k;
    else edits = { [k]: v };
    setTweaks((t) => ({ ...t, ...edits }));
    try { window.parent.postMessage({ type: '__edit_mode_set_keys', edits }, '*'); } catch {}
  };
  return [tweaks, setTweak];
}

function parseHash() {
  const hash = window.location.hash.replace(/^#\/?/, '');
  if (!hash || hash === 'home') return { view: 'home' };
  if (hash === 'path') return { view: 'path' };
  if (hash === 'library') return { view: 'library' };
  if (hash === 'about') return { view: 'about' };
  if (hash === 'glossario') return { view: 'glossario' };
  if (hash.startsWith('article/')) return { view: 'article', id: hash.slice(8) };
  return { view: 'home' };
}

function routeToHash(r) {
  if (!r || r.view === 'home') return '#/home';
  if (r.view === 'article') return `#/article/${r.id}`;
  return `#/${r.view}`;
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useSApp(parseHash);
  const [editOpen, setEditOpen] = useSApp(false);
  const [progressData, progressApi] = useProgress();
  const [darkMode, setDarkMode] = useSApp(() => {
    try { return localStorage.getItem('ir_dark') === '1'; } catch { return false; }
  });
  const toggleDark = () => setDarkMode((d) => {
    const next = !d;
    try { localStorage.setItem('ir_dark', next ? '1' : '0'); } catch {}
    return next;
  });

  // Sync dark class to <body> so body background + any out-of-app elements work
  useEApp(() => {
    document.body.classList.toggle('dark', darkMode);
    document.documentElement.classList.toggle('dark', darkMode);
  }, [darkMode]);

  const chapters = window.SF_DATA.CHAPTERS;
  const totalArticles = chapters.reduce((n, c) => n + c.articles.length, 0);

  // Sync hash → route on back/forward
  useEApp(() => {
    const onHashChange = () => setRoute(parseHash());
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  // Edit mode protocol
  useEApp(() => {
    const onMsg = (e) => {
      if (e.data?.type === '__activate_edit_mode') setEditOpen(true);
      if (e.data?.type === '__deactivate_edit_mode') setEditOpen(false);
    };
    window.addEventListener('message', onMsg);
    try { window.parent.postMessage({ type: '__edit_mode_available' }, '*'); } catch {}
    return () => window.removeEventListener('message', onMsg);
  }, []);

  const onNav = (r) => {
    window.location.hash = routeToHash(r);
    setRoute(r);
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  const onArticle = (id) => onNav({ view: 'article', id });
  const onChapter = (id) => {
    setRoute({ view: 'path' });
    window.scrollTo({ top: 0 });
    setTimeout(() => {
      const el = document.querySelector(`[data-chapter-anchor="${id}"]`);
      if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 80, behavior: 'smooth' });
    }, 50);
  };

  const className = `app accent-${tweaks.accent}${darkMode ? ' dark' : ''}`;

  return (
    <div className={className}>
      <TopNav view={route.view} onNav={onNav} progressData={progressData} totalArticles={totalArticles} brandName={tweaks.brandName} accent={tweaks.accent} darkMode={darkMode} toggleDark={toggleDark} />
      <main className="main">
        {route.view === 'home' && <HomeView chapters={chapters} progressData={progressData} onNav={onNav} onArticle={onArticle} onChapter={onChapter} brandName={tweaks.brandName} pathStyle="modules" />}
        {route.view === 'path' && <PathView chapters={chapters} progressData={progressData} onArticle={onArticle} onChapter={onChapter} />}
        {route.view === 'about' && <AboutView brandName={tweaks.brandName} onNav={onNav} />}
        {route.view === 'library' && <LibraryView chapters={chapters} progressData={progressData} onArticle={onArticle} />}
        {route.view === 'article' && <ArticleView articleId={route.id} chapters={chapters} progressData={progressData} setVisited={progressApi.setVisited} onNav={onNav} onArticle={onArticle} />}
        {route.view === 'glossario' && <GlossarioView onNav={onNav} />}
      </main>

      {editOpen && (
        <TweaksPanel tweaks={tweaks} setTweak={setTweak} resetProgress={progressApi.reset} onClose={() => {
          setEditOpen(false);
          try { window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*'); } catch {}
        }} />
      )}
    </div>
  );
}

function TweaksPanel({ tweaks, setTweak, resetProgress, onClose }) {
  return (
    <div style={{
      position: 'fixed', right: 20, bottom: 20, width: 320,
      background: 'var(--bg)', border: '1px solid var(--hairline-2)',
      borderRadius: 16, padding: 20, zIndex: 100,
      boxShadow: '0 20px 60px rgba(0,0,0,0.15)',
      fontFamily: 'var(--sans)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
        <h3 style={{ margin: 0, fontFamily: 'var(--display)', fontSize: 16, fontWeight: 700, letterSpacing: '-0.02em' }}>Tweaks</h3>
        <button onClick={onClose} style={{ border: 0, background: 'transparent', color: 'var(--ink-3)', fontSize: 20, cursor: 'pointer' }}>×</button>
      </div>

      <Section label="BRAND">
        <input type="text" value={tweaks.brandName} onChange={(e) => setTweak('brandName', e.target.value)}
          style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--hairline-2)', borderRadius: 6, fontSize: 13, fontFamily: 'inherit' }} />
      </Section>

      <Section label="ACCENT">
        <Radio value={tweaks.accent} onChange={(v) => setTweak('accent', v)} options={[
          { id: 'blue', label: 'Blu' },
          { id: 'violet', label: 'Viola' },
          { id: 'emerald', label: 'Verde' },
          { id: 'ink', label: 'Inchiostro' },
        ]} />
      </Section>

      <button onClick={resetProgress} style={{
        marginTop: 8, width: '100%', padding: '10px',
        background: 'transparent', color: 'var(--ink-3)',
        border: '1px solid var(--hairline-2)', borderRadius: 6,
        fontSize: 12, cursor: 'pointer', fontFamily: 'var(--mono)', letterSpacing: '0.02em',
      }}>Reset progresso</button>
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.06em', marginBottom: 8 }}>{label}</div>
      {children}
    </div>
  );
}

function Radio({ value, onChange, options }) {
  return (
    <div style={{ display: 'flex', gap: 4, background: 'var(--bg-deep)', padding: 3, borderRadius: 6 }}>
      {options.map((o) => (
        <button key={o.id} onClick={() => onChange(o.id)} style={{
          flex: 1, padding: '6px 8px', border: 0,
          background: value === o.id ? 'var(--bg)' : 'transparent',
          color: value === o.id ? 'var(--ink)' : 'var(--ink-3)',
          fontSize: 11, fontWeight: value === o.id ? 600 : 500,
          borderRadius: 4, cursor: 'pointer', fontFamily: 'inherit',
          boxShadow: value === o.id ? '0 1px 2px rgba(0,0,0,0.06)' : 'none',
        }}>{o.label}</button>
      ))}
    </div>
  );
}

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