/* global React, Icon, gsap */
const { useState, useEffect, useRef } = React;

const NAV = [
  { label: 'SERVICIOS', href: '#servicios' },
  { label: 'RITUALES', href: '#solucion' },
  { label: 'TESTIMONIOS', href: '#testimonios' },
  { label: 'CONTACTO', href: '#consulta' },
];

/* Video presence presets — reshape how alive the background feels */
const MOTION = {
  intimo:      { amp: 6,  scale: 1.03 },
  equilibrado: { amp: 14, scale: 1.06 },
  envolvente:  { amp: 26, scale: 1.13 },
};

/* Editorial voice — reshapes the hero message */
const COPY = {
  sereno: {
    l1: 'Lo que se fue, también puede trabajarse.',
    l2: 'Retorno del ser amado, suerte, limpias y protección.',
    subA: 'Trabajo espiritual guiado, con seriedad y sin promesas vacías.',
    subB: ' Cada caso se explica antes de empezar.',
    cta: 'Quiero mi consulta',
  },
  cercano: {
    l1: 'No tienes que cargar esto en soledad.',
    l2: 'Retorno del ser amado, suerte, limpias y protección.',
    subA: 'Estamos aquí para escucharte y acompañarte con calma.',
    subB: ' Sin juicios, a tu ritmo.',
    cta: 'Hablemos hoy',
  },
  directo: {
    l1: 'Recupera lo que perdiste.',
    l2: 'Amor, suerte, limpias y protección.',
    subA: 'Resultados con método y seriedad, no promesas vacías.',
    subB: ' Primera consulta gratis.',
    cta: 'Empezar ahora',
  },
};

/* ============================================================
   NAVBAR — fixed, glass pill center, collapses <768px
   ============================================================ */
const Navbar = () => {
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header className={`site-header fixed top-0 inset-x-0 z-50 px-6 md:px-10 flex justify-between items-center ${scrolled ? 'scrolled py-4' : 'py-6 md:py-7'}`}>
      <a href="#top" className="flex items-center" aria-label="Congregación En La Fe">
        <span className="logo-chip"><img src={(window.__resources && window.__resources.logo) || "assets/logo.png"} alt="Congregación En La Fe" /></span>
      </a>

      <nav className="liquid-glass rounded-full px-2 py-2 hidden md:flex items-center gap-1">
        {NAV.map(n => (
          <a key={n.label} href={n.href}
            className="nav-pill text-[11px] font-medium tracking-[0.12em] text-white/90 hover:text-white px-4 py-1.5 rounded-full transition-colors">
            {n.label}
          </a>
        ))}
      </nav>

      <a href="#consulta"
        className="liquid-glass rounded-full px-5 py-2.5 text-[11px] font-medium tracking-[0.12em] text-white/90 hover:text-white transition-colors hidden md:inline-flex">
        QUIERO MI CONSULTA
      </a>

      <button onClick={() => setOpen(true)} aria-label="Abrir menú"
        className="md:hidden liquid-glass rounded-full w-11 h-11 flex items-center justify-center text-white">
        <Icon name="menu" size={20} />
      </button>

      {open && (
        <div className="mobile-menu fixed inset-0 z-[60] bg-[#0B1220]/95 backdrop-blur-xl flex flex-col items-center justify-center gap-8 md:hidden">
          <button onClick={() => setOpen(false)} aria-label="Cerrar"
            className="absolute top-6 right-6 w-11 h-11 rounded-full liquid-glass flex items-center justify-center text-white">
            <Icon name="x" size={20} />
          </button>
          {NAV.map(n => (
            <a key={n.label} href={n.href} onClick={() => setOpen(false)}
              className="font-fraunces text-2xl text-white/90 hover:text-white">
              {n.label.charAt(0) + n.label.slice(1).toLowerCase()}
            </a>
          ))}
          <a href="#consulta" onClick={() => setOpen(false)}
            className="mt-2 rounded-full px-8 py-3.5 text-[15px] font-medium"
            style={{ background: '#F4EFE6', color: '#0B1220' }}>
            Quiero mi consulta
          </a>
        </div>
      )}
    </header>
  );
};

/* ============================================================
   VIDEO BACKGROUND — ping-pong + GSAP mouse parallax
   ============================================================ */
const VideoBackground = ({ motion = 'equilibrado' }) => {
  const cfg = MOTION[motion] || MOTION.equilibrado;
  const wrapRef = useRef(null);
  const videoRef = useRef(null);

  // Ping-pong playback
  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    let raf, last = 0, dir = 1;
    const RATE = 1; // reverse scrub speed multiplier

    const onLoaded = () => { v.playbackRate = 1; v.play().catch(() => {}); };

    const onEnded = () => {
      // switch to reverse scrub from the end
      dir = -1;
      v.pause();
      last = performance.now();
      raf = requestAnimationFrame(scrub);
    };

    const scrub = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      if (dir === -1) {
        v.currentTime = Math.max(0, v.currentTime - dt * RATE);
        if (v.currentTime <= 0.02) {
          dir = 1;
          v.currentTime = 0;
          v.play().catch(() => {});
          return; // native forward takes over; ended fires again
        }
        raf = requestAnimationFrame(scrub);
      }
    };

    v.addEventListener('loadeddata', onLoaded);
    v.addEventListener('ended', onEnded);
    if (v.readyState >= 2) onLoaded();

    return () => {
      cancelAnimationFrame(raf);
      v.removeEventListener('loadeddata', onLoaded);
      v.removeEventListener('ended', onEnded);
    };
  }, []);

  // GSAP mouse parallax with lerp
  useEffect(() => {
    const el = wrapRef.current;
    if (!el || typeof gsap === 'undefined') return;
    let targetX = 0, targetY = 0, curX = 0, curY = 0, raf;
    const cx = window.innerWidth / 2, cy = window.innerHeight / 2;
    const onMove = (e) => {
      targetX = ((e.clientX - cx) / cx) * cfg.amp;
      targetY = ((e.clientY - cy) / cy) * cfg.amp;
    };
    const tick = () => {
      curX += (targetX - curX) * 0.06;
      curY += (targetY - curY) * 0.06;
      gsap.set(el, { x: curX, y: curY });
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(raf); };
  }, [cfg.amp]);

  return (
    <div className="fixed inset-0 z-0 overflow-hidden">
      <div ref={wrapRef} className="absolute inset-0 origin-center" style={{ transform: `scale(${cfg.scale})` }}>
        <video ref={videoRef} className="w-full h-full object-cover"
          autoPlay muted playsInline preload="auto">
          <source src={(window.__resources && window.__resources.video) || "assets/transition.mp4"} type="video/mp4" />
        </video>
      </div>
      <div className="absolute inset-0"
        style={{ background: 'linear-gradient(180deg, rgba(11,18,32,var(--overlay-top)) 0%, rgba(11,18,32,calc((var(--overlay-top) + var(--overlay-bottom)) / 2)) 45%, rgba(11,18,32,var(--overlay-bottom)) 100%)' }} />
    </div>
  );
};

/* ============================================================
   HERO
   ============================================================ */
const Hero = ({ tone = 'sereno', motion = 'equilibrado' }) => {
  const c = COPY[tone] || COPY.sereno;
  const [shown, setShown] = useState(false);
  useEffect(() => { const t = setTimeout(() => setShown(true), 80); return () => clearTimeout(t); }, []);
  const base = 'transition-all duration-1000 ease-[cubic-bezier(.2,.8,.2,1)]';
  const on = shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-6';

  return (
    <section id="top" className="relative min-h-screen">
      <VideoBackground motion={motion} />

      {/* Headline */}
      <div className="absolute left-1/2 -translate-x-1/2 z-20 w-full px-6 text-center" style={{ top: 130 }}>
        <h1 className={`font-fraunces font-light ${base} ${on}`}
          style={{ fontSize: 'clamp(38px,5.2vw,68px)', lineHeight: 1.15, letterSpacing: '-0.01em' }}>
          <span className="block text-white">{c.l1}</span>
          <span className="block" style={{ color: 'rgba(255,255,255,0.55)' }}>
            {c.l2}
          </span>
        </h1>
      </div>

      {/* Bottom block */}
      <div className={`absolute inset-x-0 z-20 flex flex-col items-center gap-6 px-6 text-center ${base} delay-300 ${on}`}
        style={{ bottom: 56 }}>
        <p className="max-w-[600px] text-[15px] leading-relaxed">
          <span className="text-white">{c.subA}</span>
          <span style={{ color: 'rgba(255,255,255,0.55)' }}>{c.subB}</span>
        </p>
        <a href="#consulta"
          className="rounded-full px-8 py-3.5 text-[15px] font-medium transition-all duration-300 hover:scale-[1.03] active:scale-[0.97]"
          style={{ background: '#F4EFE6', color: '#0B1220' }}
          onMouseEnter={e => e.currentTarget.style.boxShadow = '0 0 32px 4px rgb(var(--gold) / 0.25)'}
          onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}>
          {c.cta}
        </a>
        <div className="flex items-center gap-2 text-white/70">
          <Icon name="lock" size={13} strokeWidth={1.5} />
          <span className="text-[11px] tracking-[0.14em]">100% CONFIDENCIAL.</span>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Navbar, Hero, VideoBackground });
