// Main App composition with multi-page routing
const { useState: aS, useEffect: aE, useCallback: aC } = React;

const App = () => {
  const [bookingOpen, setBookingOpen] = aS(false);
  const [secondOpen, setSecondOpen] = aS(false);
  const [searchOpen, setSearchOpen] = aS(false);
  const [activeSection, setActiveSection] = aS('home');

  // Determine current page from root element's data-page attribute
  const root = document.getElementById('root');
  const page = (root && root.dataset.page) || 'home';

  // Get URL params (for doctor.html?id=..., direction.html?id=...)
  const urlParams = new URLSearchParams(window.location.search);
  const paramId = urlParams.get('id');

  // Scroll-spy (only on home)
  aE(() => {
    if (page !== 'home') return;
    const sections = DATA.nav
      .map(n => document.getElementById(n.id))
      .filter(Boolean);
    if (!sections.length) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter(e => e.isIntersecting)
          .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
        if (visible[0]) setActiveSection(visible[0].target.id);
      },
      { rootMargin: '-50% 0px -45% 0px', threshold: [0, 0.25, 0.5, 0.75, 1] }
    );
    sections.forEach(s => observer.observe(s));
    return () => observer.disconnect();
  }, [page]);

  const openBooking = aC(() => setBookingOpen(true), []);
  const openSecond = aC(() => setSecondOpen(true), []);
  const openSearch = aC(() => setSearchOpen(true), []);

  // Page content
  let content;
  if (page === 'doctors') {
    content = <DoctorsCatalogPage onBook={openBooking} />;
  } else if (page === 'doctor') {
    content = <DoctorDetailPage doctorId={paramId} onBook={openBooking} />;
  } else if (page === 'directions') {
    content = <DirectionsCatalogPage onBook={openBooking} />;
  } else if (page === 'direction') {
    content = <DirectionDetailPage directionId={paramId} onBook={openBooking} />;
  } else if (page === 'contacts') {
    content = <ContactsPage onBook={openBooking} />;
  } else if (page === 'second-opinion') {
    content = <SecondOpinionPage onBook={openBooking} onSecondOpinion={openSecond} />;
  } else if (page === 'news') {
    content = <NewsListPage onBook={openBooking} />;
  } else if (page === 'article') {
    content = <ArticlePage articleId={paramId} onBook={openBooking} />;
  } else {
    // Home page (default)
    content = (
      <>
        <Hero onBook={openBooking} onSecondOpinion={openSecond} />
        <QuickSearch />
        <Directions onBook={openBooking} />
        <Doctors onBook={openBooking} />
        <WhatWeDo />
        <Stats />
        <PatientPath />
        <SecondOpinion onSecondOpinion={openSecond} />
        <Stories />
        <FinalCta onBook={openBooking} onSecondOpinion={openSecond} />
      </>
    );
  }

  return (
    <div className="page" data-page={page}>
      <Header
        activeSection={activeSection}
        currentPage={page}
        onBook={openBooking}
        onSecondOpinion={openSecond}
        onSearch={openSearch}
      />

      <main>{content}</main>

      <Footer />
      <FloatingActions />

      <BookingModal open={bookingOpen} onClose={() => setBookingOpen(false)} />
      <SecondOpinionModal open={secondOpen} onClose={() => setSecondOpen(false)} />
      <SearchModal open={searchOpen} onClose={() => setSearchOpen(false)} />
    </div>
  );
};

// Ждём загрузку врачей (API → localStorage → defaults), затем рендерим
const __root = ReactDOM.createRoot(document.getElementById('root'));
const __render = () => __root.render(<App />);
if (window.__doctorsReady && typeof window.__doctorsReady.then === 'function') {
  window.__doctorsReady.then(__render).catch(__render);
} else {
  __render();
}
