/* WASH BODEGA — Advanced Motion System
   Magnetic cursors, parallax layers, cinematic scroll choreography,
   morphing sparkles, liquid hover distortions */

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

/* =========== PARALLAX LAYER =========== */
/* Wraps children and shifts them on scroll at a given rate */
const Parallax = ({ children, speed = 0.15, className = "", style = {} }) => {
  const ref = useRef(null);
  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    let raf;
    const update = () => {
      const el = ref.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const center = rect.top + rect.height / 2;
      const viewCenter = window.innerHeight / 2;
      const offset = (center - viewCenter) * speed;
      el.style.transform = `translate3d(0, ${offset}px, 0)`;
      raf = requestAnimationFrame(update);
    };
    raf = requestAnimationFrame(update);
    return () => cancelAnimationFrame(raf);
  }, [speed]);
  return (
    <div ref={ref} className={className} style={{ willChange: 'transform', ...style }}>
      {children}
    </div>
  );
};

/* =========== MAGNETIC HOVER =========== */
/* Element gently pulls toward cursor on hover */
const Magnetic = ({ children, strength = 0.3, className = "", style = {} }) => {
  const ref = useRef(null);
  const onMove = useCallback((e) => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const cx = rect.left + rect.width / 2;
    const cy = rect.top + rect.height / 2;
    const dx = (e.clientX - cx) * strength;
    const dy = (e.clientY - cy) * strength;
    el.style.transform = `translate3d(${dx}px, ${dy}px, 0)`;
  }, [strength]);
  const onLeave = useCallback(() => {
    const el = ref.current;
    if (el) el.style.transform = 'translate3d(0, 0, 0)';
  }, []);
  return (
    <div
      ref={ref}
      className={className}
      style={{ transition: 'transform 400ms cubic-bezier(.2,.7,.2,1)', ...style }}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
    >
      {children}
    </div>
  );
};

/* =========== TILT 3D =========== */
/* Tilts element in 3D toward cursor, like a holographic card */
const Tilt3D = ({ children, intensity = 12, className = "", style = {} }) => {
  const ref = useRef(null);
  const onMove = useCallback((e) => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x = (e.clientX - rect.left) / rect.width - 0.5;
    const y = (e.clientY - rect.top) / rect.height - 0.5;
    el.style.transform = `perspective(800px) rotateY(${x * intensity}deg) rotateX(${-y * intensity}deg) scale3d(1.02, 1.02, 1.02)`;
  }, [intensity]);
  const onLeave = useCallback(() => {
    const el = ref.current;
    if (el) el.style.transform = 'perspective(800px) rotateY(0) rotateX(0) scale3d(1,1,1)';
  }, []);
  return (
    <div
      ref={ref}
      className={className}
      style={{ transition: 'transform 500ms cubic-bezier(.2,.7,.2,1)', transformStyle: 'preserve-3d', ...style }}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
    >
      {children}
    </div>
  );
};

/* =========== FLOATING SPARKLE FIELD =========== */
/* Animated sparkles that morph size + rotate */
const FloatingSparkles = ({ count = 6, area = { width: '100%', height: '100%' }, className = "" }) => {
  const sparkles = React.useMemo(() => {
    return Array.from({ length: count }, (_, i) => ({
      id: i,
      size: 10 + Math.random() * 18,
      left: `${5 + Math.random() * 90}%`,
      top: `${5 + Math.random() * 90}%`,
      delay: Math.random() * 4,
      dur: 3 + Math.random() * 5,
      color: Math.random() > 0.3 ? '#FFC627' : '#E5232B',
    }));
  }, [count]);
  return (
    <div className={className} style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      {sparkles.map(s => (
        <svg
          key={s.id}
          width={s.size} height={s.size}
          viewBox="0 0 24 24"
          style={{
            position: 'absolute',
            left: s.left,
            top: s.top,
            animation: `sparkle-morph ${s.dur}s ease-in-out ${s.delay}s infinite`,
            filter: `drop-shadow(0 0 ${s.size / 3}px ${s.color}40)`,
          }}
        >
          <path d="M12 2 L13.5 10.5 L22 12 L13.5 13.5 L12 22 L10.5 13.5 L2 12 L10.5 10.5 Z"
            fill={s.color} stroke="#5A2A12" strokeWidth="1" strokeLinejoin="round" />
        </svg>
      ))}
    </div>
  );
};

/* =========== SCROLL PROGRESS GLOW =========== */
/* A thin gradient line at top that shows scroll progress in brand colors */
const ScrollProgressGlow = () => {
  const ref = useRef(null);
  useEffect(() => {
    const update = () => {
      const el = ref.current;
      if (!el) return;
      const scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
      const progress = scrollHeight > 0 ? window.scrollY / scrollHeight : 0;
      el.style.transform = `scaleX(${progress})`;
    };
    window.addEventListener('scroll', update, { passive: true });
    update();
    return () => window.removeEventListener('scroll', update);
  }, []);
  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0, height: 3, zIndex: 200,
      background: 'linear-gradient(90deg, #E5232B, #FFC627, #E5232B)',
      transformOrigin: 'left',
      transform: 'scaleX(0)',
      boxShadow: '0 0 12px rgba(229,35,43,0.5), 0 0 24px rgba(255,198,39,0.3)',
    }} ref={ref} />
  );
};

/* =========== CURSOR GLOW =========== */
/* A subtle warm glow that follows the cursor */
const CursorGlow = () => {
  const ref = useRef(null);
  useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if ('ontouchstart' in window) return; // skip on mobile
    const el = ref.current;
    let x = 0, y = 0, tx = 0, ty = 0;
    const onMove = (e) => { tx = e.clientX; ty = e.clientY; };
    const animate = () => {
      x += (tx - x) * 0.08;
      y += (ty - y) * 0.08;
      if (el) el.style.transform = `translate(${x - 200}px, ${y - 200}px)`;
      requestAnimationFrame(animate);
    };
    window.addEventListener('mousemove', onMove, { passive: true });
    requestAnimationFrame(animate);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return (
    <div ref={ref} style={{
      position: 'fixed', top: 0, left: 0,
      width: 400, height: 400,
      borderRadius: '50%',
      background: 'radial-gradient(circle, rgba(255,198,39,0.06) 0%, rgba(229,35,43,0.03) 40%, transparent 70%)',
      pointerEvents: 'none',
      zIndex: 1,
      mixBlendMode: 'screen',
    }} />
  );
};

/* =========== MORPH TEXT (letter stagger on reveal) =========== */
const StaggerText = ({ text, className = "", staggerMs = 30 }) => {
  const [visible, setVisible] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight) { setVisible(true); return; }
    const io = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting) { setVisible(true); io.disconnect(); }
    }, { threshold: 0.3 });
    io.observe(el);
    const t = setTimeout(() => setVisible(true), 1500);
    return () => { io.disconnect(); clearTimeout(t); };
  }, []);
  return (
    <span ref={ref} className={className} aria-label={text}>
      {text.split('').map((ch, i) => (
        <span
          key={i}
          style={{
            display: 'inline-block',
            opacity: visible ? 1 : 0,
            transform: visible ? 'translateY(0) rotateX(0)' : 'translateY(40px) rotateX(-60deg)',
            transition: `all 600ms cubic-bezier(.2,.7,.2,1) ${i * staggerMs}ms`,
            transformOrigin: 'bottom center',
          }}
          aria-hidden="true"
        >
          {ch === ' ' ? '\u00A0' : ch}
        </span>
      ))}
    </span>
  );
};

/* =========== LIQUID MORPH BLOB (ambient background element) =========== */
const LiquidBlob = ({ color = 'rgba(229,35,43,0.06)', size = 500, className = "", style = {} }) => (
  <div
    className={className}
    style={{
      position: 'absolute',
      width: size, height: size,
      borderRadius: '40% 60% 70% 30% / 40% 50% 60% 50%',
      background: `radial-gradient(circle, ${color}, transparent 70%)`,
      animation: 'blob-morph 12s ease-in-out infinite',
      filter: 'blur(40px)',
      pointerEvents: 'none',
      ...style,
    }}
  />
);

Object.assign(window, {
  Parallax, Magnetic, Tilt3D, FloatingSparkles,
  ScrollProgressGlow, CursorGlow, StaggerText, LiquidBlob,
});
