// Soulforce Arts — main app
const { useState: useStateA, useEffect: useEffectA } = React;

function Header({ onCTA, onOpenMenu, scrolled, currentSection }) {
  const links = [
    { id: 'top',    label: 'Home' },
    { id: 'lab',    label: 'Free Lab', href: '/tensionreset' },
    { id: 'pwp', label: 'Perform Without Pain', href: '/pwp' },
    { id: 'book',   label: 'The Book', href: '/book' },
    { id: 'joseph', label: 'About', href: '/about' },
  ];
  return (
    <header className={`header ${scrolled ? 'scrolled' : ''}`}>
      <a className="brand" href="#top" aria-label="Soulforce Arts Institute — Home">
        <img src="assets/logo-gold-wide-light.png" alt="Soulforce Arts Institute" />
      </a>
      <div className="header-right">
        <nav aria-label="Primary">
          {links.map(l => (
            <a key={l.id} href={l.href || `#${l.id}`}
               className={currentSection === l.id ? 'current' : ''}>
              {l.label}
            </a>
          ))}
        </nav>
        <div className="cta-row">
          <button className="btn sm" onClick={() => onCTA('call')}>
            Apply
          </button>
          <button className="menu-toggle" onClick={onOpenMenu} aria-label="Menu">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
              <path d="M3 7h18M3 12h18M3 17h18"/>
            </svg>
          </button>
        </div>
      </div>
    </header>
  );
}

function MobileDrawer({ open, onClose, onCTA }) {
  return (
    <div className={`mob-drawer ${open ? 'open' : ''}`}>
      <a href="#top"    onClick={onClose}>Home</a>
      <a href="/tensionreset"    onClick={onClose}>Free Lab</a>
      <a href="/pwp" onClick={onClose}>Perform Without Pain</a>
      <a href="/book"   onClick={onClose}>The Book</a>
      <a href="/about" onClick={onClose}>About</a>
      <div className="ctas">
        <button className="btn" onClick={() => { onClose(); onCTA('call'); }}>
          Apply to work with me
        </button>
        <button className="btn outline" onClick={() => { onClose(); onCTA('chapter'); }}>
          Read the first chapter free
        </button>
      </div>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero": "fullbleed",
  "ensoIntensity": "subtle",
  "density": "regular"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [modal, setModal] = useStateA(null);
  const [menuOpen, setMenuOpen] = useStateA(false);
  const [scrolled, setScrolled] = useStateA(false);
  const [currentSection, setCurrentSection] = useStateA('top');

  useEffectA(() => {
    document.body.classList.toggle('enso-off', t.ensoIntensity === 'off');
    document.body.classList.toggle('enso-subtle', t.ensoIntensity === 'subtle');
    document.body.classList.toggle('enso-prominent', t.ensoIntensity === 'prominent');
    document.body.classList.remove('density-compact','density-comfy');
    if (t.density === 'compact') document.body.classList.add('density-compact');
    if (t.density === 'comfy')   document.body.classList.add('density-comfy');
  }, [t.ensoIntensity, t.density]);

  useEffectA(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Deep link: /path (or #path) opens the Find Your Path intake modal;
  // /discovery (or #discovery) opens the "Work with me" exploratory-call modal
  useEffectA(() => {
    const path = window.location.pathname.replace(/\/+$/, '').toLowerCase();
    const hash = window.location.hash.toLowerCase();
    if (path.endsWith('/path') || hash === '#path') {
      setModal({ kind: 'intake', source: 'Path link' });
    } else if (path.endsWith('/discovery') || hash === '#discovery') {
      setModal('call');
    }
  }, []);

  // Track which section is in view (for nav underline)
  useEffectA(() => {
    const ids = ['top','lab','studio','book','joseph'];
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) setCurrentSection(e.target.id);
      });
    }, { rootMargin: '-40% 0px -55% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  const openCTA = (kind, source) => {
    if (kind === 'call')         setModal('call');
    else if (kind === 'chapter') setModal('chapter');
    else if (kind === 'studio')  setModal('studio');
    else if (kind === 'intake')  setModal({ kind: 'intake', source: source || 'Section 6.5' });
    else if (kind === 'lab')     setModal('lab');
    else if (kind === 'findpath') { const el = document.getElementById('find-your-path'); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: 'smooth' }); }
    else if (kind === 'work')    { const el = document.getElementById('studio'); if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 60, behavior: 'smooth' }); }
    else if (kind === 'buy')     setModal({ kind: 'generic', title: 'Get the Book', body: 'Soulforce is available wherever books are sold — paperback, hardcover, or audiobook narrated by Joseph.' });
    else if (kind === 'story')   setModal({ kind: 'generic', title: 'About Joseph', body: 'The full story lives on the About page — coming soon in this prototype.' });
  };

  return (
    <>
      <Header onCTA={openCTA} onOpenMenu={() => setMenuOpen(true)} scrolled={scrolled} currentSection={currentSection} />
      <MobileDrawer open={menuOpen} onClose={() => setMenuOpen(false)} onCTA={openCTA} />

      <main id="top" className="page">
        <Hero variant={t.hero} onCTA={openCTA} />
        <LabBanner onCTA={openCTA} />
        <Problem />
        <Reframe />
        <div id="joseph"><Joseph onCTA={openCTA}/></div>
        <Pillars />
        <Plan />
        <FindYourPath onCTA={openCTA} />
        <TensionResetLab onCTA={openCTA} />
        <div id="studio"><Studio onCTA={openCTA}/></div>
        <div id="book"><Book   onCTA={openCTA}/></div>
        <SocialProof />
        <div id="work"><Stakes onCTA={openCTA} /></div>
      </main>

      <Footer />

      {modal === 'chapter' && <FreeChapterModal onClose={() => setModal(null)} />}
      {modal === 'call'    && <ExploratoryCallModal onClose={() => setModal(null)} />}
      {modal === 'studio'  && <StudioTeaserModal onClose={() => setModal(null)} onCallCTA={() => setModal('call')} />}
      {modal && typeof modal === 'object' && modal.kind === 'intake' && (
        <IntakeModal source={modal.source} onClose={() => setModal(null)} onChapter={() => setModal('chapter')} />
      )}
      {modal === 'lab'     && <LabModal onClose={() => setModal(null)} />}
      {modal && typeof modal === 'object' && modal.kind === 'generic' && (
        <GenericModal title={modal.title} body={modal.body} onClose={() => setModal(null)} />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero" />
        <TweakSelect label="Variant" value={t.hero}
          options={[
            { value: 'fullbleed', label: 'Full-bleed sunset' },
            { value: 'inset',     label: 'Green w/ inset portrait' },
            { value: 'split',     label: 'Split: type / photo' },
          ]}
          onChange={(v) => setTweak('hero', v)} />

        <TweakSection label="Enso" />
        <TweakRadio label="Intensity" value={t.ensoIntensity}
          options={['off','subtle','prominent']}
          onChange={(v) => setTweak('ensoIntensity', v)} />

        <TweakSection label="Page rhythm" />
        <TweakRadio label="Whitespace" value={t.density}
          options={['compact','regular','comfy']}
          onChange={(v) => setTweak('density', v)} />
      </TweaksPanel>
    </>
  );
}

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