"use client";
// 回响星核 / Echo Nexus — 星图天赋选择对话框（飞升后弹出，3 选 1）
import { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useGameStore } from "@/store/gameStore";
import {
  getPerk,
  CONSTELLATION_CATEGORY_META,
  constellationProgress,
} from "@/lib/game/constellation";
import { sfx } from "@/hooks/useAudio";
import { Sparkles, RefreshCw } from "lucide-react";

interface Props {
  open: boolean;
  onOpenChange: (v: boolean) => void;
}

export function ConstellationDialog({ open, onOpenChange }: Props) {
  const pendingChoices = useGameStore((s) => s.pendingPerkChoices);
  const constellation = useGameStore((s) => s.constellation ?? []);
  const choosePerk = useGameStore((s) => s.chooseConstellationPerk);
  const reroll = useGameStore((s) => s.rerollPerkChoices);
  const [picked, setPicked] = useState<string | null>(null);

  // 关闭时清理本地状态
  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    if (!open) setPicked(null);
  }, [open]);

  // 自动 open：当 pendingPerkChoices 存在且当前未 open 时
  useEffect(() => {
    if (pendingChoices && pendingChoices.length > 0 && !open) {
      onOpenChange(true);
    }
    if ((!pendingChoices || pendingChoices.length === 0) && open) {
      onOpenChange(false);
    }
  }, [pendingChoices, open, onOpenChange]);

  const handlePick = (perkId: string) => {
    setPicked(perkId);
    const ok = choosePerk(perkId);
    if (ok) {
      sfx("constellation");
      // 延迟关闭，让选中动画播放
      setTimeout(() => onOpenChange(false), 500);
    }
  };

  const handleReroll = () => {
    reroll();
    sfx("uiClick");
  };

  if (!pendingChoices || pendingChoices.length === 0) return null;

  const progress = constellationProgress(constellation);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md border-fuchsia-400/30 bg-gradient-to-br from-[#0a0820]/95 to-[#1a0f30]/95 backdrop-blur-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-fuchsia-200">
            <Sparkles className="h-4 w-4" />
            星图觉醒
          </DialogTitle>
          <DialogDescription className="text-muted-foreground text-xs">
            飞升带来的回响在星图上凝聚。从 3 道星辉中选择 1 道，永久获得其加成。
            <br />
            <span className="text-fuchsia-300/80">当前已觉醒 {progress.unlocked}/{progress.total}</span>
          </DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-1 gap-2 mt-1">
          {pendingChoices.map((perkId) => {
            const perk = getPerk(perkId);
            if (!perk) return null;
            const meta = CONSTELLATION_CATEGORY_META[perk.category];
            const isPicked = picked === perkId;
            return (
              <button
                key={perkId}
                onClick={() => handlePick(perkId)}
                disabled={!!picked}
                className={`group relative w-full text-left rounded-lg border px-3 py-2.5 transition-all overflow-hidden ${
                  isPicked
                    ? "border-fuchsia-400/80 bg-fuchsia-500/10 scale-[1.02]"
                    : picked
                    ? "border-white/5 opacity-40"
                    : "border-white/10 hover:border-white/30 hover:bg-white/5"
                }`}
                style={{
                  boxShadow: isPicked ? `0 0 20px ${meta.glow}` : undefined,
                }}
              >
                {/* 类别色条 */}
                <div
                  className="absolute left-0 top-0 bottom-0 w-1"
                  style={{ background: meta.hex, boxShadow: `0 0 8px ${meta.hex}` }}
                />
                <div className="pl-2 flex items-start gap-3">
                  {/* 类别图标 */}
                  <div
                    className="flex-shrink-0 mt-0.5 h-8 w-8 rounded-full flex items-center justify-center text-sm font-bold"
                    style={{
                      background: `${meta.hex}20`,
                      color: meta.hex,
                      border: `1px solid ${meta.hex}40`,
                    }}
                  >
                    {meta.name.charAt(0)}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-0.5">
                      <span className="text-sm font-bold text-foreground">{perk.name}</span>
                      <span
                        className="text-[9px] px-1 py-0.5 rounded font-mono"
                        style={{
                          background: `${meta.hex}20`,
                          color: meta.hex,
                        }}
                      >
                        {meta.name}
                      </span>
                    </div>
                    <div className="text-[11px] text-muted-foreground">{perk.desc}</div>
                  </div>
                </div>
                {/* 选中粒子动画 */}
                {isPicked && (
                  <div className="absolute inset-0 pointer-events-none">
                    {[...Array(8)].map((_, i) => (
                      <span
                        key={i}
                        className="absolute h-1 w-1 rounded-full animate-ping"
                        style={{
                          background: meta.hex,
                          left: `${20 + i * 8}%`,
                          top: `${30 + (i % 3) * 20}%`,
                          animationDelay: `${i * 50}ms`,
                          animationDuration: "800ms",
                        }}
                      />
                    ))}
                  </div>
                )}
              </button>
            );
          })}
        </div>

        <div className="flex items-center justify-between mt-3 pt-2 border-t border-white/5">
          <Button
            variant="ghost"
            size="sm"
            onClick={handleReroll}
            disabled={!!picked}
            className="text-muted-foreground hover:text-foreground h-7 text-[11px]"
          >
            <RefreshCw className="h-3 w-3 mr-1" />
            重新抽取
          </Button>
          <span className="text-[10px] text-muted-foreground/60">
            ✦ 选择后永久保留，跨周目生效
          </span>
        </div>
      </DialogContent>
    </Dialog>
  );
}
