const Shell = ({ children }) => {
  const [route, setRoute] = React.useState(window.location.hash.replace('#', '') || '/');
  const [scrolled, setScrolled] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [editMode, setEditMode] = React.useState(false);
  const [textEdit, setTextEdit] = React.useState(false);

  // Tweak defaults — host can rewrite this block on disk when user saves values
  const TWEAKS = /*EDITMODE-BEGIN*/{
    "textEditOn": false,
    "accentHue": "rose"
  }/*EDITMODE-END*/;

  // Edit-mode protocol: register listener FIRST, then announce availability.
  React.useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === '__activate_edit_mode') setEditMode(true);
      if (d.type === '__deactivate_edit_mode') { setEditMode(false); setTextEdit(false); }
    };
    window.addEventListener('message', onMsg);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    setTextEdit(!!TWEAKS.textEditOn);
    return () => window.removeEventListener('message', onMsg);
  }, []);

  // When text-edit is on, make textual elements contentEditable.
  React.useEffect(() => {
    const selector = 'h1,h2,h3,h4,p,blockquote,cite,summary,label,.eyebrow,.mono,.script,.btn,a,li,span.editable';
    const apply = () => {
      document.querySelectorAll(selector).forEach(el => {
        if (el.closest('.tweaks-panel')) return;
        if (textEdit && editMode) {
          if (!el.dataset.prevEditable) el.dataset.prevEditable = el.getAttribute('contenteditable') || '';
          el.setAttribute('contenteditable', 'true');
          el.classList.add('mlc-editable');
        } else {
          if (el.dataset.prevEditable === '') el.removeAttribute('contenteditable');
          else if (el.dataset.prevEditable) el.setAttribute('contenteditable', el.dataset.prevEditable);
          delete el.dataset.prevEditable;
          el.classList.remove('mlc-editable');
        }
      });
    };
    apply();
    // Re-apply on route change (new DOM) via a short interval while active
    const id = setInterval(apply, 800);
    return () => clearInterval(id);
  }, [textEdit, editMode, route]);

  const toggleTextEdit = () => {
    const v = !textEdit;
    setTextEdit(v);
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { textEditOn: v } }, '*');
  };

  React.useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.replace('#', '') || '/');
      setMobileOpen(false);
      window.scrollTo({top: 0, behavior: 'instant'});
    };
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('hashchange', onHash);
    window.addEventListener('scroll', onScroll);
    onScroll();
    return () => { window.removeEventListener('hashchange', onHash); window.removeEventListener('scroll', onScroll); };
  }, []);

  // Reveal on scroll — flag body so CSS only hides .reveal once JS is ready,
  // then observe. Fallback: force-show everything after 800ms in case observer stalls.
  React.useEffect(() => {
    document.body.classList.add('js-ready');
    const obs = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.05, rootMargin: '0px 0px -40px 0px' });
    const els = document.querySelectorAll('.reveal:not(.in)');
    els.forEach(el => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight && r.bottom > 0) el.classList.add('in');
      else obs.observe(el);
    });
    const fallback = setTimeout(() => {
      document.querySelectorAll('.reveal:not(.in)').forEach(el => el.classList.add('in'));
    }, 1200);
    return () => { obs.disconnect(); clearTimeout(fallback); };
  }, [route]);

  const nav = [
    ['/', 'Home'],
    ['/about', 'About'],
    // Hidden pre-launch — pages not ready yet. Restore when content is finalized.
    // ['/services', 'Services'],
    // ['/mini-sessions', 'Mini Sessions'],
    // ['/investment', 'Investment'],
    ['/faq', 'FAQ'],
    ['/contact', 'Contact'],
  ];

  const page = (() => {
    switch (route) {
      case '/about': return <window.About />;
      case '/services': return <window.Services />;
      case '/mini-sessions': return <window.MiniSessions />;
      case '/investment': return <window.Investment />;
      case '/faq': return <window.FAQ />;
      case '/contact': return <window.Contact />;
      case '/privacy': return <window.Privacy />;
      case '/terms': return <window.Terms />;
      default: return <window.Home />;
    }
  })();

  // Update title per page for SEO feel
  React.useEffect(() => {
    const titles = {
      '/': 'Motherhood Lens Co. · Family Photographer Fort Mill SC',
      '/about': 'Meet Abby · Motherhood Lens Co.',
      '/services': 'Newborn, Motherhood & Family Sessions · Fort Mill SC',
      '/mini-sessions': 'Seasonal Mini Sessions · Motherhood Lens Co.',
      '/investment': 'Investment & Pricing · Motherhood Lens Co.',
      '/faq': 'FAQ · Motherhood Lens Co.',
      '/contact': "Let's Work Together · Motherhood Lens Co.",
      '/privacy': 'Privacy Policy · Motherhood Lens Co.',
      '/terms': 'Terms of Service · Motherhood Lens Co.',
    };
    document.title = titles[route] || titles['/'];
  }, [route]);

  return (
    <div>
      <header className={`nav ${(scrolled || mobileOpen) ? 'scrolled' : ''}`}>
        <a href="#/" className="nav-logo-wrap" aria-label="Motherhood Lens Co." onClick={() => setMobileOpen(false)}>
          <img src="assets/mlc_logo.png" alt="Motherhood Lens Co." className="nav-logo-mark"/>
        </a>
        <nav className={`nav-links ${mobileOpen ? 'mobile-open' : ''}`}>
          {nav.map(([h, l]) => (
            <a key={h} href={`#${h}`} className={route === h ? 'active' : ''} onClick={() => setMobileOpen(false)}>{l}</a>
          ))}
          {/* Phone hidden pre-launch — restore when number is finalized.
          <a href="tel:8035550127" className="nav-phone">(803) 555-0127</a>
          */}
          <a href="#/contact" className="nav-cta" onClick={() => setMobileOpen(false)}>Inquire</a>
        </nav>
        <button className="nav-toggle" onClick={() => setMobileOpen(!mobileOpen)} aria-label={mobileOpen ? 'Close menu' : 'Open menu'} aria-expanded={mobileOpen}>
          {mobileOpen
            ? <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M5 5l14 14M19 5L5 19"/></svg>
            : <svg width="24" height="24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
          }
        </button>
      </header>

      <main>{page}</main>

      {editMode && (
        <div className="tweaks-panel" role="dialog" aria-label="Tweaks">
          <div className="tweaks-head">
            <span className="tweaks-title">Tweaks</span>
            <span className="tweaks-sub">Motherhood Lens Co.</span>
          </div>
          <div className="tweaks-body">
            <label className="tweaks-row">
              <div>
                <div className="tweaks-row-t">Text editor</div>
                <div className="tweaks-row-d">Click any heading or paragraph to edit in place.</div>
              </div>
              <button className={`tweaks-switch ${textEdit ? 'on' : ''}`} onClick={toggleTextEdit} aria-pressed={textEdit}>
                <span/>
              </button>
            </label>
            {textEdit && (
              <div className="tweaks-note">
                Text editor is <strong>on</strong>. Click any text on the page to edit it. Changes live for this session.
              </div>
            )}
          </div>
        </div>
      )}

      <footer className="footer">
        <div className="container">
          <div className="footer-grid">
            <div>
              <h3>Motherhood <span className="script" style={{color: 'var(--rose)', fontSize: 'clamp(28px, 4vw, 44px)', verticalAlign: -2}}>&amp;</span> Lens Co.</h3>
              <p style={{marginTop: 20, color: 'rgba(250,246,241,.7)', maxWidth: 380}}>
                Heirloom photography for the mothers of Fort Mill, Indian Land &amp; Rock Hill.
              </p>
              <form
                onSubmit={async e => {
                  e.preventDefault();
                  const formEl = e.currentTarget;
                  const email = new FormData(formEl).get('email');
                  try {
                    const res = await fetch('https://formsubmit.co/ajax/motherhoodlensco@gmail.com', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
                      body: JSON.stringify({
                        _subject: 'New VIP list signup — Motherhood Lens Co. (footer)',
                        _replyto: email,
                        Email: email,
                        Source: 'Footer VIP signup',
                      }),
                    });
                    if (!res.ok) throw new Error();
                    formEl.reset();
                    alert("You're on the list! 💌");
                  } catch {
                    alert("Sorry, that didn't go through. Please try again or email motherhoodlensco@gmail.com.");
                  }
                }}
                style={{marginTop: 28, display: 'flex', gap: 10, flexWrap: 'wrap'}}
              >
                <input required name="email" type="email" placeholder="Join the VIP list" style={{background: 'transparent', border: '1px solid rgba(255,255,255,.2)', borderRadius: 999, padding: '12px 20px', color: 'var(--cream)', fontSize: 16, flex: '1 1 200px', fontFamily: 'Inter'}} />
                <button className="btn btn-rose" style={{padding: '12px 22px', fontSize: 11}}>Subscribe</button>
              </form>
            </div>
            <div>
              <div className="mono" style={{color: 'var(--gold-soft)', marginBottom: 18}}>Quick Links</div>
              <div className="footer-links">
                {nav.map(([h, l]) => <a key={h} href={`#${h}`}>{l}</a>)}
              </div>
            </div>
            <div>
              <div className="mono" style={{color: 'var(--gold-soft)', marginBottom: 18}}>Connect</div>
              <div className="footer-links">
                <a href="mailto:motherhoodlensco@gmail.com">motherhoodlensco@gmail.com</a>
                {/* Phone hidden pre-launch.
                <a href="tel:8035550127">(803) 555-0127</a>
                */}
              </div>
            </div>
          </div>
          <div className="footer-bottom">
            <span>© 2026 Motherhood Lens Co.</span>
            <span style={{display: 'flex', gap: 24, flexWrap: 'wrap', justifyContent: 'center'}}>
              <a href="#/privacy">Privacy Policy</a>
              <a href="#/terms">Terms of Service</a>
              <span>Based in Fort Mill, SC</span>
            </span>
            <span className="script" style={{fontSize: 20, color: 'var(--gold-soft)', letterSpacing: 0, textTransform: 'none'}}>made with love</span>
          </div>
        </div>
      </footer>
    </div>
  );
};

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