"use client";
// 回响星核 / Echo Nexus — 中央晶体集群 + 主动脉冲
import { useRef, useState, useCallback } from "react";
import { useGameStore } from "@/store/gameStore";
import { formatNum } from "@/lib/game/config";
import { useToast } from "@/hooks/use-toast";
import { sfx } from "@/hooks/useAudio";

interface FloatNum {
  id: number;
  x: number;
  y: number;
  text: string;
  born: number;
  color: string;
}

interface Particle {
  id: number;
  angle: number;
  dist: number;
  born: number;
  color: string;
}

export function CrystalOrb() {
  const pulse = useGameStore((s) => s.pulse);
  const crystals = useGameStore((s) => s.crystals);
  const crystalsPerSec = useGameStore((s) => s.crystalsPerSec);
  const crystalCap = useGameStore((s) => s.crystalCap);
  const combo = useGameStore((s) => s._combo);
  const { toast } = useToast();
  const [floats, setFloats] = useState<FloatNum[]>([]);
  const [particles, setParticles] = useState<Particle[]>([]);
  const [pulseAnim, setPulseAnim] = useState(0);
  const idRef = useRef(0);

  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLButtonElement>) => {
      const res = pulse();
      if (!res) return;
      const rect = e.currentTarget.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      const id = idRef.current++;
      const floatColor = res.combo >= 5 ? "#fbbf24" : res.combo >= 3 ? "#e879f9" : "#34d399";
      setFloats((f) => [
        ...f,
        { id, x, y, text: `+${res.gain.toFixed(1)}`, born: Date.now(), color: floatColor },
      ]);
      // 粒子爆发
      const newParticles: Particle[] = [];
      const pcount = 6 + Math.min(6, res.combo);
      for (let i = 0; i < pcount; i++) {
        newParticles.push({
          id: idRef.current++,
          angle: (Math.PI * 2 * i) / pcount + Math.random() * 0.3,
          dist: 0,
          born: Date.now(),
          color: floatColor,
        });
      }
      setParticles((p) => [...p, ...newParticles]);
      setPulseAnim((n) => n + 1);
      // 音效
      sfx(res.combo >= 3 ? "pulseCombo" : "pulse", { combo: res.combo });
      setTimeout(() => {
        setFloats((f) => f.filter((it) => it.id !== id));
      }, 900);
      setTimeout(() => {
        setParticles((p) => p.filter((it) => !newParticles.includes(it)));
      }, 700);
      if (res.combo >= 5 && res.combo % 5 === 0) {
        toast({
          title: `×${res.combo} 连击！`,
          description: "谐振叠加，产能飙升。",
        });
      }
    },
    [pulse, toast]
  );

  // 进度比例
  const fillPct = Math.min(100, (crystals / Math.max(1, crystalCap)) * 100);

  return (
    <div className="relative flex flex-col items-center justify-center gap-4 select-none">
      {/* 连击显示 */}
      {combo > 1 && (
        <div className="absolute -top-2 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full bg-rose-500/20 border border-rose-400/40 text-rose-200 text-xs font-mono animate-pulse">
          ×{combo} 连击
        </div>
      )}

      <button
        onClick={handleClick}
        className="relative h-52 w-52 sm:h-64 sm:w-64 rounded-full focus:outline-none group"
        aria-label="脉冲扫描，获取记忆晶体"
      >
        {/* 外层光晕 */}
        <div className="absolute inset-0 rounded-full bg-emerald-500/10 blur-2xl group-hover:bg-emerald-500/20 transition-colors" />
        {/* 旋转外环 */}
        <div
          className="absolute inset-2 rounded-full border border-emerald-400/30"
          style={{ animation: "echo-spin 18s linear infinite" }}
        >
          <div className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 h-2 w-2 rounded-full bg-emerald-300 shadow-[0_0_8px_#34d399]" />
          <div className="absolute bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2 h-1.5 w-1.5 rounded-full bg-rose-300 shadow-[0_0_8px_#fb7185]" />
        </div>
        {/* 反向旋转内环 */}
        <div
          className="absolute inset-6 rounded-full border border-fuchsia-400/20 border-dashed"
          style={{ animation: "echo-spin 24s linear infinite reverse" }}
        />
        {/* 进度填充环 */}
        <svg className="absolute inset-0 -rotate-90" viewBox="0 0 100 100">
          <circle
            cx="50"
            cy="50"
            r="44"
            fill="none"
            stroke="rgba(255,255,255,0.06)"
            strokeWidth="2"
          />
          <circle
            cx="50"
            cy="50"
            r="44"
            fill="none"
            stroke="url(#echoGrad)"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeDasharray={`${2 * Math.PI * 44}`}
            strokeDashoffset={`${2 * Math.PI * 44 * (1 - fillPct / 100)}`}
            style={{ transition: "stroke-dashoffset 0.3s ease", filter: "drop-shadow(0 0 4px rgba(52,211,153,0.6))" }}
          />
          <defs>
            <linearGradient id="echoGrad" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="#34d399" />
              <stop offset="50%" stopColor="#e879f9" />
              <stop offset="100%" stopColor="#fb7185" />
            </linearGradient>
          </defs>
        </svg>
        {/* 脉冲扩散环（点击时） */}
        <div
          key={`ring-${pulseAnim}`}
          className="absolute inset-8 rounded-full border-2 border-emerald-400/60 pointer-events-none"
          style={{ animation: "echo-ring 0.7s ease-out forwards" }}
        />
        {/* 中央晶体 */}
        <div
          key={pulseAnim}
          className="absolute inset-12 rounded-full flex items-center justify-center"
          style={{ animation: "echo-ping 0.4s ease-out" }}
        >
          <div className="relative h-full w-full">
            {/* 晶核 */}
            <div
              className="absolute inset-0 rounded-full"
              style={{
                background:
                  "radial-gradient(circle at 35% 30%, rgba(255,255,255,0.9), rgba(52,211,153,0.7) 35%, rgba(232,121,249,0.5) 70%, rgba(251,113,133,0.3))",
                boxShadow:
                  "0 0 30px rgba(52,211,153,0.6), 0 0 60px rgba(232,121,249,0.4), inset 0 0 20px rgba(255,255,255,0.3)",
              }}
            />
            {/* 高光 */}
            <div className="absolute top-3 left-6 h-6 w-10 rounded-full bg-white/40 blur-sm rotate-[-20deg]" />
            {/* 内部六边形纹理 */}
            <div
              className="absolute inset-4 rounded-full opacity-30"
              style={{
                backgroundImage:
                  "repeating-linear-gradient(60deg, rgba(255,255,255,0.4) 0 1px, transparent 1px 8px), repeating-linear-gradient(-60deg, rgba(255,255,255,0.4) 0 1px, transparent 1px 8px)",
              }}
            />
          </div>
        </div>
        {/* 粒子爆发 */}
        {particles.map((p) => (
          <span
            key={p.id}
            className="absolute left-1/2 top-1/2 rounded-full pointer-events-none"
            style={{
              width: 4,
              height: 4,
              background: p.color,
              boxShadow: `0 0 6px ${p.color}`,
              ["--angle" as string]: `${p.angle}rad`,
              animation: "echo-burst 0.7s ease-out forwards",
            }}
          />
        ))}
        {/* 浮动数字 */}
        {floats.map((f) => (
          <span
            key={f.id}
            className="absolute pointer-events-none font-mono font-bold text-sm"
            style={{
              left: f.x,
              top: f.y,
              color: f.color,
              transform: "translate(-50%, -50%)",
              animation: "echo-float 0.9s ease-out forwards",
              textShadow: `0 0 8px ${f.color}`,
            }}
          >
            {f.text}
          </span>
        ))}
      </button>

      {/* 数值显示 */}
      <div className="text-center">
        <div className="text-2xl font-mono font-bold text-emerald-300" style={{ textShadow: "0 0 12px rgba(52,211,153,0.5)" }}>
          {formatNum(crystals)}
        </div>
        <div className="text-xs text-muted-foreground mt-0.5">
          记忆晶体 · {crystalsPerSec.toFixed(1)}/s · 上限 {formatNum(crystalCap)}
        </div>
        <div className="text-[11px] text-muted-foreground/70 mt-2">
          点击晶体发起<span className="text-emerald-300">脉冲扫描</span>，连击叠加加成
        </div>
      </div>

      <style jsx>{`
        @keyframes echo-spin { to { transform: rotate(360deg); } }
        @keyframes echo-ping {
          0% { transform: scale(0.92); }
          50% { transform: scale(1.04); }
          100% { transform: scale(1); }
        }
        @keyframes echo-float {
          0% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
          100% { opacity: 0; transform: translate(-50%, -180%) scale(1.3); }
        }
        @keyframes echo-ring {
          0% { transform: scale(0.8); opacity: 0.8; }
          100% { transform: scale(1.6); opacity: 0; }
        }
        @keyframes echo-burst {
          0% {
            transform: translate(-50%, -50%) rotate(var(--angle)) translateX(0) rotate(calc(-1 * var(--angle)));
            opacity: 1;
          }
          100% {
            transform: translate(-50%, -50%) rotate(var(--angle)) translateX(80px) rotate(calc(-1 * var(--angle)));
            opacity: 0;
          }
        }
      `}</style>
    </div>
  );
}
