/* app.jsx — Main application assembly for template1 */

const SECTION_COMPONENTS = {
  hero: HeroSection,
  trust_logos: TrustLogosSection,
  problem: ProblemSection,
  features: FeaturesSection,
  process: ProcessSection,
  case_studies: CaseStudiesSection,
  trust_testimonials: TrustTestimonialsSection,
  faq: FaqSection,
  cta: CtaSection,
  lead_form: LeadFormSection,
};

const App = () => {
  const [schemaVisible, setSchemaVisible] = React.useState(false);
  const [currentSection, setCurrentSection] = React.useState("hero");

  const schemaSections = (window.LP_SCHEMA && window.LP_SCHEMA.sections) || [];

  React.useEffect(() => {
    document.body.classList.toggle("schema-on", schemaVisible);
  }, [schemaVisible]);

  React.useEffect(() => {
    const nodes = document.querySelectorAll("[data-editor-section-id]");
    if (!nodes.length) return undefined;

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort((a, b) => b.intersectionRatio - a.intersectionRatio);
        if (visible[0]) {
          setCurrentSection(visible[0].target.getAttribute("data-editor-section-id"));
        }
      },
      { rootMargin: "-35% 0px -55% 0px", threshold: [0, 0.15, 0.4] }
    );

    nodes.forEach((n) => observer.observe(n));
    return () => observer.disconnect();
  }, [schemaSections.length]);

  const SP = window.SchemaPanel || null;
  const LT = window.LPTweaks || null;

  return (
    <React.Fragment>
      <Nav showNav={true} />
      <main id="main-content">
        {schemaSections.map(({ sectionId }) => {
          const Component = SECTION_COMPONENTS[sectionId];
          return Component ? <Component key={sectionId} /> : null;
        })}
      </main>
      <Footer />

      <button
        type="button"
        className={"fab-schema" + (schemaVisible ? " fab-schema--active" : "")}
        onClick={() => setSchemaVisible((v) => !v)}
        aria-pressed={schemaVisible}
        aria-label="Toggle schema overlay"
      >
        {schemaVisible ? "HIDE SCHEMA" : "SHOW SCHEMA"}
      </button>

      {SP && <SP visible={schemaVisible} currentSection={currentSection} />}
      {LT && (
        <LT
          currentSection={currentSection}
          schemaVisible={schemaVisible}
          onToggleSchema={() => setSchemaVisible((v) => !v)}
        />
      )}
    </React.Fragment>
  );
};

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