/* MOB.tv — landing page shell (Nav, MenuSheet, Footer, Tweaks, hooks) */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ─── Smooth scroll with sticky-nav offset ─────────────────────── */
function smoothScrollTo(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 24;
  window.scrollTo({ top, behavior: 'smooth' });
}
window.smoothScrollTo = smoothScrollTo;

/* ─── Ripple effect on button press ─────────────────────────────── */
function rippleAt(el, x, y) {
  const rect = el.getBoundingClientRect();
  const size = Math.max(rect.width, rect.height) * 1.2;
  const ripple = document.createElement('span');
  ripple.className = 'ripple';
  ripple.style.width = ripple.style.height = `${size}px`;
  ripple.style.left = `${x - rect.left - size / 2}px`;
  ripple.style.top = `${y - rect.top - size / 2}px`;
  el.appendChild(ripple);
  setTimeout(() => ripple.remove(), 700);
}
function useRipple() {
  return useCallback((e) => {
    const el = e.currentTarget;
    const x = e.clientX ?? (e.touches?.[0]?.clientX ?? el.getBoundingClientRect().left + el.offsetWidth / 2);
    const y = e.clientY ?? (e.touches?.[0]?.clientY ?? el.getBoundingClientRect().top + el.offsetHeight / 2);
    rippleAt(el, x, y);
  }, []);
}

/* ─── Reveal-on-scroll ─────────────────────────────────────────── */
function useReveal() {
  useEffect(() => {
    const observed = new WeakSet();
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.1, rootMargin: '0px 0px -6% 0px' }
    );
    const observe = () => {
      document.querySelectorAll('.reveal').forEach((el) => {
        if (!observed.has(el)) {
          observed.add(el);
          io.observe(el);
        }
      });
    };
    observe();
    // Also re-scan after any DOM updates (sections mount asynchronously)
    const mo = new MutationObserver(observe);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => {
      io.disconnect();
      mo.disconnect();
    };
  }, []);
}

/* ─── Scroll state ─────────────────────────────────────────────── */
function useScrollState() {
  const [progress, setProgress] = useState(0);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const max = document.documentElement.scrollHeight - window.innerHeight;
        const p = max > 0 ? Math.min(1, window.scrollY / max) : 0;
        setProgress(p);
        setScrolled(window.scrollY > 32);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      cancelAnimationFrame(raf);
    };
  }, []);
  return { progress, scrolled };
}

/* ─── Scroll-spy active section ────────────────────────────────── */
function useActiveSection(ids) {
  const [active, setActive] = useState(ids[0]);
  useEffect(() => {
    const observers = [];
    ids.forEach((id) => {
      const el = document.getElementById(id);
      if (!el) return;
      const io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) setActive(id);
          });
        },
        { rootMargin: '-40% 0px -55% 0px' }
      );
      io.observe(el);
      observers.push(io);
    });
    return () => observers.forEach((o) => o.disconnect());
  }, [ids.join('|')]);
  return active;
}

/* ─── Nav ──────────────────────────────────────────────────────── */
const NAV_ITEMS = [
  { id: 'beneficios', label: 'Benefícios' },
  { id: 'catalogo', label: 'Catálogo' },
  { id: 'dispositivos', label: 'Dispositivos' },
  { id: 'planos', label: 'Planos' },
];

function Nav({ scrolled, onOpenMenu, menuOpen, active }) {
  const trackRef = useRef(null);
  const linkRefs = useRef({});
  const [ind, setInd] = useState({ left: 0, width: 0, visible: false });

  useEffect(() => {
    const el = linkRefs.current[active];
    if (!el || !trackRef.current) {
      setInd((s) => ({ ...s, visible: false }));
      return;
    }
    const trackRect = trackRef.current.getBoundingClientRect();
    const r = el.getBoundingClientRect();
    setInd({
      left: r.left - trackRect.left,
      width: r.width,
      visible: true,
    });
  }, [active]);

  const ripple = useRipple();

  return (
    <nav className={`nav${scrolled ? ' scrolled' : ''}`}>
      <div className="nav-inner">
        <a
          className="nav-brand"
          href="#top"
          onClick={(e) => {
            e.preventDefault();
            window.tracker?.trackClick('header_brand');
            window.scrollTo({ top: 0, behavior: 'smooth' });
          }}
        >
          MOB<span className="dot">.</span>TV
        </a>

        <div className="nav-track" ref={trackRef}>
          <span
            className="nav-indicator"
            style={{
              left: ind.left,
              width: ind.width,
              opacity: ind.visible ? 1 : 0,
            }}
            aria-hidden="true"
          />
          {NAV_ITEMS.map((it) => (
            <a
              key={it.id}
              href={`#${it.id}`}
              ref={(n) => (linkRefs.current[it.id] = n)}
              className={active === it.id ? 'active' : ''}
              onClick={(e) => {
                e.preventDefault();
                window.tracker?.trackClick('header_nav_' + it.id);
                smoothScrollTo(it.id);
              }}
            >
              {it.label}
            </a>
          ))}
        </div>

        <a
          href="#cta"
          className="nav-cta"
          onClick={(e) => {
            ripple(e);
            e.preventDefault();
            window.tracker?.trackClick('header_cta');
            smoothScrollTo('cta');
          }}
        >
          Quero testar
        </a>

        <button
          className="nav-menu-btn"
          aria-label="Abrir menu"
          data-open={menuOpen ? 'true' : 'false'}
          onClick={(e) => {
            if (!menuOpen) window.tracker?.trackClick('header_menu_open');
            onOpenMenu();
          }}
        >
          <span></span>
          <span></span>
        </button>
      </div>
    </nav>
  );
}

function MenuSheet({ open, onClose }) {
  useEffect(() => {
    document.body.classList.toggle('menu-open', open);
    return () => document.body.classList.remove('menu-open');
  }, [open]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  return (
    <div className={`menu-sheet${open ? ' open' : ''}`} aria-hidden={!open}>
      <ol>
        {NAV_ITEMS.map((it, i) => (
          <li key={it.id}>
            <a
              href={`#${it.id}`}
              onClick={(e) => {
                e.preventDefault();
                window.tracker?.trackClick('menu_sheet_nav_' + it.id);
                onClose();
                setTimeout(() => smoothScrollTo(it.id), 320);
              }}
            >
              <span>{it.label}</span>
              <span className="idx">0{i + 1}</span>
            </a>
          </li>
        ))}
      </ol>
      <div className="menu-sheet-cta">
        <a
          href="#cta"
          className="cta-cinematic"
          style={{ width: '100%', justifyContent: 'center', animation: 'none', opacity: 1, transform: 'none' }}
          onClick={(e) => {
            e.preventDefault();
            window.tracker?.trackClick('menu_sheet_cta');
            onClose();
            setTimeout(() => smoothScrollTo('cta'), 320);
          }}
        >
          <span className="label">Quero Realizar Meu Teste</span>
        </a>
      </div>
      <div className="menu-sheet-foot">
        <span>MOB.TV</span>
        <span>2026</span>
      </div>
    </div>
  );
}

/* ─── Footer ──────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer className="footer shell" data-screen-label="10 Footer">
      <div className="footer-grid">
        <div className="footer-brand-wrap">
          <div className="footer-brand">MOB<span className="dot">.</span>TV</div>
          <p className="footer-tag">Mob.tv — dê o play no que importa.</p>
        </div>
        <div className="footer-col">
          <h4>Navegar</h4>
          <ul>
            <li><a href="#top" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_nav_top'); window.scrollTo({ top: 0, behavior: 'smooth' }); }}>Início</a></li>
            <li><a href="#beneficios" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_nav_benefits'); smoothScrollTo('beneficios'); }}>Benefícios</a></li>
            <li><a href="#catalogo" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_nav_catalog'); smoothScrollTo('catalogo'); }}>Catálogo</a></li>
            <li><a href="#dispositivos" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_nav_devices'); smoothScrollTo('dispositivos'); }}>Dispositivos</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Suporte</h4>
          <ul>
            <li><a href="https://api.whatsapp.com/send?phone=5521959063337&text=Olá! Gostaria de tirar algumas dúvidas." target="_blank" rel="noopener noreferrer" onClick={() => window.tracker?.trackClick('footer_faq')}>FAQ</a></li>
            <li><a href="https://api.whatsapp.com/send?phone=5521959063337&text=Olá! Gostaria de entrar em contato com o suporte." target="_blank" rel="noopener noreferrer" onClick={() => window.tracker?.trackClick('footer_contact')}>Contato</a></li>
            <li><a href="https://api.whatsapp.com/send?phone=5521959063337&text=Olá! Quero falar com um atendente." target="_blank" rel="noopener noreferrer" onClick={() => window.tracker?.trackClick('footer_whatsapp')}>WhatsApp</a></li>
            <li><a href="https://api.whatsapp.com/send?phone=5521959063337&text=Olá! Gostaria de verificar o status do meu acesso." target="_blank" rel="noopener noreferrer" onClick={() => window.tracker?.trackClick('footer_status')}>Status</a></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Legal</h4>
          <ul>
            <li><a href="#" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_legal_terms'); }}>Termos</a></li>
            <li><a href="#" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_legal_privacy'); }}>Privacidade</a></li>
            <li><a href="#" onClick={(e) => { e.preventDefault(); window.tracker?.trackClick('footer_legal_cookies'); }}>Cookies</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 MOB TV — Todos os direitos reservados</span>
        <a 
          href="./adm/" 
          style={{ 
            color: 'rgba(255, 255, 255, 0.15)', 
            textDecoration: 'none', 
            fontSize: '11px', 
            fontWeight: '600', 
            letterSpacing: '0.08em',
            transition: 'color 0.2s ease-in-out'
          }} 
          onMouseEnter={(e) => e.target.style.color = 'var(--accent)'}
          onMouseLeave={(e) => e.target.style.color = 'rgba(255, 255, 255, 0.15)'}
          onClick={() => window.tracker?.trackClick('footer_adm_link')}
        >
          ADM
        </a>
        <span>São Paulo · Brasil</span>
      </div>
    </footer>
  );
}

/* ─── Mobile floating dock CTA ────────────────────────────────── */
function MobileDock({ visible, trialHours }) {
  return (
    <div className={`mobile-dock${visible ? ' visible' : ''}`} aria-hidden={!visible}>
      <div className="dock-inner">
        <div className="dock-label">
          Seu acesso grátis foi liberado por <span className="hot-highlight" style={{ fontWeight: 600 }}>{trialHours}</span>.
        </div>
        <a
          href="#cta"
          className="dock-btn"
          onClick={(e) => {
            e.preventDefault();
            window.tracker?.trackClick('floating_dock_cta');
            smoothScrollTo('cta');
          }}
        >
          Quero testar
        </a>
      </div>
    </div>
  );
}

/* ─── Tweaks ──────────────────────────────────────────────────── */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "default",
  "motion": "normal",
  "dock": true
}/*EDITMODE-END*/;

function Tweaks() {
  const [t, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  useEffect(() => { document.body.setAttribute('data-accent', t.accent); }, [t.accent]);
  useEffect(() => { document.body.setAttribute('data-motion', t.motion); }, [t.motion]);
  useEffect(() => { document.body.setAttribute('data-dock', t.dock ? 'on' : 'off'); }, [t.dock]);
  return (
    <window.TweaksPanel title="Tweaks">
      <window.TweakSection label="Acento">
        <window.TweakSelect
          label="Cor"
          value={t.accent}
          onChange={(v) => setTweak('accent', v)}
          options={[
            { value: 'default', label: 'Amarelo cinematográfico' },
            { value: 'ember', label: 'Âmbar' },
            { value: 'violet', label: 'Violeta' },
            { value: 'lime', label: 'Lima' },
            { value: 'ice', label: 'Gelo (mono)' },
          ]}
        />
      </window.TweakSection>
      <window.TweakSection label="Movimento">
        <window.TweakRadio
          label="Intensidade"
          value={t.motion}
          onChange={(v) => setTweak('motion', v)}
          options={[
            { value: 'normal', label: 'Normal' },
            { value: 'calm', label: 'Calmo' },
            { value: 'off', label: 'Off' },
          ]}
        />
      </window.TweakSection>
      <window.TweakSection label="Mobile">
        <window.TweakToggle
          label="Dock flutuante"
          value={t.dock}
          onChange={(v) => setTweak('dock', v)}
        />
      </window.TweakSection>
    </window.TweaksPanel>
  );
}

/* ─── App ─────────────────────────────────────────────────────── */
function App() {
  useReveal();
  const { progress, scrolled } = useScrollState();
  const SECTION_IDS = useMemo(() => ['beneficios', 'catalogo', 'dispositivos', 'cta'], []);
  const active = useActiveSection(SECTION_IDS);
  const [menuOpen, setMenuOpen] = useState(false);
  const [dock, setDock] = useState(true);
  const [trialHours, setTrialHours] = useState("3h");

  // Fetch trial hours config from database
  useEffect(() => {
    const loadTrialHours = async () => {
      if (window.tracker?.getTrialHours) {
        const hours = await window.tracker.getTrialHours();
        if (hours) {
          setTrialHours(hours + "h");
        }
      }
    };
    loadTrialHours();
  }, []);

  // Listen for dock toggle from the tweaks panel
  useEffect(() => {
    const initial = document.body.getAttribute('data-dock');
    if (initial !== null) setDock(initial !== 'off');
    const obs = new MutationObserver(() => {
      setDock(document.body.getAttribute('data-dock') !== 'off');
    });
    obs.observe(document.body, { attributes: true, attributeFilter: ['data-dock'] });
    return () => obs.disconnect();
  }, []);

  const showDock = dock && scrolled && !menuOpen && progress < 0.9;

  return (
    <>
      <div
        className="scroll-progress"
        style={{ width: `${progress * 100}%`, opacity: scrolled ? 1 : 0 }}
        aria-hidden="true"
      />
      <Nav
        scrolled={scrolled}
        onOpenMenu={() => setMenuOpen((v) => !v)}
        menuOpen={menuOpen}
        active={active}
      />
      <MenuSheet open={menuOpen} onClose={() => setMenuOpen(false)} />
      <main>
        <window.HeroV2 />
        <window.StreamingMarquee />
        <window.Benefits />
        <window.Catalog />
        <window.TechStability />
        <window.DevicesCarousel />
        <window.Testimonials />
        <window.HowItWorks />
        <window.PricingSection />
        <window.FinalCTAV2 />
      </main>
      <Footer />
      <MobileDock visible={showDock} trialHours={trialHours} />
      <Tweaks />
    </>
  );
}

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