/* VARIANTE D · SPLASH — salpicaduras orgánicas */

const { useState: useStateD, useEffect: useEffectD, useRef: useRefD, useCallback: useCallbackD } = React;

const FOAM_MARACUYA  = 'images/espuma-maracuya.png';
const FOAM_FRAMBUESA = 'images/espuma-frambuesa.png';

const SPLASH_HERO = "M195,18 C228,4 268,8 292,32 C318,58 310,100 322,132 C336,168 358,192 348,226 C338,260 304,272 278,292 C250,314 242,348 210,354 C178,360 150,336 122,322 C92,308 54,312 34,288 C12,264 16,230 14,198 C12,166 -4,134 4,100 C12,66 42,44 72,28 C102,12 162,32 195,18 Z";
const SPLASH_A = "M180,14 C212,2 252,6 278,28 C306,52 298,94 312,126 C328,160 352,180 344,216 C334,252 298,266 270,288 C240,312 230,350 196,358 C162,366 132,340 102,324 C70,306 28,314 8,288 C-14,260 -8,224 -10,190 C-12,156 -28,122 -18,86 C-8,50 24,28 56,12 C88,-4 148,26 180,14 Z";
const SPLASH_B = "M165,12 C200,-2 242,4 268,28 C296,54 286,98 300,132 C316,168 342,190 332,228 C320,266 282,280 252,304 C220,330 208,366 174,374 C138,382 106,356 74,338 C40,318 -2,328 -22,300 C-44,270 -38,232 -40,196 C-42,158 -60,120 -48,82 C-36,42 0,18 34,2 C70,-16 128,28 165,12 Z";
const SPLASH_C = "M188,10 C222,-2 264,4 290,28 C318,54 308,98 322,132 C338,168 364,188 354,226 C342,264 304,278 274,302 C242,328 230,366 196,374 C160,382 128,354 96,336 C62,316 18,326 -4,296 C-28,264 -22,226 -24,190 C-26,152 -44,114 -32,76 C-20,36 16,12 50,-4 C86,-22 152,24 188,10 Z";
const SPLASH_CTA = "M52,4 C68,-1 82,6 92,18 C103,31 108,50 106,68 C104,86 94,100 82,110 C69,121 54,128 40,126 C25,124 12,114 6,100 C-1,86 -2,66 2,50 C6,34 16,20 28,12 C38,5 42,7 52,4 Z";

function SplashBlob({ path, className, style, children }) {
  return (
    <div className={`splash-blob ${className||''}`} style={style}>
      <svg viewBox="-60 -10 440 390" preserveAspectRatio="none">
        <path d={path} />
      </svg>
      {children}
    </div>
  );
}

function RevealSection({ children, className, style, delay = 0 }) {
  const [ref, shown] = useReveal();
  return (
    <div ref={ref}
         className={`rv ${shown?'rv-in':''} ${className||''}`}
         style={{ ...style, transitionDelay: `${delay}ms` }}>
      {children}
    </div>
  );
}

function ProductSplash({ product, onClose }) {
  if (!product) return null;
  const cocktailImg = product.id === 'maracuya' ? 'images/coctel pisco sour maracuya .png'
    : product.id === 'frambuesa' ? 'images/coctel pisco sour de frambuesa .png'
    : 'images/coctel-pina-colada.png';
  return (
    <div className="prod-splash-overlay" onClick={onClose}>
      <div className="prod-splash-bg" style={{ '--p-tone': product.tone }}>
        <svg viewBox="-60 -10 440 390" preserveAspectRatio="none">
          <path d={SPLASH_HERO} />
        </svg>
      </div>
      <img src={cocktailImg} alt={product.name} className="prod-splash-img" />
      <div className="prod-splash-info">
        <span className="prod-splash-n">{product.n}</span>
        <h3>{product.name}</h3>
        <p>{product.mood}</p>
      </div>
    </div>
  );
}

/* Floating CTA — sigue cursor con lerp más rápido */
function FloatingCTA({ total, final, onCheckout, warning }) {
  const ref    = useRefD(null);
  const pos    = useRefD({ x: window.innerWidth - 100, y: window.innerHeight / 2 });
  const target = useRefD({ x: window.innerWidth - 100, y: window.innerHeight / 2 });
  const [vis, setVis] = useStateD(false);

  useEffectD(() => {
    const isTouchDevice = 'ontouchstart' in window;
    if (isTouchDevice) return;

    let raf;
    const onMove = e => {
      target.current.x = e.clientX + 55;
      target.current.y = e.clientY + 55;
    };

    const loop = () => {
      const p = pos.current, t = target.current;
      /* lerp 0.1 = rápido y fluido, sin lag exagerado */
      p.x += (t.x - p.x) * 0.1;
      p.y += (t.y - p.y) * 0.1;
      const breathe = Math.sin(Date.now() * 0.001) * 4;
      if (ref.current) {
        ref.current.style.transform = `translate(${p.x}px,${p.y + breathe}px) translate(-50%,-50%)`;
      }
      raf = requestAnimationFrame(loop);
    };

    const timer = setTimeout(() => setVis(true), 1200);
    raf = requestAnimationFrame(loop);
    addEventListener('mousemove', onMove);
    return () => {
      cancelAnimationFrame(raf);
      removeEventListener('mousemove', onMove);
      clearTimeout(timer);
    };
  }, []);

  if (!vis) return null;
  const hasItems = total > 0;
  const label = warning ? '!' : (hasItems ? `S/${final}` : '');

  return (
    <button ref={ref}
            className={`floating-cta ${hasItems ? 'has-items' : ''} ${warning ? 'is-warn' : ''}`}
            onClick={onCheckout} data-cursor data-cursor-label="Pedir">
      <svg className="floating-cta-shape" viewBox="-10 -10 130 150" preserveAspectRatio="none">
        <path d={SPLASH_CTA} />
      </svg>
      {hasItems && <span className="floating-cta-label">{label}</span>}
      {hasItems && <span className="floating-cta-count">{total}</span>}
    </button>
  );
}

/* Parallax sin re-renders — manipula el DOM directo en rAF */
function useParallaxRefs() {
  const foamA   = useRefD(null);
  const foamB   = useRefD(null);
  const heroTxt = useRefD(null);
  const blobA   = useRefD(null);
  const blobB   = useRefD(null);
  const bridge  = useRefD(null);
  const nav     = useRefD(null);

  useEffectD(() => {
    let raf = null;
    const tick = () => {
      raf = null;
      const y = window.scrollY;
      if (foamA.current)   foamA.current.style.transform   = `translateY(${y * 0.22}px)`;
      if (foamB.current)   foamB.current.style.transform   = `translateY(${y * 0.32}px)`;
      if (heroTxt.current) heroTxt.current.style.transform = `translateY(${-y * 0.28}px)`;
      if (blobA.current)   blobA.current.style.transform   = `translateY(${y * 0.14}px)`;
      if (blobB.current)   blobB.current.style.transform   = `translateY(${y * 0.09}px)`;
      if (bridge.current)  bridge.current.style.transform  = `translateY(${Math.max(0, (y - 300)) * 0.08}px)`;
      if (nav.current)     nav.current.classList.toggle('is-stick', y > 40);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(tick); };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => {
      window.removeEventListener('scroll', onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return { foamA, foamB, heroTxt, blobA, blobB, bridge, nav };
}

function VariantD({ accent }) {
  const { cart, total, final, add, reset, checkout, warning } = useCart();
  const [activeFoam, setActiveFoam]   = useStateD(0);
  const [menuOpen, setMenuOpen]       = useStateD(false);
  const [splashProduct, setSplashProduct] = useStateD(null);
  const px = useParallaxRefs();

  useEffectD(() => {
    const id = setInterval(() => setActiveFoam(v => (v + 1) % 2), 8000);
    return () => clearInterval(id);
  }, []);

  useEffectD(() => {
    document.body.style.overflow = (menuOpen || splashProduct) ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [menuOpen, splashProduct]);

  const handleProductClick = useCallbackD((p) => {
    setSplashProduct(p);
    setTimeout(() => setSplashProduct(null), 2800);
  }, []);

  return (
    <div className="vD" style={{ '--accent': accent }}>

      {/* ── NAV — eliminada ── */}

      {/* ── MENU OVERLAY ── */}
      {menuOpen && (
        <div className="vD-overlay" onClick={() => setMenuOpen(false)}>
          <div className="vD-overlay-inner" onClick={e => e.stopPropagation()}>
            <button className="vD-overlay-close" onClick={() => setMenuOpen(false)} data-cursor>&times;</button>
            <nav className="vD-overlay-nav">
              {['Caja', 'Ritual', 'Empresas'].map((item, i) => (
                <a key={item}
                   href={item === 'Empresas' ? 'restaurantes.html' : `#vD-${item.toLowerCase()}`}
                   className="vD-overlay-link"
                   style={{ animationDelay: `${i * 80 + 200}ms` }}
                   onClick={() => setMenuOpen(false)} data-cursor>
                  <span className="vD-overlay-link-n">0{i + 1}</span>
                  <span className="vD-overlay-link-t">{item}</span>
                </a>
              ))}
            </nav>
            <div className="vD-overlay-foot">
              <a href="https://www.instagram.com/cordial.cocteles" target="_blank" data-cursor>Instagram</a>
              <a href="https://wa.me/51997331112" target="_blank" data-cursor>WhatsApp</a>
            </div>
          </div>
        </div>
      )}

      {/* ── PRODUCT SPLASH REVEAL ── */}
      <ProductSplash product={splashProduct} onClose={() => setSplashProduct(null)} />

      {/* ── HERO — solo Ø gigante, parallax DOM-directo ── */}
      <section className="vD-hero">
        {/* capas de espuma */}
        <div className={`vD-hero-foam foam-${activeFoam}`}>
          <div ref={px.foamA} className="vD-foam-layer vD-foam-A">
            <img src={FOAM_MARACUYA} alt="" />
          </div>
          <div ref={px.foamB} className="vD-foam-layer vD-foam-B">
            <img src={FOAM_FRAMBUESA} alt="" />
          </div>
        </div>

        <div className="vD-hero-veil" />

        {/* blobs decorativos */}
        <div ref={px.blobA}>
          <SplashBlob path={SPLASH_HERO} className="splash-hero-a" />
        </div>
        <div ref={px.blobB}>
          <SplashBlob path={SPLASH_A} className="splash-hero-b" />
        </div>

        {/* Ø sola, centrada */}
        <div ref={px.heroTxt} className="vD-hero-text">
          <div className="vD-hero-o-wrap">
            <span className="vD-hero-solo-o">Ø</span>
          </div>
          <p className="vD-hero-sub">Coctelería congelada</p>
        </div>

        <div className="vD-hero-scroll"><span>Scroll</span><div /></div>
      </section>

      {/* ── FOAM BRIDGE ── */}
      <div className="vD-foam-bridge">
        <img ref={px.bridge} src={FOAM_MARACUYA} alt="" />
      </div>

      {/* ── COLECCIÓN ── */}
      <section className="vD-coleccion">
        <RevealSection className="vD-sec-head">
          <div className="vD-num">I.</div>
          <h2 className="vD-h2">Tres recetas, <em>un ritual.</em></h2>
        </RevealSection>

        <div className="vD-prod-list">
          {PRODUCTS.map((p, idx) => {
            const cocktailImg = p.id === 'maracuya' ? 'images/coctel pisco sour maracuya .png'
              : p.id === 'frambuesa' ? 'images/coctel pisco sour de frambuesa .png'
              : 'images/coctel-pina-colada.png';
            const splashPath = [SPLASH_A, SPLASH_B, SPLASH_C][idx];
            return (
              <RevealSection key={p.id} delay={idx * 120}>
                <div className={`vD-prod ${idx % 2 === 1 ? 'is-flip' : ''}`} style={{ '--p-tone': p.tone }}>
                  <div className="vD-prod-visual" onClick={() => handleProductClick(p)}
                       data-cursor data-cursor-label="Ver">
                    <SplashBlob path={splashPath} className="splash-prod" />
                    <img src={cocktailImg} alt={p.name} className="vD-prod-img" />
                  </div>
                  <div className="vD-prod-info">
                    <span className="vD-prod-n">{p.n}</span>
                    <h3 className="vD-prod-name">{p.name}</h3>
                    <p className="vD-prod-mood">{p.mood}</p>
                    <div className="vD-prod-foot">
                      <div className="vD-prod-price">S/{p.price}<small>125 ml</small></div>
                      <div className="vD-qty">
                        <button onClick={() => add(p.id, -1)} disabled={cart[p.id] <= 0} data-cursor>−</button>
                        <span>{cart[p.id]}</span>
                        <button onClick={() => add(p.id, +1)} disabled={total >= PACK_QTY} data-cursor>+</button>
                      </div>
                    </div>
                  </div>
                </div>
              </RevealSection>
            );
          })}
        </div>
      </section>

      {/* ── CAJA BUILDER ── */}
      <section className="vD-caja" id="vD-caja">
        <div className="vD-caja-grid">
          <RevealSection className="vD-caja-art">
            <SplashBlob path={SPLASH_HERO} className="splash-caja-bg" />
            <img src="images/cajamixta2.png" alt="Caja Mixta CØRDIAL" className="vD-caja-img" />
            <div className="vD-caja-stamp">
              <div>Edición</div>
              <strong>S/80</strong>
              <div>ocho unidades</div>
            </div>
          </RevealSection>

          <RevealSection className="vD-caja-side" delay={200}>
            <div className="vD-num">II.</div>
            <h2 className="vD-h2">Compón <em>ocho.</em></h2>
            <p className="vD-p">Tres recetas, tu mezcla. Caja completa S/80 (ahorras S/40). Desde 3 unidades a S/15 c/u.</p>

            <div className="vD-builder">
              <div className="vD-builder-head">
                <span>Tu selección</span>
                <strong>{total} / {PACK_QTY}</strong>
              </div>
              <div className="vD-builder-bar">
                <div className="vD-builder-fill" style={{ width: `${(total / PACK_QTY) * 100}%` }} />
              </div>
              {PRODUCTS.map(p => (
                <div key={p.id} className={`vD-builder-row ${cart[p.id] ? 'is-on' : ''}`}>
                  <div className="vD-builder-name">
                    <span className="vD-dot" style={{ background: p.tone }} />
                    {p.name}
                  </div>
                  <div className="vD-qty">
                    <button onClick={() => add(p.id, -1)} disabled={cart[p.id] <= 0} data-cursor>−</button>
                    <span>{cart[p.id]}</span>
                    <button onClick={() => add(p.id, +1)} disabled={total >= PACK_QTY} data-cursor>+</button>
                  </div>
                </div>
              ))}
            </div>

            <div className="vD-price-row">
              <div>
                <div className="vD-price-now">S/{final}</div>
                {total === PACK_QTY && (
                  <div className="vD-price-was"><s>S/120</s> <span>Ahorras S/40</span></div>
                )}
              </div>
              <div className="vD-price-cta">
                <button className={`vD-cta ${warning ? 'is-warn' : ''}`} onClick={checkout}
                        data-cursor data-cursor-label="Pedir">
                  <span>{warning ? warning : (total === 0 ? 'Componer' : `Pedir · S/${final}`)}</span>
                  <svg viewBox="0 0 24 24" width="14" height="14"><path d="M4 12h16M14 6l6 6-6 6" stroke="currentColor" strokeWidth="1.5" fill="none" /></svg>
                </button>
                <button className="vD-cta-link" onClick={reset} data-cursor>Vaciar</button>
              </div>
            </div>
          </RevealSection>
        </div>
      </section>

      {/* ── RITUAL ── */}
      <section className="vD-ritual" id="vD-ritual">
        <RevealSection className="vD-sec-head">
          <div className="vD-num">III.</div>
          <h2 className="vD-h2">Un minuto. <em>Tres pasos.</em></h2>
        </RevealSection>
        <div className="vD-ritual-grid">
          {[
            { n: '01', t: 'Vierte', b: '125 ml en la licuadora.', s: '20s' },
            { n: '02', t: 'Añade agua', b: 'Llena el envase y echa.', s: '20s' },
            { n: '03', t: 'Licúa', b: '10s a potencia alta. Sirve.', s: '10s' },
          ].map((r, i) => (
            <RevealSection key={i} delay={i * 150}>
              <div className="vD-ritual-cell">
                <SplashBlob path={[SPLASH_A, SPLASH_B, SPLASH_C][i]} className="splash-ritual" />
                <div className="vD-ritual-n">{r.n}</div>
                <h3>{r.t}</h3>
                <p>{r.b}</p>
                <span className="vD-ritual-s">{r.s}</span>
              </div>
            </RevealSection>
          ))}
        </div>
      </section>

      {/* ── B2B ── */}
      <section className="vD-b2b">
        <RevealSection className="vD-b2b-inner">
          <SplashBlob path={SPLASH_B} className="splash-b2b" />
          <div className="vD-num">IV.</div>
          <h2 className="vD-h2">¿Restaurante u hotel?</h2>
          <p className="vD-p">Programa B2B con precios mayoristas, soporte de carta y entrega programada.</p>
          <a href="restaurantes.html" className="vD-cta" data-cursor data-cursor-label="Ver">
            <span>Propuesta empresas</span>
            <svg viewBox="0 0 24 24" width="14" height="14"><path d="M4 12h16M14 6l6 6-6 6" stroke="currentColor" strokeWidth="1.5" fill="none" /></svg>
          </a>
        </RevealSection>
      </section>

      {/* ── FOOTER ── */}
      <footer className="vD-foot">
        <SplashBlob path={SPLASH_HERO} className="splash-footer" />
        <div className="vD-foot-mark">C<span className="vD-o">Ø</span>RDIAL</div>
        <div className="vD-foot-tag">Coctelería congelada · Hecha en Lima</div>
        <div className="vD-foot-grid">
          <div>
            <span>Tienda</span>
            <a href="#vD-caja" data-cursor>La caja</a>
            <a href="restaurantes.html" data-cursor>Empresas</a>
          </div>
          <div>
            <span>Contacto</span>
            <a href="https://wa.me/51997331112" target="_blank" data-cursor>WhatsApp</a>
            <a href="mailto:cordialperu@gmail.com" data-cursor>Email</a>
            <a href="https://www.instagram.com/cordial.cocteles" target="_blank" data-cursor>Instagram</a>
          </div>
          <div>
            <span>Legal</span>
            <a>+18 · Beber con moderación</a>
            <a>© CØRDIAL · 2026</a>
          </div>
        </div>
      </footer>

      {/* ── FLOATING CTA ── */}
      <FloatingCTA total={total} final={final} onCheckout={checkout} warning={warning} />
    </div>
  );
}

window.VariantD = VariantD;
