// agilEspresso v2 — Primitives: Cursor, Grain, Nav, Marquee, Scroll-reveal hook

const { useState: useS2, useEffect: useE2, useRef: useR2 } = React;

// ===== Magnetic cursor =====
function V2Cursor() {
  const dotRef = useR2(null);
  const ringRef = useR2(null);
  const [hover, setHover] = useS2(false);

  useE2(() => {
    let mx = window.innerWidth / 2, my = window.innerHeight / 2;
    let rx = mx, ry = my;
    const onMove = (e) => { mx = e.clientX; my = e.clientY; if (dotRef.current) { dotRef.current.style.transform = `translate(${mx}px, ${my}px) translate(-50%, -50%)`; } };
    const anim = () => {
      rx += (mx - rx) * 0.15;
      ry += (my - ry) * 0.15;
      if (ringRef.current) ringRef.current.style.transform = `translate(${rx}px, ${ry}px) translate(-50%, -50%)`;
      requestAnimationFrame(anim);
    };
    anim();
    window.addEventListener('mousemove', onMove);
    const onEnter = (e) => { if (e.target.closest('a, button, [data-cursor="hover"]')) setHover(true); };
    const onLeave = (e) => { if (e.target.closest && e.target.closest('a, button, [data-cursor="hover"]')) setHover(false); };
    document.addEventListener('mouseover', onEnter);
    document.addEventListener('mouseout', onLeave);
    return () => {
      window.removeEventListener('mousemove', onMove);
      document.removeEventListener('mouseover', onEnter);
      document.removeEventListener('mouseout', onLeave);
    };
  }, []);

  return (
    <>
      <div ref={dotRef} className={`v2-cursor ${hover ? 'hover' : ''}`} aria-hidden="true" />
      <div ref={ringRef} className={`v2-cursor-ring ${hover ? 'hide' : ''}`} aria-hidden="true" />
    </>
  );
}

// ===== Grain overlay =====
function V2Grain() {
  return (
    <svg className="v2-grain" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <filter id="v2n">
        <feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" stitchTiles="stitch" />
        <feColorMatrix values="0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.5 0" />
      </filter>
      <rect width="100%" height="100%" filter="url(#v2n)" />
    </svg>
  );
}

// ===== Scroll reveal hook =====
function useV2Reveal(ref) {
  useE2(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12 });
    const all = el.querySelectorAll ? [el, ...el.querySelectorAll('.v2-reveal')] : [el];
    all.forEach(x => x.classList && x.classList.contains && x.classList.contains('v2-reveal') && io.observe(x));
    return () => io.disconnect();
  }, [ref]);
}

// ===== Nav =====
function V2Nav({ scrollProgress }) {
  return (
    <>
      <div className="v2-progress" style={{ transform: `scaleX(${scrollProgress})` }} />
      <nav className="v2-nav">
        <a href="#top" className="v2-logo">
          <span className="v2-logo-dot" />
          agilEspresso
        </a>
        <div className="v2-nav-links">
          <a href="#shots">shots</a>
          <a href="#maturity">olgunluk</a>
          <a href="#manifesto">manifesto</a>
          <a href="#archive">arşiv</a>
        </div>
        <a href="#subscribe" className="v2-nav-cta">
          abone ol
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2 6h8m-3-3l3 3-3 3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
      </nav>
    </>
  );
}

// ===== Marquee =====
function V2Marquee({ items }) {
  const doubled = [...items, ...items, ...items, ...items];
  return (
    <div className="v2-marquee" aria-hidden="true">
      <div className="v2-marquee-track">
        {doubled.map((it, i) => <span key={i}>{it}</span>)}
      </div>
    </div>
  );
}

// ===== Animated Cup (hero right) =====
function V2Cup() {
  const stageRef = useR2(null);
  useE2(() => {
    const onScroll = () => {
      if (!stageRef.current) return;
      const y = window.scrollY;
      stageRef.current.style.transform = `translateY(${y * 0.15}px) rotate(${y * 0.02}deg)`;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <div className="v2-cup-stage" ref={stageRef}>
      <div className="v2-cup-orbit" />
      <div className="v2-cup-orbit-2" />
      <span className="v2-cup-label v2-cup-label-top">espresso double</span>
      <span className="v2-cup-label v2-cup-label-right">agile</span>
      <span className="v2-cup-label v2-cup-label-bottom">~60sn okuma</span>
      <span className="v2-cup-label v2-cup-label-left">ai</span>
      <svg viewBox="0 0 400 400" className="v2-cup-svg">
        <defs>
          <radialGradient id="v2crema" cx="40%" cy="38%" r="65%">
            <stop offset="0%" stopColor="#d99968" />
            <stop offset="50%" stopColor="#8a4618" />
            <stop offset="100%" stopColor="#2b1108" />
          </radialGradient>
          <radialGradient id="v2rim" cx="50%" cy="22%" r="75%">
            <stop offset="0%" stopColor="rgba(255,255,255,0.35)" />
            <stop offset="50%" stopColor="rgba(255,255,255,0.02)" />
            <stop offset="100%" stopColor="rgba(0,0,0,0.5)" />
          </radialGradient>
        </defs>
        {/* saucer */}
        <circle cx="200" cy="200" r="180" fill="#1a1714" stroke="rgba(245,240,232,0.1)" strokeWidth="1" />
        <circle cx="200" cy="200" r="160" fill="none" stroke="rgba(245,240,232,0.06)" strokeWidth="1" />
        {/* cup rim */}
        <circle cx="200" cy="200" r="140" fill="#0a0907" />
        <circle cx="200" cy="200" r="138" fill="none" stroke="rgba(245,240,232,0.2)" strokeWidth="1" />
        {/* crema */}
        <circle cx="200" cy="200" r="132" fill="url(#v2crema)" />
        {/* rim lighting */}
        <circle cx="200" cy="200" r="132" fill="url(#v2rim)" />
        {/* crema highlight */}
        <ellipse cx="165" cy="155" rx="50" ry="22" fill="rgba(255,235,200,0.25)" />
        {/* latte-art swirl */}
        <path d="M 80 200 Q 150 160, 200 200 T 320 200" fill="none" stroke="rgba(255,220,180,0.35)" strokeWidth="2" />
        <path d="M 100 230 Q 160 250, 200 230 T 300 230" fill="none" stroke="rgba(255,220,180,0.2)" strokeWidth="1.5" />
        {/* bubbles */}
        {[
          [160, 180, 3], [220, 195, 2.5], [185, 225, 3.5], [240, 170, 2], [130, 215, 2.5],
          [260, 220, 2], [175, 160, 1.8], [215, 245, 2.2]
        ].map(([x, y, r], i) => (
          <circle key={i} cx={x} cy={y} r={r} fill="rgba(255,230,200,0.4)" />
        ))}
        {/* steam */}
        <g opacity="0.5">
          <path d="M 170 60 Q 180 40, 170 20" fill="none" stroke="#ff7a3d" strokeWidth="1.5" strokeLinecap="round" opacity="0.6">
            <animate attributeName="opacity" values="0.2;0.8;0.2" dur="3s" repeatCount="indefinite" />
          </path>
          <path d="M 200 60 Q 210 40, 200 20" fill="none" stroke="#ff7a3d" strokeWidth="1.5" strokeLinecap="round" opacity="0.6">
            <animate attributeName="opacity" values="0.4;0.9;0.4" dur="3s" begin="0.5s" repeatCount="indefinite" />
          </path>
          <path d="M 230 60 Q 240 40, 230 20" fill="none" stroke="#ff7a3d" strokeWidth="1.5" strokeLinecap="round" opacity="0.6">
            <animate attributeName="opacity" values="0.2;0.8;0.2" dur="3s" begin="1s" repeatCount="indefinite" />
          </path>
        </g>
      </svg>
    </div>
  );
}

// Expose for sections
Object.assign(window, { V2Cursor, V2Grain, V2Nav, V2Marquee, V2Cup, useV2Reveal });
