"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { Download } from "lucide-react";

interface Particle {
  x: number;
  y: number;
  z: number;
  vx: number;
  vy: number;
  baseSize: number;
  color: string;
  twinkleSpeed: number;
  twinklePhase: number;
}

const slides = [
  { image: "/banners/banner_2.png" },
  { image: "/banners/banner_1.png" },
  { image: "/banners/banner_3.png" },
];

const PARTICLE_COUNT = 50;
const AUTO_PLAY_MS = 6000;

export function HeroBanner({
  totalDownloads,
  launcherVersion,
}: {
  totalDownloads?: number;
  launcherVersion?: string | null;
}) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const particlesRef = useRef<Particle[]>([]);
  const rafRef = useRef(0);
  const [active, setActive] = useState(0);

  const createParticles = useCallback((w: number, h: number) => {
    const palettes = [
      "rgba(255,215,0,",
      "rgba(255,191,0,",
      "rgba(218,165,32,",
      "rgba(255,255,220,",
      "rgba(200,160,255,",
      "rgba(120,200,255,",
    ];
    const out: Particle[] = [];
    for (let i = 0; i < PARTICLE_COUNT; i++) {
      const z = Math.random();
      out.push({
        x: Math.random() * w,
        y: Math.random() * h,
        z,
        vx: (Math.random() - 0.5) * 0.3,
        vy: -(Math.random() * 0.3 + 0.05),
        baseSize: z * 2 + 0.6,
        color: palettes[Math.floor(Math.random() * palettes.length)],
        twinkleSpeed: Math.random() * 0.025 + 0.006,
        twinklePhase: Math.random() * Math.PI * 2,
      });
    }
    return out;
  }, []);

  useEffect(() => {
    const canvas = canvasRef.current;
    const container = containerRef.current;
    if (!canvas || !container) return;

    const ctx = canvas.getContext("2d")!;
    let w = 0;
    let h = 0;

    const resize = () => {
      const dpr = window.devicePixelRatio || 1;
      const rect = container.getBoundingClientRect();
      w = rect.width;
      h = rect.height;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      canvas.style.width = w + "px";
      canvas.style.height = h + "px";
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      if (particlesRef.current.length === 0) {
        particlesRef.current = createParticles(w, h);
      }
    };

    resize();
    window.addEventListener("resize", resize);

    let tick = 0;
    const loop = () => {
      ctx.clearRect(0, 0, w, h);
      tick++;

      for (const p of particlesRef.current) {
        p.x += p.vx;
        p.y += p.vy;
        if (p.y < -20) {
          p.y = h + 20;
          p.x = Math.random() * w;
        }
        if (p.x < -20) p.x = w + 20;
        if (p.x > w + 20) p.x = -20;

        const twinkle =
          Math.sin(tick * p.twinkleSpeed + p.twinklePhase) * 0.5 + 0.5;
        const alpha = (p.z * 0.45 + 0.1) * twinkle;
        const glowR = p.baseSize * 5;
        const grad = ctx.createRadialGradient(
          p.x,
          p.y,
          0,
          p.x,
          p.y,
          glowR
        );
        grad.addColorStop(0, p.color + (alpha * 0.4).toFixed(3) + ")");
        grad.addColorStop(1, p.color + "0)");
        ctx.fillStyle = grad;
        ctx.beginPath();
        ctx.arc(p.x, p.y, glowR, 0, Math.PI * 2);
        ctx.fill();

        ctx.fillStyle = p.color + alpha.toFixed(3) + ")";
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.baseSize, 0, Math.PI * 2);
        ctx.fill();
      }

      rafRef.current = requestAnimationFrame(loop);
    };
    loop();

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

  useEffect(() => {
    const id = setInterval(() => {
      setActive((prev) => (prev + 1) % slides.length);
    }, AUTO_PLAY_MS);
    return () => clearInterval(id);
  }, []);

  const goTo = (i: number) => setActive(i);

  const handleDownload = async () => {
    try {
      const res = await fetch("/api/software/latest?info=1");
      const data = await res.json();
      if (data.available && data.downloadUrl) {
        window.location.href = data.downloadUrl;
      } else {
        window.location.href = "/api/software/latest";
      }
    } catch {
      window.location.href = "/api/software/latest";
    }
  };

  return (
    <div className="hero-aurora-wrapper">
      <div className="hero-aurora hero-aurora--top" />

      <section
        ref={containerRef}
        className="relative overflow-hidden bg-[#0a0912]"
      >
        {/* Slide images */}
        {slides.map((s, i) => (
          <div
            key={i}
            className="absolute inset-0 transition-opacity duration-[1200ms] ease-in-out"
            style={{ opacity: i === active ? 1 : 0 }}
          >
            <img
              src={s.image}
              alt=""
              draggable={false}
              className="h-full w-full object-cover"
            />
          </div>
        ))}

        {/* Spacer to maintain 21:9 aspect ratio */}
        <div className="pointer-events-none w-full" style={{ paddingBottom: "min(42.86%, 720px)" }} />

        {/* Bottom gradient for button readability */}
        <div className="pointer-events-none absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0a0912] via-[#0a0912]/60 to-transparent" />

        {/* Particle canvas */}
        <canvas
          ref={canvasRef}
          className="pointer-events-none absolute inset-0 z-10"
        />

        {/* Bottom content */}
        <div className="absolute inset-x-0 bottom-0 z-20 flex flex-col items-center pb-6 sm:pb-8">
          <button
            onClick={handleDownload}
            className="group relative cursor-pointer overflow-hidden rounded-lg border border-amber-500/60 bg-gradient-to-b from-amber-900/80 to-amber-950/90 px-8 py-3.5 backdrop-blur transition-all duration-300 hover:border-amber-400/80 hover:shadow-[0_0_30px_rgba(255,191,0,0.3)] active:scale-[0.97]"
          >
            <div className="absolute inset-0 bg-gradient-to-r from-transparent via-amber-500/10 to-transparent opacity-0 transition-opacity duration-500 group-hover:opacity-100" />
            <span className="relative flex items-center gap-2.5 text-amber-100">
              <Download className="h-5 w-5" />
              <span className="text-base font-semibold tracking-wide">
                下载 Nanami 启动器
              </span>
              {launcherVersion && (
                <span className="rounded border border-amber-500/30 bg-amber-500/15 px-2 py-0.5 text-xs font-medium text-amber-300">
                  v{launcherVersion}
                </span>
              )}
            </span>
          </button>

          {totalDownloads != null && totalDownloads > 0 && (
            <p className="mt-2.5 text-sm text-white/40">
              累计{" "}
              <span className="font-semibold text-amber-300/70">
                {totalDownloads.toLocaleString()}
              </span>{" "}
              次下载
            </p>
          )}

          <div className="mt-3 flex gap-2.5">
            {slides.map((_, i) => (
              <button
                key={i}
                aria-label={`前往第 ${i + 1} 张`}
                onClick={() => goTo(i)}
                className={`cursor-pointer h-1.5 rounded-full transition-all duration-500 ${
                  i === active
                    ? "w-8 bg-amber-400"
                    : "w-1.5 bg-white/30 hover:bg-white/60"
                }`}
              />
            ))}
          </div>
        </div>
      </section>

      <div className="hero-aurora hero-aurora--bottom" />
    </div>
  );
}
