// FENIX - Visual Effects layer
const { useState: useStateFx, useEffect: useEffectFx, useRef: useRefFx } = React;

// ─── Custom cursor ────────────────────────────────────────────
window.CustomCursor = function CustomCursor({ accent }) {
  const ringRef = useRefFx(null);
  const dotRef = useRefFx(null);
  const [hover, setHover] = useStateFx(false);

  useEffectFx(() => {
    let rx = window.innerWidth / 2, ry = window.innerHeight / 2;
    let dx = rx, dy = ry;
    let mx = rx, my = ry;
    let raf;

    const onMove = (e) => { mx = e.clientX; my = e.clientY; };
    const onOver = (e) => {
      const t = e.target;
      if (t.closest && t.closest('a, button, [role="button"], input, textarea, .group')) {
        setHover(true);
      } else setHover(false);
    };

    const tick = () => {
      rx += (mx - rx) * 0.18;
      ry += (my - ry) * 0.18;
      dx += (mx - dx) * 0.5;
      dy += (my - dy) * 0.5;
      if (ringRef.current) ringRef.current.style.transform = `translate3d(${rx}px, ${ry}px, 0) translate(-50%, -50%)`;
      if (dotRef.current) dotRef.current.style.transform = `translate3d(${dx}px, ${dy}px, 0) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    tick();

    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseover', onOver);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseover', onOver);
    };
  }, []);

  return (
    <>
      <div
        ref={ringRef}
        className="fixed top-0 left-0 pointer-events-none z-[9999] hidden md:block"
        style={{
          width: hover ? 56 : 32,
          height: hover ? 56 : 32,
          border: `1.5px solid ${accent}`,
          borderRadius: '50%',
          transition: 'width 0.25s, height 0.25s, background 0.25s',
          background: hover ? `${accent}22` : 'transparent',
          mixBlendMode: 'difference',
        }}
      />
      <div
        ref={dotRef}
        className="fixed top-0 left-0 pointer-events-none z-[9999] hidden md:block"
        style={{
          width: 5, height: 5,
          background: accent,
          borderRadius: '50%',
        }}
      />
      <style>{`@media (hover: hover) and (pointer: fine) { body, a, button { cursor: none !important; } }`}</style>
    </>
  );
};

// ─── Reveal on scroll ─────────────────────────────────────────
window.Reveal = function Reveal({ children, delay = 0, y = 24, as: Tag = "div", className = "" }) {
  const ref = useRefFx(null);
  const [show, setShow] = useStateFx(false);
  useEffectFx(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setShow(true); io.disconnect(); }
    }, { threshold: 0.12 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <Tag
      ref={ref}
      className={className}
      style={{
        opacity: show ? 1 : 0,
        transform: show ? 'translate3d(0,0,0)' : `translate3d(0, ${y}px, 0)`,
        transition: `opacity 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) ${delay}ms, transform 0.9s cubic-bezier(0.2, 0.7, 0.2, 1) ${delay}ms`,
        willChange: 'transform, opacity',
      }}
    >
      {children}
    </Tag>
  );
};

// ─── Counter (animates when in view) ─────────────────────────
window.Counter = function Counter({ to, duration = 1600, suffix = "", prefix = "", decimals = 0 }) {
  const ref = useRefFx(null);
  const [val, setVal] = useStateFx(0);
  useEffectFx(() => {
    if (!ref.current) return;
    let started = false;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !started) {
        started = true;
        const start = performance.now();
        const tick = (t) => {
          const p = Math.min(1, (t - start) / duration);
          const eased = 1 - Math.pow(1 - p, 3);
          setVal(eased * to);
          if (p < 1) requestAnimationFrame(tick);
        };
        requestAnimationFrame(tick);
      }
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [to]);
  return <span ref={ref}>{prefix}{val.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}{suffix}</span>;
};

// ─── Magnetic button ─────────────────────────────────────────
window.Magnetic = function Magnetic({ children, strength = 0.35, className = "", style = {}, ...rest }) {
  const ref = useRefFx(null);
  useEffectFx(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const x = (e.clientX - (r.left + r.width / 2)) * strength;
      const y = (e.clientY - (r.top + r.height / 2)) * strength;
      el.style.transform = `translate3d(${x}px, ${y}px, 0)`;
    };
    const onLeave = () => { el.style.transform = `translate3d(0,0,0)`; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, [strength]);
  return (
    <div ref={ref} className={className} style={{ transition: 'transform 0.4s cubic-bezier(0.2, 0.7, 0.2, 1)', display: 'inline-block', ...style }} {...rest}>
      {children}
    </div>
  );
};

// ─── Tilt card ───────────────────────────────────────────────
window.TiltCard = function TiltCard({ children, max = 8, className = "" }) {
  const ref = useRefFx(null);
  useEffectFx(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const px = (e.clientX - r.left) / r.width - 0.5;
      const py = (e.clientY - r.top) / r.height - 0.5;
      el.style.transform = `perspective(900px) rotateX(${-py * max}deg) rotateY(${px * max}deg) scale(1.02)`;
      const glare = el.querySelector('[data-glare]');
      if (glare) {
        glare.style.background = `radial-gradient(circle at ${(px + 0.5) * 100}% ${(py + 0.5) * 100}%, rgba(255,255,255,0.18), transparent 50%)`;
      }
    };
    const onLeave = () => {
      el.style.transform = `perspective(900px) rotateX(0deg) rotateY(0deg) scale(1)`;
      const glare = el.querySelector('[data-glare]');
      if (glare) glare.style.background = 'transparent';
    };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
    };
  }, [max]);
  return (
    <div ref={ref} className={className} style={{ transition: 'transform 0.35s cubic-bezier(0.2, 0.7, 0.2, 1)', transformStyle: 'preserve-3d', willChange: 'transform' }}>
      {children}
      <div data-glare className="absolute inset-0 pointer-events-none" style={{ transition: 'background 0.2s' }} />
    </div>
  );
};

// ─── Scramble Text ───────────────────────────────────────────
window.Scramble = function Scramble({ text, className = "", duration = 900, trigger = "view" }) {
  const ref = useRefFx(null);
  const [out, setOut] = useStateFx(text);
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*";
  useEffectFx(() => {
    if (!ref.current) return;
    let started = false;
    const run = () => {
      if (started) return;
      started = true;
      const start = performance.now();
      const tick = (t) => {
        const p = Math.min(1, (t - start) / duration);
        const reveal = Math.floor(p * text.length);
        let s = "";
        for (let i = 0; i < text.length; i++) {
          if (i < reveal || text[i] === ' ') s += text[i];
          else s += chars[Math.floor(Math.random() * chars.length)];
        }
        setOut(s);
        if (p < 1) requestAnimationFrame(tick);
        else setOut(text);
      };
      requestAnimationFrame(tick);
    };
    if (trigger === "view") {
      const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) run(); }, { threshold: 0.5 });
      io.observe(ref.current);
      return () => io.disconnect();
    } else if (trigger === "hover") {
      const el = ref.current;
      el.addEventListener('mouseenter', () => { started = false; run(); });
    }
  }, [text]);
  return <span ref={ref} className={className}>{out}</span>;
};

// ─── Parallax wrapper ────────────────────────────────────────
window.Parallax = function Parallax({ children, speed = 0.3, className = "" }) {
  const ref = useRefFx(null);
  useEffectFx(() => {
    const el = ref.current;
    if (!el) return;
    let raf;
    const tick = () => {
      const r = el.getBoundingClientRect();
      const center = r.top + r.height / 2 - window.innerHeight / 2;
      el.style.transform = `translate3d(0, ${-center * speed}px, 0)`;
      raf = requestAnimationFrame(tick);
    };
    tick();
    return () => cancelAnimationFrame(raf);
  }, [speed]);
  return <div ref={ref} className={className} style={{ willChange: 'transform' }}>{children}</div>;
};

// ─── Grain overlay ───────────────────────────────────────────
window.Grain = function Grain() {
  return (
    <div
      className="fixed inset-0 pointer-events-none z-[9000] opacity-[0.06] mix-blend-overlay"
      style={{
        backgroundImage:
          "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='200'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>\")",
        backgroundSize: "200px 200px",
        animation: "grain 0.5s steps(2) infinite",
      }}
    />
  );
};

// ─── Scroll progress bar ─────────────────────────────────────
window.ScrollProgress = function ScrollProgress({ accent }) {
  const [p, setP] = useStateFx(0);
  useEffectFx(() => {
    const onScroll = () => {
      const max = document.documentElement.scrollHeight - window.innerHeight;
      setP(Math.max(0, Math.min(1, window.scrollY / max)));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div className="fixed top-0 left-0 right-0 z-[9100] h-[2px] bg-white/5">
      <div className="h-full transition-[width] duration-100" style={{ width: `${p * 100}%`, background: accent, boxShadow: `0 0 12px ${accent}` }} />
    </div>
  );
};

// Global animations CSS
(function injectFxStyles() {
  if (document.getElementById('fenix-fx-styles')) return;
  const s = document.createElement('style');
  s.id = 'fenix-fx-styles';
  s.textContent = `
    @keyframes grain {
      0%, 100% { transform: translate(0, 0); }
      10% { transform: translate(-5%, -10%); }
      30% { transform: translate(3%, -15%); }
      50% { transform: translate(12%, 9%); }
      70% { transform: translate(9%, 4%); }
      90% { transform: translate(-1%, 7%); }
    }
    @keyframes glitch-1 {
      0%, 92%, 100% { transform: translate(0); }
      93% { transform: translate(-2px, 1px); }
      94% { transform: translate(2px, -1px); }
      95% { transform: translate(-1px, 2px); }
      96% { transform: translate(1px, 0); }
    }
    @keyframes shine {
      0% { transform: translateX(-150%) skewX(-20deg); }
      100% { transform: translateX(250%) skewX(-20deg); }
    }
    .glitch-hover:hover { animation: glitch-1 0.6s steps(2) 1; }
    .shine-btn { position: relative; overflow: hidden; }
    .shine-btn::before {
      content: '';
      position: absolute;
      top: 0; left: 0; bottom: 0;
      width: 40%;
      background: linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent);
      transform: translateX(-150%) skewX(-20deg);
      pointer-events: none;
    }
    .shine-btn:hover::before { animation: shine 0.9s ease-out; }
    @keyframes float {
      0%, 100% { transform: translateY(0); }
      50% { transform: translateY(-8px); }
    }
    .float-y { animation: float 4s ease-in-out infinite; }
    @keyframes pulse-ring {
      0% { transform: scale(0.95); opacity: 1; }
      100% { transform: scale(1.6); opacity: 0; }
    }
    .pulse-ring::after {
      content: '';
      position: absolute;
      inset: 0;
      border: 2px solid currentColor;
      border-radius: inherit;
      animation: pulse-ring 1.6s cubic-bezier(0.2, 0.7, 0.2, 1) infinite;
    }
  `;
  document.head.appendChild(s);
})();
