// Ninja flair — shuriken dividers, peeking mask mascot, cursor trail
const { useEffect: useEffectN, useState: useStateN, useRef: useRefN } = React;

// ————————————————————————————————————————————————————————————
// Shuriken divider: flies across, leaves a slash cut
// ————————————————————————————————————————————————————————————
function ShurikenDivider({ direction = "left-to-right", variant = "normal" }) {
  const ref = useRefN(null);
  const [visible, setVisible] = useStateN(false);

  useEffectN(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) setVisible(true); },
      { threshold: 0.5 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  return (
    <div ref={ref} className={`shur-divider ${visible ? "is-visible" : ""} ${direction}`}>
      <div className="shur-divider-line" />
      <div className="shur-divider-star">
        <svg width="36" height="36" viewBox="0 0 60 60" aria-hidden>
          <g fill="var(--accent)" stroke="var(--ink)" strokeWidth="2" strokeLinejoin="round">
            <path d="M30 4 L36 24 L56 30 L36 36 L30 56 L24 36 L4 30 L24 24 Z" />
          </g>
          <circle cx="30" cy="30" r="4" fill="var(--paper)" stroke="var(--ink)" strokeWidth="2" />
        </svg>
      </div>
      <div className="shur-divider-slash" />
    </div>
  );
}

// ————————————————————————————————————————————————————————————
// Peeking mask mascot — sits in corner, blinks, follows scroll
// ————————————————————————————————————————————————————————————
function PeekingMask() {
  const [peek, setPeek] = useStateN(0); // 0 hidden, 1..4 positions
  const [blink, setBlink] = useStateN(false);
  const [eyeDir, setEyeDir] = useStateN({ x: 0, y: 0 });

  // rotate peek position through the page as user scrolls
  useEffectN(() => {
    const onScroll = () => {
      const y = window.scrollY;
      const total = document.body.scrollHeight - window.innerHeight;
      const pct = y / Math.max(total, 1);
      if (pct < 0.15) setPeek(0);
      else if (pct < 0.4) setPeek(1);
      else if (pct < 0.65) setPeek(2);
      else if (pct < 0.9) setPeek(3);
      else setPeek(4);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // blink periodically
  useEffectN(() => {
    const id = setInterval(() => {
      setBlink(true);
      setTimeout(() => setBlink(false), 160);
    }, 3500 + Math.random() * 2000);
    return () => clearInterval(id);
  }, []);

  // eye tracking
  useEffectN(() => {
    const onMove = (e) => {
      const el = document.querySelector(".peek-mask");
      if (!el) return;
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const d = Math.hypot(dx, dy) || 1;
      const max = 3;
      setEyeDir({ x: (dx / d) * max, y: (dy / d) * max });
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  if (peek === 0) return null;

  const positionClass = `peek-${peek}`;

  return (
    <div className={`peek-mask ${positionClass}`}>
      <svg viewBox="0 0 140 140" aria-hidden>
        <g className="peek-body">
          {/* Head — rounded, flesh-tone */}
          <ellipse cx="70" cy="78" rx="44" ry="46" fill="#e8c9a8" />
          {/* Neck */}
          <rect x="58" y="118" width="24" height="18" fill="#d9b896" />
          {/* Top of head covered by wrap */}
          <path
            d="M 26 62
               Q 26 32, 70 32
               Q 114 32, 114 62
               L 114 70
               Q 70 58, 26 70 Z"
            fill="var(--ink)"
          />
          {/* Wrap band across eyes */}
          <rect x="22" y="60" width="96" height="26" fill="var(--ink)" />
          {/* Wrap cut under chin (lower covering) */}
          <path
            d="M 26 96
               Q 26 126, 70 126
               Q 114 126, 114 96
               L 114 90
               Q 70 102, 26 90 Z"
            fill="var(--ink)"
          />
          {/* Tie ends flapping behind */}
          <path d="M 110 68 L 136 58 L 130 82 L 110 82 Z" fill="var(--ink)" className="peek-tie" />
          <path d="M 110 82 L 138 92 L 128 104 L 108 94 Z" fill="var(--ink-70)" className="peek-tie-2" />
          {/* Narrow eye slit */}
          <rect x="38" y="68" width="64" height="10" rx="5" fill="#e8c9a8" />
          {/* Eyes — focused, slightly narrowed */}
          {!blink ? (
            <>
              <ellipse cx={54 + eyeDir.x * 0.8} cy={73 + eyeDir.y * 0.3} rx="2.6" ry="3" fill="var(--ink)" />
              <ellipse cx={86 + eyeDir.x * 0.8} cy={73 + eyeDir.y * 0.3} rx="2.6" ry="3" fill="var(--ink)" />
              {/* tiny catchlights */}
              <circle cx={55 + eyeDir.x * 0.8} cy={72 + eyeDir.y * 0.3} r="0.7" fill="#fff" />
              <circle cx={87 + eyeDir.x * 0.8} cy={72 + eyeDir.y * 0.3} r="0.7" fill="#fff" />
            </>
          ) : (
            <>
              <line x1="50" y1="73" x2="58" y2="73" stroke="var(--ink)" strokeWidth="2.2" strokeLinecap="round" />
              <line x1="82" y1="73" x2="90" y2="73" stroke="var(--ink)" strokeWidth="2.2" strokeLinecap="round" />
            </>
          )}
          {/* Eyebrow furrow — determined look */}
          <path d="M 46 64 L 60 67" stroke="#3a2b1a" strokeWidth="2" strokeLinecap="round" opacity="0.8" />
          <path d="M 80 67 L 94 64" stroke="#3a2b1a" strokeWidth="2" strokeLinecap="round" opacity="0.8" />
        </g>
        {/* motion streaks */}
        <g className="peek-streaks">
          <line x1="0" y1="50" x2="14" y2="50" stroke="var(--ink-30)" strokeWidth="2" strokeLinecap="round" />
          <line x1="0" y1="78" x2="10" y2="78" stroke="var(--ink-30)" strokeWidth="2" strokeLinecap="round" />
          <line x1="0" y1="106" x2="16" y2="106" stroke="var(--ink-30)" strokeWidth="2" strokeLinecap="round" />
        </g>
      </svg>
    </div>
  );
}

// ————————————————————————————————————————————————————————————
// Cursor trail — tiny shurikens fade behind cursor
// ————————————————————————————————————————————————————————————
function CursorTrail() {
  const layerRef = useRefN(null);
  const lastRef = useRefN({ x: 0, y: 0, t: 0 });

  useEffectN(() => {
    const layer = layerRef.current;
    if (!layer) return;
    // skip on touch / small screens
    if (matchMedia("(pointer: coarse)").matches || window.innerWidth < 900) return;

    const onMove = (e) => {
      const now = performance.now();
      const last = lastRef.current;
      const dx = e.clientX - last.x;
      const dy = e.clientY - last.y;
      const dist = Math.hypot(dx, dy);
      if (dist < 60 || now - last.t < 80) return;
      lastRef.current = { x: e.clientX, y: e.clientY, t: now };

      const star = document.createElement("div");
      star.className = "cursor-star";
      star.style.left = e.clientX + "px";
      star.style.top  = e.clientY + "px";
      star.style.transform = `translate(-50%, -50%) rotate(${Math.random() * 360}deg)`;
      star.innerHTML = `<svg viewBox="0 0 20 20"><path d="M10 1 L12 8 L19 10 L12 12 L10 19 L8 12 L1 10 L8 8 Z" fill="var(--accent)" stroke="var(--ink)" stroke-width="1" stroke-linejoin="round"/></svg>`;
      layer.appendChild(star);
      setTimeout(() => star.remove(), 700);
    };
    window.addEventListener("mousemove", onMove);
    return () => window.removeEventListener("mousemove", onMove);
  }, []);

  return <div ref={layerRef} className="cursor-trail-layer" aria-hidden />;
}

Object.assign(window, { ShurikenDivider, PeekingMask, CursorTrail });
