// App — wires everything together
const App = () => {
  const defaults = JSON.parse(document.getElementById('tweak-defaults').textContent.replace(/\/\*EDITMODE-(BEGIN|END)\*\//g, ''));
  const [tweaks, setTweaks] = useState(defaults);
  const [tweaksActive, setTweaksActive] = useState(false);
  const [bookingOpen, setBookingOpen] = useState(false);
  const [bookingPrefill, setBookingPrefill] = useState('single');
  const [showStickyBar, setShowStickyBar] = useState(false);
  const [activeSection, setActiveSection] = useState('');

  const openBooking = (service = 'masazas60') => {
    setBookingPrefill(service);
    setBookingOpen(true);
  };

  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY;
      setShowStickyBar(y > 900 && tweaks.showStickyBookBar && !bookingOpen);
      const sections = ['about','method','process','results','pricing','faq'];
      let current = '';
      for (const id of sections) {
        const el = document.getElementById(id);
        if (el && el.offsetTop - 120 <= y) current = id;
      }
      setActiveSection(current);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [tweaks.showStickyBookBar, bookingOpen]);

  useEffect(() => {
    const listener = (e) => {
      if (e.data?.type === '__activate_edit_mode') setTweaksActive(true);
      if (e.data?.type === '__deactivate_edit_mode') setTweaksActive(false);
    };
    window.addEventListener('message', listener);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', listener);
  }, []);

  return (
    <>
      {tweaks.showPromoBanner && <PromoBanner text={tweaks.promoText} />}
      <Nav onBook={() => openBooking()} activeSection={activeSection} ctaLabel={tweaks.ctaLabel} />
      <Hero variant={tweaks.heroVariant} onBook={() => openBooking()} />
      <StatBand />
      <About />
      <Problem />
      <Method />
      <Process />
      <Testimonials />
      <BeforeAfter />
      <Pricing onBook={() => openBooking('osteo')} />
      <FAQ />
      <BookingCta onBook={openBooking} />
      <Footer />
      <StickyBar show={showStickyBar} onBook={() => openBooking()} />
      <Booking open={bookingOpen} onClose={() => setBookingOpen(false)} prefill={bookingPrefill} />
      <TweaksPanel active={tweaksActive} tweaks={tweaks} setTweaks={setTweaks} />
      <a className="whatsapp-float"
         href="https://wa.me/37067253955?text=Labas%2C%20nor%C4%97čiau%20u%C5%BEsisakyti%20seansą"
         target="_blank" rel="noopener noreferrer"
         aria-label="Rašyti per WhatsApp">
        <Icon name="whatsapp" size={26} />
      </a>
    </>
  );
};

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