// app.jsx — main App: language state, tweaks, sticky observation, palette CSS vars.

const { useState, useEffect, useRef } = React;

const PALETTES = {
  warm: {
    '--bg': '#FFFFFF', '--bg-alt': '#F7FAF7', '--bg-deep': '#EDF5EF',
    '--ink': '#142219', '--ink-soft': '#506055', '--ink-faint': '#8D998F', '--rule': '#E2E8E3',
  },
  cool: {}, minimal: {},
};

// "Jungle after rain" accents — wet, lush greens.
const ACCENTS = {
  jungle: { '--accent': '#1C7A45', '--accent-deep': '#125E33', '--accent-ink': '#F4FBF3' },
  palm:   { '--accent': '#2E9E5B', '--accent-deep': '#1C7A45', '--accent-ink': '#F4FBF3' },
  forest: { '--accent': '#155E37', '--accent-deep': '#0E4527', '--accent-ink': '#F1F8EF' },
  none:   { '--accent': 'var(--ink)', '--accent-deep': 'var(--ink)', '--accent-ink': 'var(--bg)' },
};

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  palette: 'warm',
  accent: 'jungle',
  cardStyle: 'border',
  notes: true,
}/*EDITMODE-END*/;

function applyPalette(name) {
  const p = PALETTES[name] || PALETTES.warm;
  const root = document.documentElement;
  Object.entries(p).forEach(([k, v]) => root.style.setProperty(k, v));
}

function applyAccent(name) {
  const a = ACCENTS[name] || ACCENTS.jungle;
  const root = document.documentElement;
  Object.entries(a).forEach(([k, v]) => root.style.setProperty(k, v));
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useState(() => {
    try {
      const stored = localStorage.getItem('bag_lang');
      return CONTENT[stored] ? stored : 'en';
    } catch { return 'en'; }
  });
  const [modalOpen, setModalOpen] = useState(false);
  const [stickyVisible, setStickyVisible] = useState(false);
  const [route, setRoute] = useState(() => (typeof location !== 'undefined' && location.hash === '#partners') ? 'partners' : 'home');

  // Hash-based routing between the landing and the partner program
  useEffect(() => {
    const onHash = () => {
      const isPartner = location.hash === '#partners';
      setRoute(isPartner ? 'partners' : 'home');
      if (isPartner) {
        window.scrollTo(0, 0);
      } else if (location.hash && location.hash.length > 1) {
        // returning to landing with a section anchor — scroll to it after render
        const id = location.hash.slice(1);
        requestAnimationFrame(() => {
          const el = document.getElementById(id);
          if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 70, behavior: 'auto' });
        });
      }
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  // Apply palette to :root
  useEffect(() => {
    applyPalette(t.palette);
  }, [t.palette]);

  // Apply accent to :root
  useEffect(() => {
    applyAccent(t.accent);
  }, [t.accent]);

  // Toggle handwritten notes
  useEffect(() => {
    document.documentElement.dataset.notes = t.notes ? 'on' : 'off';
  }, [t.notes]);

  // Persist language
  useEffect(() => {
    try { localStorage.setItem('bag_lang', lang); } catch {}
    document.documentElement.lang = lang;
  }, [lang]);

  // Sticky CTA visibility (after hero)
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY || window.pageYOffset;
      setStickyVisible(y > window.innerHeight * 0.7);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const c = CONTENT[lang];
  const onPreOrder = () => setModalOpen(true);

  return (
    <>
      <PaperGrain />
      <RoughDefs />
      <Header t={c} lang={lang} setLang={setLang} onPreOrder={onPreOrder} route={route} />
      <main>
        {route === 'partners' ?
          <PartnerPage t={c} /> :
          <>
            <Hero t={c} onPreOrder={onPreOrder} />
            <MoreThan t={c} cardVariant={t.cardStyle} />
            <Marquee items={c.marquee} speed={48} />
            <Inside t={c} cardVariant={t.cardStyle} />
            <RouteCollage t={c} />
            <Stops t={c} lang={lang} cardVariant={t.cardStyle} />
            <NotFor t={c} />
            <Trust t={c} />
            <Price t={c} cardVariant={t.cardStyle} onPreOrder={onPreOrder} />
            <Faq t={c} />
            <PartnerBanner t={c} onGo={() => { location.hash = '#partners'; }} />
          </>
        }
      </main>
      <Footer t={c} />

      <StickyCta t={c} visible={route === 'home' && stickyVisible && !modalOpen} onPreOrder={onPreOrder} />
      <PreOrderModal t={c} lang={lang} open={modalOpen} onClose={() => setModalOpen(false)} />

      {/* Visual controls are retained for the design editor, but production uses the fixed white route-guide system. */}
      {false && <TweaksPanel title="Tweaks">
        <TweakSection label="Palette" />
        <TweakRadio
          label="Tone"
          value={t.palette}
          options={['warm', 'cool', 'minimal']}
          onChange={(v) => setTweak('palette', v)}
        />

        <TweakSection label="Accent — jungle green" />
        <TweakColor
          label="Accent"
          value={t.accent === 'jungle' ? '#1C7A45' : t.accent === 'palm' ? '#2E9E5B' : t.accent === 'forest' ? '#155E37' : '#1C1916'}
          options={['#1C7A45', '#2E9E5B', '#155E37', '#1C1916']}
          onChange={(v) => {
            const map = { '#1C7A45': 'jungle', '#2E9E5B': 'palm', '#155E37': 'forest', '#1C1916': 'none' };
            setTweak('accent', map[v] || 'jungle');
          }}
        />

        <TweakSection label="Card style" />
        <TweakRadio
          label="Surface"
          value={t.cardStyle}
          options={['border', 'filled', 'none']}
          onChange={(v) => setTweak('cardStyle', v)}
        />
      </TweaksPanel>}
    </>
  );
}

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