/* global React, ReactDOM */
const { useState, useEffect, useCallback } = React;
const { Header, Hero } = window.LYTLE_UI;
const { CoreServices, DisplayProducts } = window.LYTLE_SECTIONS;
const { DesignCTA, Story, FinalCTA, Footer, QuoteModal, Tweaks } = window.LYTLE_EXTRA;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "hero": "photo",
  "display": "Oswald",
  "density": "comfortable",
  "red": "#CF1A27"
}/*EDITMODE-END*/;

function App() {
  const [quoteOpen, setQuoteOpen] = useState(false);
  const [active, setActive] = useState('home');
  const [svcReset, setSvcReset] = useState(0);
  const [tweaksOpen, setTweaksOpen] = useState(false);
  const [tweaks, setTweaks] = useState(() => {
    try {
      const saved = localStorage.getItem('lytle_tweaks');
      return saved ? { ...TWEAK_DEFAULTS, ...JSON.parse(saved) } : TWEAK_DEFAULTS;
    } catch { return TWEAK_DEFAULTS; }
  });

  // Apply tweaks
  useEffect(() => {
    document.documentElement.dataset.hero = tweaks.hero;
    document.documentElement.dataset.density = tweaks.density;
    document.documentElement.style.setProperty('--display', `'${tweaks.display}', 'Arial Narrow', sans-serif`);
    document.documentElement.style.setProperty('--red', tweaks.red);
    try { localStorage.setItem('lytle_tweaks', JSON.stringify(tweaks)); } catch {}
    // Persist to host file
    window.parent.postMessage({ type: '__edit_mode_set_keys', edits: tweaks }, '*');
  }, [tweaks]);

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

  // Scroll spy + reveal
  useEffect(() => {
    const sections = ['home', 'services', 'display', 'about', 'contact'];
    const onScroll = () => {
      const y = window.scrollY + 140;
      let curr = 'home';
      for (const id of sections) {
        const el = document.getElementById(id);
        if (el && el.offsetTop <= y) curr = id;
      }
      setActive(curr);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  useEffect(() => {
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting) en.target.classList.add('in');
      });
    }, { threshold: 0.12 });
    document.querySelectorAll('.reveal').forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  const jump = useCallback((id) => {
    if (id === 'team') { window.location.href = 'team-stores.html'; return; }
    if (id === 'catalog') { window.location.href = 'catalog.html'; return; }
    if (id === 'home' || id === 'services') setSvcReset(n => n + 1);
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'smooth' });
  }, []);

  useEffect(() => {
    if (!window.location.hash) return;
    const id = window.location.hash.slice(1);
    history.replaceState(null, '', window.location.pathname);
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: 'auto' });
  }, []);

  const openQuote = useCallback(() => setQuoteOpen(true), []);

  return (
    <>
      <Header active={active} onJump={jump} onQuote={openQuote}/>
      <Hero onJump={jump} onQuote={openQuote}/>
      <CoreServices onJump={jump} onQuote={openQuote} resetKey={svcReset}/>
      <DisplayProducts onQuote={openQuote}/>
      <DesignCTA onQuote={openQuote}/>
      <Story/>
      <FinalCTA onQuote={openQuote}/>
      <Footer onJump={jump} onQuote={openQuote}/>
      <QuoteModal open={quoteOpen} onClose={() => setQuoteOpen(false)}/>
      <Tweaks open={tweaksOpen} onClose={() => setTweaksOpen(false)} state={tweaks} setState={setTweaks}/>
    </>
  );
}

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