/* global React, ReactDOM, MLN, NavBar, Hero, AboutSection, PoemSection, LecturesSection, StoreSection, GallerySection, TestimonialsSection, FaqSection, ContactSection, Footer, InquiryModal, AdminPanel, AccessibilityBar */
const { useState: useStateSite, useEffect: useEffectSite } = React;

function Site() {
  const [data, setData] = useStateSite(() => MLN.load());
  const [scrolled, setScrolled] = useStateSite(false);
  const [inquiry, setInquiry] = useStateSite(null);
  const [adminOpen, setAdminOpen] = useStateSite(false);

  // On mount: load from cloud and override local cache
  useEffectSite(() => {
    if (!window.MLN_CONFIG) return;
    window.MLN_CONFIG.load().then(cloudData => {
      if (!cloudData) return;
      setData(prev => {
        const merged = { ...prev, ...cloudData };
        MLN.save(merged);
        return merged;
      });
    });
  }, []);

  // Persist every change to localStorage; save to cloud when admin is active
  useEffectSite(() => {
    MLN.save(data);
    if (window.MLN_CONFIG && sessionStorage.getItem('mln_admin') === '1') {
      window.MLN_CONFIG.save(data);
    }
  }, [data]);

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

  const onNav = (id) => {
    if (id === 'top') { window.scrollTo({ top: 0, behavior: 'smooth' }); return; }
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  };

  // Only stores the inquiry in the local admin inbox.
  // Supabase + EmailJS sending is handled by each component (InquiryModal / ContactSection)
  // to avoid double-sends.
  const addInquiry = (rec) => {
    setData(d => ({ ...d, inbox: [rec, ...d.inbox] }));
  };

  return (
    <React.Fragment>
      <NavBar scrolled={scrolled} onNav={onNav} onAdmin={() => setAdminOpen(true)} />
      <main>
        <Hero onNav={onNav} />
        <AboutSection about={data.about} />
        <PoemSection poem={data.poem} />
        <LecturesSection onInquiry={setInquiry} />
        <StoreSection products={data.products} onInquiry={setInquiry} />
        <GallerySection gallery={data.gallery} />
        <TestimonialsSection testimonials={data.testimonials} />
        <FaqSection faq={data.faq} />
        <ContactSection onSubmit={addInquiry} />
        <Footer onNav={onNav} />
      </main>

      <InquiryModal data={inquiry} onClose={() => setInquiry(null)} onSubmit={addInquiry} />
      <AdminPanel open={adminOpen} onClose={() => setAdminOpen(false)} data={data} onChange={setData} />
      {typeof AccessibilityBar !== 'undefined' && <AccessibilityBar />}
    </React.Fragment>
  );
}

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