/* eslint-disable */
// HAIQ — root App: language state, scroll tracking, section composition

const { useState, useEffect, useRef, useCallback } = React;

const SECTION_IDS = ['top','problems','services','how','stats','tech','pricing','about','contact','footer'];
const SECTION_NAMES = ['Hero','Problems','Services','Process','Stats','Tech','Pricing','About','Contact','Footer'];

function App() {
  const initialLang = /^\/en(\/|$)/.test(window.location.pathname) ? 'en' : 'ua';
  const [lang, setLang] = useState(initialLang);
  const [activeIdx, setActiveIdx] = useState(0);
  const [fade, setFade] = useState(false);
  const t = HAIQ_CONTENT[lang];

  // Language fade transition
  const switchLang = useCallback((next) => {
    if (next === lang) return;
    setFade(true);
    setTimeout(() => {
      setLang(next);
      history.replaceState({}, '', '/' + next);
      requestAnimationFrame(() => setFade(false));
    }, 180);
  }, [lang]);

  // Scroll-spy via IntersectionObserver
  useEffect(() => {
    const observers = [];
    const candidates = SECTION_IDS.map(id => document.getElementById(id)).filter(Boolean);
    let visibility = new Map();
    candidates.forEach(el => {
      const io = new IntersectionObserver(entries => {
        entries.forEach(e => {
          visibility.set(e.target.id, e.intersectionRatio);
        });
        // pick most visible
        let best = SECTION_IDS[0], bestV = -1;
        visibility.forEach((v, k) => { if (v > bestV) { bestV = v; best = k; } });
        const idx = SECTION_IDS.indexOf(best);
        if (idx >= 0) setActiveIdx(idx);
      }, { threshold: [0.15, 0.35, 0.55, 0.75] });
      io.observe(el);
      observers.push(io);
    });
    return () => observers.forEach(o => o.disconnect());
  }, []);

  const scrollTo = useCallback((idx) => {
    const id = SECTION_IDS[idx];
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({behavior:'smooth', block:'start'});
  }, []);

  return (
    <div style={{
      position:'relative',
      opacity: fade ? 0.4 : 1,
      transition:'opacity 0.18s ease',
    }}>
      <Particles/>
      <ScrollProgress/>
      <Grain/>

      <Nav lang={lang} setLang={switchLang} t={t} sections={SECTION_NAMES} activeIdx={activeIdx} scrollTo={scrollTo}/>
      <SectionRail sections={SECTION_NAMES} activeIdx={activeIdx} scrollTo={scrollTo}/>

      <main style={{position:'relative', zIndex:2}}>
        <Hero t={t}/>
        <ProblemsSection t={t}/>
        <ServicesSection t={t}/>
        <ProcessSection t={t}/>
        <StatsSection t={t}/>
        <TechSection t={t}/>
        <PricingSection t={t}/>
        <AboutSection t={t}/>
        <CTASection t={t}/>
      </main>

      <Footer t={t} lang={lang} setLang={switchLang} scrollTo={scrollTo}/>
      <Chatbot t={t} lang={lang}/>
      <ContactModal lang={lang}/>
    </div>
  );
}

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