/* The Healthy Way — components */
const { useState, useEffect, useRef } = React;
const D = window.THW;

/* ---------- helpers ---------- */
function useReveal(opts = {}) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) { el.classList.add('in'); io.unobserve(el); } });
    }, { threshold: opts.threshold ?? 0.18, rootMargin: opts.rootMargin ?? '0px 0px -8% 0px' });
    io.observe(el); return () => io.disconnect();
  }, []);
  return ref;
}
function Reveal({ as: Tag = 'div', className = '', children, ...rest }) {
  const ref = useReveal();
  return <Tag ref={ref} className={('reveal ' + className).trim()} {...rest}>{children}</Tag>;
}
const Arrow = ({ s = 16 }) => (
  <svg className="arr" width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="square">
    <path d="M5 12h14M13 6l6 6-6 6" />
  </svg>
);
const Logo = ({ className = '' }) => (
  <span className={'logoMark ' + className} role="img" aria-label="The Healthy Way"
    dangerouslySetInnerHTML={{ __html: window.LOGO_SVG || '' }} />
);

/* ---------- NAV ---------- */
function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll(); window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <React.Fragment>
      <header className={'nav' + (scrolled ? ' scrolled' : '')}>
        <div className="navIn">
          <a className="logo" href={D.site} aria-label="The Healthy Way"><Logo /></a>
          <nav className="navLinks">
            {D.nav.map((n) => <a key={n.label} href={n.href}>{n.label}</a>)}
          </nav>
          <div className="navCta">
            <a className="ingresar" href={D.ingresar}>INGRESAR</a>
            <button className={'burger' + (open ? ' open' : '')} onClick={() => setOpen(o => !o)} aria-label="Menú">
              <span></span><span></span><span></span>
            </button>
          </div>
        </div>
      </header>
      <div className={'mobileMenu' + (open ? ' open' : '')}>
        {D.nav.map((n) => <a key={n.label} href={n.href} onClick={() => setOpen(false)}>{n.label}</a>)}
        <a href={D.ingresar} onClick={() => setOpen(false)}>INGRESAR</a>
      </div>
    </React.Fragment>
  );
}

/* ---------- HERO ---------- */
function Hero({ layout, scaleBig }) {
  const ref = useReveal({ threshold: 0.01 });
  const vref = useRef(null);
  useEffect(() => {
    const v = vref.current; if (!v) return;
    v.muted = true;
    const tryPlay = () => { const p = v.play(); if (p && p.catch) p.catch(() => {}); };
    tryPlay();
    const onCan = () => tryPlay();
    v.addEventListener('canplay', onCan);
    const onInteract = () => tryPlay();
    document.addEventListener('pointerdown', onInteract, { once: true });
    return () => { v.removeEventListener('canplay', onCan); document.removeEventListener('pointerdown', onInteract); };
  }, []);
  const h = D.hero;
  return (
    <section className={'hero ' + layout + (scaleBig ? ' scaleBig' : '')} id="inicio">
      <video ref={vref} className="heroVideo" autoPlay muted loop playsInline preload="auto">
        <source src="assets/hero.mp4" type="video/mp4" />
      </video>
      <div className="heroFallback" aria-hidden="true"></div>
      <div className="scrim"></div>
      {layout === 'left' && <div className="scrim2"></div>}
      <div className="container">
        <div ref={ref} className="heroContent reveal in">
          <div className="heroMain">
            <div className="heroEyebrow eyebrow">{h.eyebrow}</div>
            <h1 className="display heroTitle">
              <span className="lineMask"><span>{h.line1}</span></span>
              <span className="lineMask l2"><span className="l2">{h.line2}</span></span>
            </h1>
            <p className="heroSub">{h.sub}</p>
            <div className="heroBtns">
              <a className="btn btn-primary" href={h.ctaPrimary.href}>{h.ctaPrimary.label}<Arrow /></a>
              <a className="btn btn-ghost" href={h.ctaSecondary.href}>{h.ctaSecondary.label}</a>
            </div>
          </div>
          {layout === 'split' && (
            <div className="heroSideStat">
              <div className="heroStats" style={{ justifyContent: 'flex-end' }}>
                <div className="heroStat"><div className="n">+8</div><div className="l">Años</div></div>
                <div className="heroStat"><div className="n">10</div><div className="l">Programas</div></div>
              </div>
            </div>
          )}
        </div>
      </div>
      <div className="scrollCue"><span>SCROLL</span><span className="bar"></span></div>
    </section>
  );
}

/* ---------- MARQUEE ---------- */
function Marquee({ reverse }) {
  const items = D.marquee;
  const row = (
    <div className="marqItemSet" style={{ display: 'inline-flex' }}>
      {items.map((t, i) => (
        <span className="marqItem" key={i}>{t}<span className="dot"></span></span>
      ))}
    </div>
  );
  return (
    <div className="marquee">
      <div className={'marqueeTrack' + (reverse ? ' rev' : '')}>{row}{row}</div>
    </div>
  );
}

/* ---------- SCROLL-DRIVEN MARQUEE ---------- */
function ScrollMarquee({ text, sub }) {
  const t = text || "TRANSFORMÁ TU CUERPO";
  const s = sub || "TU MENTE · TU VIDA";
  return (
    <div className="scrollMarquee" aria-hidden="true">
      <div className="smRow" data-scrollx="-560"><span>{(t + " — ").repeat(4)}</span></div>
      <div className="smRow ghost" data-scrollx="560"><span>{(s + " — ").repeat(4)}</span></div>
    </div>
  );
}

/* ---------- MANIFESTO ---------- */
function Manifesto() {
  const m = D.manifesto;
  return (
    <section className="manifesto">
      <div className="container">
        <Reveal>
          <h2 className="display manifestoBig">
            <span className="lineMask"><span>{m.big1}</span></span>
            <span className="lineMask l2"><span className="accent">{m.big2}</span></span>
          </h2>
        </Reveal>
        <Reveal className="d2">
          <div className="manifestoLines">
            {m.lines.map((l, i) => <div key={i}>{l}</div>)}
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- PROGRAMS STACK (sticky) ---------- */
function ProgramsStack() {
  const flags = D.plans.filter((p) => p.flagship);
  const headRef = useReveal();
  return (
    <section className="stackSec" id="programas">
      <div className="container">
        <div ref={headRef} className="secHead reveal">
          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>PROGRAMAS DESTACADOS</div>
            <h2 className="display htitle">ELEGÍ TU CAMINO</h2>
          </div>
          <div className="hside">Cada programa, un mundo. Deslizá para descubrir los caminos que más transforman.</div>
        </div>
      </div>
      <div className="stack">
        {flags.map((p, i) => (
          <article className="stackCard" key={p.name} style={{ '--i': i, zIndex: i + 1 }}>
            <a className="stackInner" href={p.href}>
              <div className="stackImgWrap">
                <div className="ph"><span className="num">{String(i + 1).padStart(2, '0')}</span><span className="phHint">Foto del plan</span></div>
                {p.img && <img className="stackImg" data-parallax="30" src={p.img} alt={p.name} onError={(e) => { e.target.style.display = 'none'; }} />}
              </div>
              <div className="stackScrim"></div>
              <div className="stackContent">
                <div className="container stackGrid">
                  <div className="stackIndex">{String(i + 1).padStart(2, '0')} <span>/ {String(flags.length).padStart(2, '0')}</span></div>
                  <div className="stackMain">
                    <div className="stackTag">{p.tag}</div>
                    <h3 className="display stackTitle">{p.name}</h3>
                    <p className="stackDesc">{p.desc}</p>
                    <span className="btn btn-primary">+ INFO <Arrow /></span>
                  </div>
                </div>
              </div>
            </a>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ---------- PLANS ---------- */
function PlanCard({ p, i, layout }) {
  const ref = useReveal();
  return (
    <a ref={ref} className={'card reveal' + (p.featured ? ' feat' : '')} href={p.href} style={{ transitionDelay: (i % 4) * 0.06 + 's' }}>
      <div className="media">
        <div className="ph"><span className="num">{String(i + 1).padStart(2, '0')}</span><span className="phHint">Foto del plan</span></div>
        {p.img && <img className="cardImg" data-parallax="22" src={p.img} alt={p.name} loading="lazy" onError={(e) => { e.target.style.display = 'none'; }} />}
      </div>
      <div className="grad"></div>
      {p.featured && <span className="badge">MÁS ELEGIDO</span>}
      <div className="body">
        <div className="tag">{p.tag}</div>
        <h3 className="pname">{p.name}</h3>
        <p className="pdesc">{p.desc}</p>
        <span className="info">+ INFO <Arrow s={15} /></span>
      </div>
    </a>
  );
}
function Plans({ layout }) {
  let plans = D.plans;
  return (
    <section className={'section plans layout-' + layout} id="planes">
      <div className="container">
        <div className="secHead">
          <Reveal>
            <div className="eyebrow" style={{ marginBottom: 18 }}>EL CATÁLOGO COMPLETO</div>
            <h2 className="display htitle">TODOS LOS PLANES</h2>
          </Reveal>
          <Reveal className="d1 hside">
            Diez caminos, un mismo objetivo: tu transformación. Elegí el que mejor se adapta a vos y empezá hoy.
          </Reveal>
        </div>
        <div className="plansGrid">
          {plans.map((p, i) => <PlanCard key={p.name} p={p} i={i} layout={layout} />)}
        </div>
      </div>
    </section>
  );
}

/* ---------- COMPARISON ---------- */
function Comparison() {
  const c = D.comparison;
  return (
    <section className="section compare" id="porque">
      <div className="container">
        <div className="secHead">
          <Reveal><h2 className="display htitle">NO ES LO MISMO<br />SOLA QUE ACOMPAÑADA</h2></Reveal>
          <Reveal className="d1 hside">La diferencia entre intentarlo y lograrlo está en tener un método, corrección y a alguien que no te suelta la mano.</Reveal>
        </div>
        <Reveal className="compareGrid">
          <div className="compCol bad">
            <h3>{c.leftTitle}</h3>
            <div className="compList">
              {c.left.map((t, i) => <div className="compRow" key={i}><span className="ic">✕</span><span>{t}</span></div>)}
            </div>
          </div>
          <div className="compCol good">
            <h3>{c.rightTitle}</h3>
            <div className="compList">
              {c.right.map((t, i) => <div className="compRow" key={i}><span className="ic">✓</span><span>{t}</span></div>)}
            </div>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- COACHING feature ---------- */
function Coaching() {
  const c = D.coaching;
  return (
    <section className="section coaching" id="coaching">
      <div className="container">
        <div className="coachWrap">
          <Reveal className="coachLeft">
            <div className="eyebrow" style={{ marginBottom: 18 }}>{c.eyebrow}</div>
            <h2 className="display ctitle">{c.title}</h2>
            <p className="cdesc">{c.desc}</p>
            <div className="cmeta">
              <div><div className="n">{c.duration}</div><div className="l">Duración</div></div>
              <div><div className="n">1 : 1</div><div className="l">Seguimiento</div></div>
            </div>
          </Reveal>
          <Reveal className="d2 priceCard">
            <div className="pcTag">PROGRAMA COMPLETO</div>
            <div className="pcHead">
              <div className="pcPrice">{c.price}</div>
              <div className="pcDur">{c.duration}</div>
            </div>
            <ul>
              {c.includes.map((t, i) => <li key={i}><span className="chk">✓</span><span>{t}</span></li>)}
            </ul>
            <a className="btn btn-primary" href={c.cta.href}>{c.cta.label}<Arrow /></a>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- STORY ---------- */
function Story() {
  const s = D.story;
  return (
    <section className="section story" id="sobre-mi">
      <div className="container">
        <div className="storyWrap">
          <Reveal className="storyPortrait">
            <div className="ph"><span className="mk">CC</span><span className="mono">Foto de Cata</span></div>
            {s.img && <img className="storyImg" data-parallax="26" src={s.img} alt="Cata Cohan" onError={(e) => { e.target.style.display = 'none'; }} />}
          </Reveal>
          <Reveal className="d1 storyText">
            <div className="eyebrow" style={{ marginBottom: 16 }}>{s.eyebrow}</div>
            <h2 className="display stitle">{s.title}</h2>
            {s.paras.map((p, i) => <p key={i}>{p}</p>)}
            <p className="storyQuote">“{s.quote}”</p>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

/* ---------- CTA ---------- */
function CTA() {
  const c = D.cta;
  return (
    <section className="cta" id="contacto">
      <div className="container">
        <Reveal>
          <h2 className="display ctaBig">
            <span className="lineMask"><span>{c.big1}</span></span>
            <span className="lineMask l2"><span className="accent">{c.big2}</span></span>
          </h2>
        </Reveal>
        <Reveal className="d2"><p className="ctaSub">{c.sub}</p></Reveal>
        <Reveal className="d3 ctaBtns">
          <a className="btn btn-wa" href={D.whatsapp} target="_blank" rel="noopener">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 0 0-8.6 15l-1.3 4.7 4.8-1.3A10 10 0 1 0 12 2Zm5.8 14.2c-.2.7-1.4 1.3-2 1.4-.5.1-1.2.1-1.9-.1-.4-.1-1-.3-1.7-.6-3-1.3-4.9-4.3-5-4.5-.2-.2-1.2-1.6-1.2-3 0-1.5.8-2.2 1-2.5.3-.3.6-.4.8-.4h.6c.2 0 .4 0 .6.5l.8 2c.1.2.1.4 0 .5l-.4.6-.3.3c-.2.2-.3.4-.1.7.2.3.9 1.4 1.9 2.3 1.3 1.1 2.3 1.5 2.6 1.6.3.1.5.1.7-.1l.8-1c.2-.3.4-.2.7-.1l2 .9c.3.2.5.2.6.4.1.1.1.6-.1 1.3Z"/></svg>
            {c.button}<Arrow />
          </a>
          <a className="btn btn-ghost" href={D.coaching ? D.coaching.cta.href : '#planes'} >VER COACHING 1 A 1</a>
        </Reveal>
      </div>
    </section>
  );
}

/* ---------- FOOTER ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footTop">
          <div className="footAbout">
            <a className="footLogo" href={D.site} aria-label="The Healthy Way"><Logo /></a>
            <p>Planes de entrenamiento, nutrición y coaching para transformar tu cuerpo y tu mente. The Healthy Way by Cata Cohan.</p>
          </div>
          <div className="footCol">
            <h4>Navegación</h4>
            {D.nav.map((n) => <a key={n.label} href={n.href}>{n.label}</a>)}
          </div>
          <div className="footCol">
            <h4>Programas</h4>
            {D.plans.slice(0, 6).map((p) => <a key={p.name} href={p.href}>{p.name}</a>)}
          </div>
        </div>
        <div className="footBottom">
          <span>© {new Date().getFullYear()} The Healthy Way · Todos los derechos reservados</span>
          <a className="igbtn" href={D.instagram} target="_blank" rel="noopener">
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
            INSTAGRAM
          </a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Nav, Hero, Marquee, ScrollMarquee, Manifesto, ProgramsStack, Plans, Comparison, Coaching, Story, CTA, Footer, Reveal, Logo, initScrollFx });

/* ---------- scroll fx engine ---------- */
function initScrollFx() {
  if (window.__fxBound) return; window.__fxBound = true;
  const q = (s) => [...document.querySelectorAll(s)];
  let parallax = [], stackCards = [], scrollx = [];
  const collect = () => { parallax = q('[data-parallax]'); stackCards = q('.stackCard'); scrollx = q('[data-scrollx]'); };
  collect();
  const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
  const fine = matchMedia('(pointer:fine)').matches;
  if (window.__fxK == null) window.__fxK = 1;
  let ticking = false;
  function update() {
    const K = window.__fxK ?? 1;
    const vh = window.innerHeight;
    if (!reduce) parallax.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.bottom < -120 || r.top > vh + 120) return;
      const prog = (r.top + r.height / 2 - vh / 2) / vh; // -0.5..0.5
      const amt = (parseFloat(el.dataset.parallax) || 14) * K;
      el.style.transform = 'translate3d(0,' + (-prog * amt).toFixed(2) + '%,0)';
    });
    if (!reduce) scrollx.forEach((el) => {
      const r = el.getBoundingClientRect();
      if (r.bottom < -160 || r.top > vh + 160) return;
      const prog = (vh - r.top) / (vh + r.height); // 0..1 as it crosses viewport
      const amt = (parseFloat(el.dataset.scrollx) || 300) * K;
      el.style.transform = 'translate3d(' + ((prog - 0.5) * amt).toFixed(1) + 'px,0,0)';
    });
    stackCards.forEach((card, i) => {
      const next = stackCards[i + 1];
      const inner = card.querySelector('.stackInner');
      const scrim = card.querySelector('.stackScrim');
      if (!next) { if (inner) inner.style.transform = ''; if (scrim) scrim.style.opacity = ''; return; }
      const nr = next.getBoundingClientRect();
      const p = Math.min(1, Math.max(0, (vh - nr.top) / vh));
      const depth = Math.max(0.8, 1 - p * (0.13 * K));      // stronger recede
      const lift = -p * 30 * K;                              // push card up as next overlaps
      if (inner) inner.style.transform = 'scale(' + depth.toFixed(3) + ') translateY(' + lift.toFixed(1) + 'px)';
      if (scrim) scrim.style.opacity = Math.min(0.94, 0.24 + p * 0.62).toFixed(2);
    });
    ticking = false;
  }
  const onScroll = () => { if (!ticking) { ticking = true; requestAnimationFrame(update); } };
  window.addEventListener('scroll', onScroll, { passive: true });
  window.addEventListener('resize', () => { collect(); update(); });
  setTimeout(() => { collect(); update(); }, 300);
  update();

  /* ---- magnetic buttons + card tilt (efectos puntuales) ---- */
  if (fine && !reduce) {
    let active = null;
    const reset = () => {
      if (!active) return;
      active.style.transition = 'transform .5s var(--ease)';
      active.style.transform = '';
      const a = active.querySelector('.arr'); if (a) a.style.transform = '';
      active = null;
    };
    const onMove = (e) => {
      const K = window.__fxK ?? 1;
      const btn = (window.__magnetic !== false) && e.target.closest('.btn, .ingresar');
      const card = !btn && (window.__tilt !== false) && e.target.closest('.card');
      if (btn) {
        if (active && active !== btn) reset();
        const r = btn.getBoundingClientRect();
        const mx = e.clientX - (r.left + r.width / 2);
        const my = e.clientY - (r.top + r.height / 2);
        const s = 0.32;
        btn.style.transition = 'transform .18s var(--ease)';
        btn.style.transform = 'translate(' + (mx * s).toFixed(1) + 'px,' + (my * s - 2).toFixed(1) + 'px)';
        const a = btn.querySelector('.arr'); if (a) a.style.transform = 'translateX(' + (6 + mx * 0.14).toFixed(1) + 'px)';
        active = btn;
      } else if (card) {
        if (active && active !== card) reset();
        const r = card.getBoundingClientRect();
        const px = (e.clientX - r.left) / r.width - 0.5;
        const py = (e.clientY - r.top) / r.height - 0.5;
        const d = 7 * Math.min(1.6, K);
        card.style.transition = 'transform .2s var(--ease)';
        card.style.transform = 'perspective(1100px) rotateY(' + (px * d).toFixed(2) + 'deg) rotateX(' + (-py * d).toFixed(2) + 'deg)';
        active = card;
      } else if (active) {
        reset();
      }
    };
    document.addEventListener('pointermove', onMove, { passive: true });
    document.addEventListener('pointerleave', reset);
  }
}
