// Main app — wires together all sections, manages global state.

const { useState, useEffect, useRef } = React;

// Tweakable defaults — host can rewrite this block on disk
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "density": "comfortable",
  "motion": "moderate",
  "accent": "teal",
  "scale": 100
}/*EDITMODE-END*/;

// Estimate reading time from goal text
function estimateReadingTime() {
  const data = window.TUTKE_DATA;
  let words = 0;
  data.goals.forEach(g => {
    words += (g.title + ' ' + g.why + ' ' + g.action).split(/\s+/).length;
  });
  data.themes.forEach(t => {
    words += (t.lede + ' ' + t.tagline + ' ' + t.risk + ' ' + t.solution).split(/\s+/).length;
  });
  return Math.max(14, Math.round(words / 220));
}

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [readerOpen, setReaderOpen] = useState(false);
  const [activeGoal, setActiveGoal] = useState(null);
  const [overNight, setOverNight] = useState(true);

  const readingTime = React.useMemo(estimateReadingTime, []);

  // Apply scale + density via CSS vars on <html>
  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty('font-size', (tweaks.scale || 100) + '%');
    document.body.dataset.density = tweaks.density;
    document.body.dataset.motion = tweaks.motion;
    document.body.dataset.accent = tweaks.accent;

    const accentMap = {
      teal: { teal: '#2d5a5a', bright: '#4a7c7c', glow: '#69a3a3' },
      moss: { teal: '#4a6a3a', bright: '#6a8a5a', glow: '#8aa570' },
      indigo: { teal: '#3a4a7a', bright: '#5a6a9a', glow: '#7a8ac0' },
      rust: { teal: '#a04a2a', bright: '#c06a4a', glow: '#d48a6a' },
    };
    const a = accentMap[tweaks.accent] || accentMap.teal;
    r.setProperty('--teal', a.teal);
    r.setProperty('--teal-bright', a.bright);
    r.setProperty('--teal-glow', a.glow);
  }, [tweaks]);

  // Detect when chrome is over a dark section
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + 30;
      const darkSections = document.querySelectorAll('.hero, .map, .ministry, .foot');
      let inDark = false;
      darkSections.forEach(s => {
        const rect = s.getBoundingClientRect();
        const top = rect.top + window.scrollY;
        const bottom = top + rect.height;
        if (y >= top && y <= bottom) inDark = true;
      });
      setOverNight(inDark);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Hash linking
  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash;
      if (h.startsWith('#suositus-')) {
        const id = h.replace('#suositus-', '');
        setActiveGoal(id);
        setTimeout(() => {
          const el = document.getElementById('suositus-' + id);
          if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
      }
    };
    onHash();
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Esc closes reader
  useEffect(() => {
    if (!readerOpen) return;
    const onKey = (e) => { if (e.key === 'Escape') setReaderOpen(false); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [readerOpen]);

  const handleJump = (anchor) => {
    const el = document.getElementById(anchor);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <React.Fragment>
      <Chrome
        onOpenReader={() => setReaderOpen(true)}
        readingTime={readingTime}
        overNight={overNight}
      />
      <Hero />
      <IntroChapter />
      <ThemeOverview onJump={handleJump} />
      <GoalMap activeGoalId={activeGoal} onActiveGoal={setActiveGoal} />
      <ChapterScroller />
      <MinistryViz />
      <Closing />
      <Footer />

      {readerOpen && <ReaderMode onClose={() => setReaderOpen(false)} />}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Aksenttiväri">
          <TweakRadio
            value={tweaks.accent}
            onChange={v => setTweak('accent', v)}
            options={[
              { value: 'teal',   label: 'Teal' },
              { value: 'moss',   label: 'Sammal' },
              { value: 'indigo', label: 'Indigo' },
              { value: 'rust',   label: 'Ruoste' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Tiheys">
          <TweakRadio
            value={tweaks.density}
            onChange={v => setTweak('density', v)}
            options={[
              { value: 'cozy',         label: 'Cozy' },
              { value: 'comfortable',  label: 'Comfort' },
              { value: 'spacious',     label: 'Avara' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Liike">
          <TweakRadio
            value={tweaks.motion}
            onChange={v => setTweak('motion', v)}
            options={[
              { value: 'subtle',   label: 'Hillitty' },
              { value: 'moderate', label: 'Maltillinen' },
              { value: 'rich',     label: 'Rikas' },
            ]}
          />
        </TweakSection>
        <TweakSection title="Tekstin koko">
          <TweakSlider
            value={tweaks.scale}
            onChange={v => setTweak('scale', v)}
            min={85} max={120} step={5}
            suffix="%"
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
};

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