"use client";

import { useEffect, useRef, useState } from "react";
import { motion } from "framer-motion";
import CountUp from "react-countup";

/**
 * Shared visual-FX primitives for the premium service pages — floating
 * particles, mouse-tilt cards, an infinite tech belt, scroll-spy counters and
 * a browser/product mockup frame. Brand-strict (orange/gold on dark). Keep
 * positions deterministic so client+server markup match (no hydration drift).
 */

/* Fixed particle field — deterministic so SSR and client agree. */
const DOTS = [
  { left: "8%", top: "24%", s: 6, d: 0, dur: 7 },
  { left: "18%", top: "68%", s: 4, d: 1.2, dur: 8 },
  { left: "32%", top: "16%", s: 5, d: 0.6, dur: 6.5 },
  { left: "44%", top: "78%", s: 3, d: 1.8, dur: 9 },
  { left: "58%", top: "30%", s: 7, d: 0.3, dur: 7.5 },
  { left: "70%", top: "62%", s: 4, d: 1.5, dur: 8.5 },
  { left: "82%", top: "22%", s: 5, d: 0.9, dur: 6.8 },
  { left: "90%", top: "70%", s: 3, d: 2.1, dur: 9.5 },
  { left: "26%", top: "44%", s: 4, d: 1.1, dur: 7.2 },
  { left: "64%", top: "48%", s: 5, d: 0.4, dur: 8.1 },
];

export function Particles({ className = "" }) {
  return (
    <div aria-hidden="true" className={"pointer-events-none absolute inset-0 overflow-hidden " + className}>
      {DOTS.map((p, i) => (
        <motion.span
          key={i}
          className="absolute rounded-full bg-primary shadow-[0_0_12px_2px_rgb(var(--primary)/0.5)]"
          style={{ left: p.left, top: p.top, width: p.s, height: p.s }}
          animate={{ y: [0, -22, 0], opacity: [0.15, 0.7, 0.15] }}
          transition={{ duration: p.dur, delay: p.d, repeat: Infinity, ease: "easeInOut" }}
        />
      ))}
    </div>
  );
}

/* Slow-drifting aurora blobs — a living gradient backdrop for heroes. */
const BLOBS = [
  { c: "primary", left: "6%", top: "10%", size: "34rem", dx: 50, dy: -28, dur: 19 },
  { c: "accent", left: "60%", top: "2%", size: "30rem", dx: -58, dy: 40, dur: 23 },
  { c: "primary", left: "42%", top: "52%", size: "32rem", dx: 32, dy: 30, dur: 27 },
];

export function Aurora({ className = "" }) {
  return (
    <div aria-hidden="true" className={"pointer-events-none absolute inset-0 overflow-hidden " + className}>
      {BLOBS.map((b, i) => (
        <motion.div
          key={i}
          className="absolute rounded-full blur-[120px]"
          style={{
            left: b.left,
            top: b.top,
            width: b.size,
            height: b.size,
            background: `rgb(var(--${b.c}) / 0.14)`,
          }}
          animate={{ x: [0, b.dx, 0], y: [0, b.dy, 0], scale: [1, 1.18, 1] }}
          transition={{ duration: b.dur, repeat: Infinity, ease: "easeInOut" }}
        />
      ))}
    </div>
  );
}

/** Dot-field "wave" backdrop with soft top light beams (AI-agency hero look). */
export function WaveBackdrop({ className = "" }) {
  return (
    <div aria-hidden="true" className={"pointer-events-none absolute inset-0 overflow-hidden " + className}>
      {/* perspective dot field — fades in below a high horizon */}
      <div
        className="absolute inset-0"
        style={{
          backgroundImage: "radial-gradient(rgb(var(--foreground) / 0.18) 1px, transparent 1.5px)",
          backgroundSize: "24px 24px",
          maskImage: "radial-gradient(130% 100% at 50% -10%, transparent 38%, #000 78%)",
          WebkitMaskImage: "radial-gradient(130% 100% at 50% -10%, transparent 38%, #000 78%)",
        }}
      />
      {/* angled top light beams */}
      <div className="absolute -top-40 left-[22%] h-96 w-40 -rotate-[18deg] rounded-[50%] bg-foreground/[0.06] blur-3xl" />
      <div className="absolute -top-40 right-[26%] h-96 w-32 rotate-[18deg] rounded-[50%] bg-foreground/[0.05] blur-3xl" />
      {/* faint brand glow */}
      <div className="absolute left-1/2 top-1/4 h-72 w-[36rem] -translate-x-1/2 rounded-full bg-primary/10 blur-[140px]" />
    </div>
  );
}

/** Canvas dot-wave — a flowing field of dots (sine motion), brighter toward
   the bottom. The animated "wave" backdrop for heroes. */
export function DotWave({ className = "" }) {
  const ref = useRef(null);

  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    let raf = 0;
    let w = 0;
    let h = 0;

    const resize = () => {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      const rect = canvas.getBoundingClientRect();
      w = rect.width;
      h = rect.height;
      canvas.width = Math.max(1, Math.floor(w * dpr));
      canvas.height = Math.max(1, Math.floor(h * dpr));
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener("resize", resize);

    const gap = 26;
    const draw = (t) => {
      ctx.clearRect(0, 0, w, h);
      const time = t * 0.0011;
      for (let y = 0; y < h + gap; y += gap) {
        const depth = y / h; // 0 top → 1 bottom
        for (let x = 0; x < w + gap; x += gap) {
          const wave = Math.sin(x * 0.011 + time) + Math.sin(y * 0.02 + time * 0.7);
          const n = (wave + 2) / 4; // 0..1
          const radius = 0.5 + n * 1.7;
          const alpha = (0.05 + n * 0.5) * (0.12 + depth);
          ctx.beginPath();
          ctx.fillStyle = `rgba(245, 245, 246, ${alpha})`;
          ctx.arc(x, y + wave * 4, radius, 0, Math.PI * 2);
          ctx.fill();
        }
      }
      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, []);

  return (
    <canvas
      ref={ref}
      aria-hidden="true"
      className={"pointer-events-none absolute inset-0 h-full w-full " + className}
    />
  );
}

/** Subtle 3D mouse-tilt + glow-follow wrapper. */
export function TiltCard({ children, className = "", max = 6 }) {
  const [t, setT] = useState({ rx: 0, ry: 0, gx: "50%", gy: "50%", on: false });

  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    setT({
      rx: -py * max,
      ry: px * max,
      gx: `${((e.clientX - r.left) / r.width) * 100}%`,
      gy: `${((e.clientY - r.top) / r.height) * 100}%`,
      on: true,
    });
  };
  const reset = () => setT((s) => ({ ...s, rx: 0, ry: 0, on: false }));

  return (
    <div
      onMouseMove={onMove}
      onMouseLeave={reset}
      style={{
        transform: `perspective(900px) rotateX(${t.rx}deg) rotateY(${t.ry}deg)`,
        transition: "transform 0.25s ease-out",
      }}
      className={"relative " + className}
    >
      <span
        aria-hidden="true"
        className="pointer-events-none absolute inset-0 rounded-[inherit] opacity-0 transition-opacity duration-300"
        style={{
          opacity: t.on ? 1 : 0,
          background: `radial-gradient(20rem 20rem at ${t.gx} ${t.gy}, rgb(var(--primary) / 0.12), transparent 60%)`,
        }}
      />
      {children}
    </div>
  );
}

/** Infinite horizontal belt of items (uses the global marquee keyframes). */
export function TechBelt({ items, reverse = false }) {
  const row = [...items, ...items];
  return (
    <div className="relative overflow-hidden [mask-image:linear-gradient(90deg,transparent,#000_8%,#000_92%,transparent)]">
      <div className={"flex w-max gap-3 " + (reverse ? "animate-marquee-slow-rev" : "animate-marquee-slow")}>
        {row.map((item, i) => (
          <span
            key={i}
            className="flex items-center gap-2 rounded-full border border-border bg-surface/70 px-5 py-2.5 text-sm font-medium text-foreground/80 backdrop-blur"
          >
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            {item}
          </span>
        ))}
      </div>
    </div>
  );
}

/** Scroll-triggered animated number. */
export function Counter({ end, suffix = "", prefix = "", decimals = 0 }) {
  return (
    <CountUp
      end={end}
      suffix={suffix}
      prefix={prefix}
      decimals={decimals}
      duration={2.2}
      enableScrollSpy
      scrollSpyOnce
    />
  );
}

/** Phone mockup frame around any child (e.g. an app screenshot). */
export function PhoneFrame({ children, className = "" }) {
  return (
    <div className={"relative mx-auto w-full max-w-[14rem] " + className}>
      <div className="relative overflow-hidden rounded-[2rem] border-[7px] border-surface bg-surface shadow-2xl shadow-black/50">
        <div className="absolute left-1/2 top-2 z-10 h-5 w-20 -translate-x-1/2 rounded-full bg-background" />
        <div className="relative aspect-[9/19]">{children}</div>
      </div>
    </div>
  );
}

/** Browser/product mockup chrome around any child (e.g. a screenshot). */
export function BrowserFrame({ children, className = "" }) {
  return (
    <div className={"overflow-hidden rounded-2xl border border-border bg-surface shadow-2xl shadow-black/50 " + className}>
      <div className="flex items-center gap-1.5 border-b border-border bg-muted/80 px-4 py-3">
        <span className="h-3 w-3 rounded-full bg-foreground/20" />
        <span className="h-3 w-3 rounded-full bg-foreground/20" />
        <span className="h-3 w-3 rounded-full bg-foreground/20" />
        <span className="ml-3 hidden h-5 w-full max-w-[16rem] rounded-md bg-background/60 sm:block" />
      </div>
      <div className="relative">{children}</div>
    </div>
  );
}
