/* CØRDIAL · Nueva Web · 3 variaciones
   Variantes:
     A · EDITORIAL  → tipo Kettmeir, foto + serif
     B · BOLD       → tipografía gigante, contraste, marquesinas
     C · MAGAZINE   → grid asimétrico, microinteracciones
*/

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

/* ----------------------------------------------------------------
   PRODUCTS — espejo del original
---------------------------------------------------------------- */
const PRODUCTS = [
  { id:'maracuya',  n:'01', name:'Pisco Søur de Maracuyá',   short:'Maracuyá',  fruit:'Maracuyá',  ml:125, price:15, img:'images/01.png', label:'images/pisco-sour-maracuya-169.png', tone:'#E8842B', mood:'Cítrico · Dulce · Tropical', notes:'pulpa fresca · pisco quebranta · clara de huevo' },
  { id:'frambuesa', n:'02', name:'Pisco Søur de Frambuesa',  short:'Frambuesa', fruit:'Frambuesa', ml:125, price:15, img:'images/02.png', label:'images/pisco-sour-frambuesa-169.png', tone:'#C8385C', mood:'Floral · Berries · Suave',     notes:'frambuesa peruana · pisco italia · limón' },
  { id:'pina',      n:'03', name:'Piña Cølada',              short:'Piña',      fruit:'Piña',      ml:125, price:15, img:'images/03.png', label:'images/pina-colada-169.png', tone:'#D9B33A', mood:'Tropical · Dulce',              notes:'piña en almíbar · pisco acholado · té negro' }
];

const PACK_PRICE = 60;
const MIN_QTY = 3;
const PACK_QTY = 6;
const WA_NUMBER = '51997331112';

/* ----------------------------------------------------------------
   useCart — lógica reutilizada por todas las variaciones
---------------------------------------------------------------- */
function useCart(){
  const init = useMemo(()=>Object.fromEntries(PRODUCTS.map(p=>[p.id,0])),[]);
  const [cart, setCart] = useState(init);
  const [warning, setWarning] = useState(null);

  const total = Object.values(cart).reduce((a,b)=>a+b,0);
  const subtotal = total * 15;
  const final = total === PACK_QTY ? PACK_PRICE : subtotal;

  const add = useCallback((id, d=1)=>{
    setCart(prev=>{
      const t = Object.values(prev).reduce((a,b)=>a+b,0);
      if(d>0 && t>=PACK_QTY) return prev;
      const next = { ...prev, [id]: Math.max(0, Math.min(PACK_QTY, prev[id]+d)) };
      return next;
    });
  },[]);

  const reset = useCallback(()=>setCart(init),[init]);

  const checkout = useCallback(()=>{
    if(total < MIN_QTY){
      setWarning(`Mínimo ${MIN_QTY} unidades para realizar el pedido`);
      setTimeout(()=>setWarning(null), 2400);
      return;
    }
    const totalPrice = total === PACK_QTY ? PACK_PRICE : total*15;
    const precioBotella = totalPrice / total;
    const items = PRODUCTS.filter(p=>cart[p.id]>0).map(p=>({
      id:p.id, n:p.n, nombre:p.name, sku:'',
      botellas:cart[p.id], unidades:cart[p.id], cajas:0,
      precio_unit:precioBotella
    }));
    if(window.B2B && typeof window.B2B.open === 'function'){
      window.B2B.open({ boxes: total, pricePerBox: precioBotella, total: totalPrice, items, modo:'b2c' });
    }else{
      const lines = items.map(it => `· ${it.botellas} × ${it.nombre} (N.º ${it.n})`).join('%0A');
      const msg = `Hola, CØRDIAL%0A%0AQuiero pedir:%0A${lines}%0A%0ATotal: S/${totalPrice}%0A%0AGracias.`;
      window.open(`https://wa.me/${WA_NUMBER}?text=${msg}`, '_blank');
    }
  },[cart, total]);

  // Wire B2B reset hook
  useEffect(()=>{
    window.B2B_onSubmitted = ()=>setCart(init);
    return ()=>{ delete window.B2B_onSubmitted; };
  },[init]);

  return { cart, total, subtotal, final, add, reset, checkout, warning };
}

/* ----------------------------------------------------------------
   useReveal — IntersectionObserver hook para reveals
---------------------------------------------------------------- */
function useReveal(){
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(()=>{
    if(!ref.current) return;
    const io = new IntersectionObserver((es)=>{
      es.forEach(e=>{ if(e.isIntersecting){ setShown(true); io.disconnect(); } });
    },{ threshold: 0.12 });
    io.observe(ref.current);
    return ()=>io.disconnect();
  },[]);
  return [ref, shown];
}

/* ----------------------------------------------------------------
   useScrollY — para parallax / progress
---------------------------------------------------------------- */
function useScrollY(){
  const [y, setY] = useState(0);
  useEffect(()=>{
    let raf;
    const onS = ()=>{ if(raf) return; raf = requestAnimationFrame(()=>{ setY(window.scrollY); raf=null; }); };
    window.addEventListener('scroll', onS, {passive:true});
    return ()=>window.removeEventListener('scroll', onS);
  },[]);
  return y;
}

/* ----------------------------------------------------------------
   Custom cursor — gota líquida + membrana orgánica
   · La gota se ESTIRA en la dirección del movimiento (squash & stretch)
     y rota hacia donde viaja: se siente líquida, no un punto rígido.
   · La membrana exterior (solo la línea) respira con un morph orgánico
     y se expande sobre interactivos mostrando el label (p.ej. "Ver").
   · Al hacer click, suelta burbujas que estallan.
---------------------------------------------------------------- */
function Cursor({ accent, enabled }){
  const dotRef = useRef(null);
  const ringRef = useRef(null);
  const [hover, setHover] = useState(false);
  const [down, setDown] = useState(false);
  const [label, setLabel] = useState('');
  /* intro: al cargar, el cursor es una FLECHA hacia abajo (invita a
     scrollear); con el primer scroll se transforma en la circunferencia */
  const [intro, setIntro] = useState(true);

  useEffect(()=>{
    if(!enabled) return;
    const onIntroScroll = ()=>{
      if (window.scrollY > 24){
        setIntro(false);
        window.removeEventListener('scroll', onIntroScroll);
      }
    };
    window.addEventListener('scroll', onIntroScroll, { passive: true });
    onIntroScroll();
    return ()=>window.removeEventListener('scroll', onIntroScroll);
  },[enabled]);

  useEffect(()=>{
    if(!enabled) return;
    let dx=innerWidth/2, dy=innerHeight/2, rx=dx, ry=dy, tx=dx, ty=dy;
    let ang = 0;
    const onMove = e => { tx=e.clientX; ty=e.clientY; };
    let raf;
    const loop = ()=>{
      const pdx = dx, pdy = dy;
      dx += (tx-dx)*0.42; dy += (ty-dy)*0.42;
      rx += (tx-rx)*0.14; ry += (ty-ry)*0.14;
      /* velocidad → estiramiento de la gota */
      const vx = dx-pdx, vy = dy-pdy;
      const spd = Math.min(1, Math.hypot(vx, vy) / 26);
      if (spd > 0.04) ang = Math.atan2(vy, vx) * 180 / Math.PI;
      const sx = 1 + spd * 0.85;       /* se alarga hacia el movimiento */
      const sy = 1 - spd * 0.38;       /* y se achata perpendicular     */
      if(dotRef.current) dotRef.current.style.transform =
        `translate(${dx}px,${dy}px) translate(-50%,-50%) rotate(${ang}deg) scale(${sx},${sy})`;
      if(ringRef.current) ringRef.current.style.transform =
        `translate(${rx}px,${ry}px) translate(-50%,-50%)`;
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    addEventListener('mousemove', onMove);
    const onOver = e => {
      const t = e.target.closest('[data-cursor]') || e.target.closest('a, button');
      if(t){
        setHover(true);
        setLabel(t.getAttribute && t.getAttribute('data-cursor-label') || '');
      } else {
        setHover(false); setLabel('');
      }
    };
    addEventListener('mouseover', onOver);
    /* click → burbujas que estallan desde el punto */
    const onDown = e => {
      setDown(true);
      for(let i=0;i<6;i++){
        const b = document.createElement('i');
        b.className = 'cur-burbuja';
        const a = (i/6)*Math.PI*2 + Math.random()*0.8;
        const d = 16 + Math.random()*26;
        b.style.left = e.clientX+'px';
        b.style.top  = e.clientY+'px';
        b.style.setProperty('--bx', (Math.cos(a)*d).toFixed(1)+'px');
        b.style.setProperty('--by', (Math.sin(a)*d).toFixed(1)+'px');
        b.style.width = b.style.height = (4 + Math.random()*5).toFixed(1)+'px';
        document.body.appendChild(b);
        setTimeout(()=>b.remove(), 750);
      }
    };
    const onUp = ()=> setDown(false);
    addEventListener('mousedown', onDown);
    addEventListener('mouseup', onUp);
    return ()=>{
      cancelAnimationFrame(raf);
      removeEventListener('mousemove', onMove);
      removeEventListener('mouseover', onOver);
      removeEventListener('mousedown', onDown);
      removeEventListener('mouseup', onUp);
    };
  },[enabled]);

  if(!enabled) return null;
  return (
    <>
      <div ref={dotRef} className={`cur-dot ${down?'is-down':''} ${intro?'is-intro':''}`} />
      <div ref={ringRef} className={`cur-ring ${hover?'is-hover':''} ${down?'is-down':''} ${intro?'is-intro':''}`}>
        <svg className="cur-flecha" viewBox="0 0 24 24" aria-hidden="true">
          <path d="M12 4v14M5.5 12.5 12 19l6.5-6.5" fill="none" stroke="currentColor"
                strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        {!intro && label && <span className="cur-lbl">{label}</span>}
      </div>
    </>
  );
}

Object.assign(window, { useCart, useReveal, useScrollY, Cursor, PRODUCTS, PACK_QTY, MIN_QTY, PACK_PRICE });
