// ADOS website — Single-page scroll layout + Tweaks
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroLayout": "Imagen completa",
  "heroImage": "./assets/img/reactor-aerial.webp",
  "heroTitle": "BIM que evita errores antes de llegar a obra",
  "heroOverlay": 58,
  "scrollReveal": true,
  "accent": "#F9B233"
}/*EDITMODE-END*/;

// accent → derived hover/press (keeps the brand's amber discipline; teal is a rare alt)
const ACCENTS = {
  '#F9B233': { hover: '#FBC766', press: '#E7A11E' },
  '#E7A11E': { hover: '#F9B233', press: '#CE8E14' },
  '#2F8A8A': { hover: '#46A6A6', press: '#256E6E' },
};

const HERO_IMAGES = [
  { value: './assets/img/structural-frame.webp', label: 'Estructura metálica' },
  { value: './assets/img/water-plant-wide.webp', label: 'PTAR (planta)' },
  { value: './assets/img/reactor-aerial.webp', label: 'Reactor (aéreo)' },
  { value: './assets/img/building-section.webp', label: 'Corte de edificio' },
  { value: './assets/img/mep-isometric.webp', label: 'Isométrico MEP' },
];

const SECTION_IDS = ['inicio', 'servicios', 'proyectos', 'nosotros', 'contacto'];
const HEADER_OFFSET = 78;

function App() {
  const {
    Header, Footer, HeroSection, FederationBand, ProcessSection, CTASection, ScrollScrubVideo,
    StatsBand, CompareSection, AboutSection, WhatsAppFab,
    ServicesSection, ProjectsSection, ContactSection, ProjectModal,
    useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakSlider, TweakToggle, TweakText, TweakColor,
  } = window;

  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Los proyectos abren en un modal centrado sobre la misma página (no hay
  // página de detalle aparte; ProjectDetailScreen quedó sin uso).
  const [project, setProject] = React.useState(null);
  const [active, setActive] = React.useState('inicio');

  const doScroll = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const top = id === 'inicio' ? 0 : el.getBoundingClientRect().top + window.scrollY - HEADER_OFFSET;
    window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
  };

  const goToSection = (id) => {
    if (!SECTION_IDS.includes(id)) return; // footer may pass non-section ids → ignore
    doScroll(id);
  };

  const openProject = (p) => setProject(p);

  // Scroll-spy — highlight the active nav pill as each section passes.
  React.useEffect(() => {
    let raf = null;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const line = window.scrollY + window.innerHeight * 0.38;
        let cur = 'inicio';
        for (const id of SECTION_IDS) {
          const el = document.getElementById(id);
          if (el && el.getBoundingClientRect().top + window.scrollY <= line) cur = id;
        }
        // snap to last section at the very bottom of the page
        if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 4) cur = 'contacto';
        setActive(cur);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);

  const acc = ACCENTS[t.accent] || ACCENTS['#F9B233'];
  const accentVars = {
    '--accent': t.accent,
    '--accent-hover': acc.hover,
    '--accent-press': acc.press,
    '--focus-on-dark': t.accent,
  };

  return (
    <div style={accentVars}>
      <Header active={active} onNavigate={goToSection} />

      <main style={{ background: 'var(--bg-deep)' }}>
          <ScrollScrubVideo src="./uploads/home-web.mp4">
            <div id="inicio"><HeroSection t={t} onNavigate={goToSection} /></div>
            <FederationBand t={t} />
          </ScrollScrubVideo>
          <StatsBand t={t} />
          <ProcessSection t={t} />
          <CompareSection t={t} />
          <div id="servicios"><ServicesSection onNavigate={goToSection} /></div>
          <div id="proyectos"><ProjectsSection onNavigate={goToSection} onOpenProject={openProject} /></div>
          <div id="nosotros"><AboutSection t={t} /></div>
          <CTASection onNavigate={goToSection} />
          <div id="contacto"><ContactSection onNavigate={goToSection} /></div>
      </main>

      <Footer onNavigate={goToSection} />
      <WhatsAppFab />

      {/* detalle de proyecto: ventana emergente centrada (Escape o clic afuera cierra) */}
      <ProjectModal
        project={project}
        onClose={() => setProject(null)}
        onNavigate={(r) => goToSection(r === 'contact' ? 'contacto' : r)}
      />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Portada principal" />
        <TweakRadio label="Disposición" value={t.heroLayout}
          options={['Imagen completa', 'Dividida']}
          onChange={(v) => setTweak('heroLayout', v)} />
        <TweakSelect label="Imagen" value={t.heroImage} options={HERO_IMAGES}
          onChange={(v) => setTweak('heroImage', v)} />
        <TweakSlider label="Oscurecer" value={t.heroOverlay} min={20} max={90} unit="%"
          onChange={(v) => setTweak('heroOverlay', v)} />
        <TweakText label="Titular" value={t.heroTitle} placeholder="Titular de la portada"
          onChange={(v) => setTweak('heroTitle', v)} />

        <TweakSection label="Movimiento" />
        <TweakToggle label="Aparecer al hacer scroll" value={t.scrollReveal}
          onChange={(v) => setTweak('scrollReveal', v)} />

        <TweakSection label="Marca" />
        <TweakColor label="Acento" value={t.accent}
          options={['#F9B233', '#E7A11E', '#2F8A8A']}
          onChange={(v) => setTweak('accent', v)} />
      </TweaksPanel>
    </div>
  );
}

// Exported to window; index.html performs the single mount after all babel
// scripts have loaded (App.jsx is also pulled into _ds_bundle.js, so it must
// NOT render on its own or it would double-mount).
window.App = App;
