import { useEffect, useRef, useState } from 'react';
import './DealAnim.css';

interface Props {
  /** 台面元素：用于测量中央与各座位坐标 */
  feltRef: React.RefObject<HTMLDivElement | null>;
  /** 每次发牌递增，触发飞牌动画 */
  dealKey: number;
  /** 每个座位飞入的牌数（首轮 2 张底牌，之后 1 张明牌） */
  perSeat: number;
}

interface Target {
  dx: number;
  dy: number;
  rot: number;
}

// 中央牌堆相对台面的纵向位置（与 .felt__center 的 top:43% 对齐）
const CENTER_TOP = 0.43;

/** 发牌飞入特效：牌背从中央牌堆依次飞向各座位，落位后淡出 */
export function DealAnim({ feltRef, dealKey, perSeat }: Props) {
  const [count, setCount] = useState(0);
  const targetsRef = useRef<Target[]>([]);
  const layerRef = useRef<HTMLDivElement>(null);

  // 触发：测量各座位中心相对中央牌堆的偏移
  useEffect(() => {
    if (dealKey <= 0) return;
    const felt = feltRef.current;
    if (!felt) return;
    const fr = felt.getBoundingClientRect();
    const cx = fr.left + fr.width / 2;
    const cy = fr.top + fr.height * CENTER_TOP;
    const slots = Array.from(felt.querySelectorAll<HTMLElement>('[data-deal="1"]'));
    if (slots.length === 0) return;

    const targets: Target[] = [];
    slots.forEach((el) => {
      const r = el.getBoundingClientRect();
      const baseX = r.left + r.width / 2 - cx;
      const baseY = r.top + r.height / 2 - cy;
      for (let k = 0; k < perSeat; k++) {
        targets.push({
          dx: baseX + (k - (perSeat - 1) / 2) * 7,
          dy: baseY,
          rot: (Math.random() * 2 - 1) * 8,
        });
      }
    });
    targetsRef.current = targets;
    setCount(targets.length);
  }, [dealKey, perSeat, feltRef]);

  // 渲染后用 Web Animations API 逐张飞出
  useEffect(() => {
    if (count === 0) return;
    const layer = layerRef.current;
    if (!layer) return;
    const cards = Array.from(layer.children) as HTMLElement[];
    const anims = cards.map((el, i) => {
      const { dx, dy, rot } = targetsRef.current[i] ?? { dx: 0, dy: 0, rot: 0 };
      return el.animate(
        [
          { transform: 'translate(-50%, -50%) translate(0px, 0px) scale(0.45)', opacity: 0 },
          {
            transform: 'translate(-50%, -50%) translate(0px, 0px) scale(1)',
            opacity: 1,
            offset: 0.18,
          },
          {
            transform: `translate(-50%, -50%) translate(${dx}px, ${dy}px) rotate(${rot}deg) scale(0.92)`,
            opacity: 1,
            offset: 0.9,
          },
          {
            transform: `translate(-50%, -50%) translate(${dx}px, ${dy}px) rotate(${rot}deg) scale(0.92)`,
            opacity: 0,
          },
        ],
        { duration: 430, delay: i * 55, fill: 'forwards', easing: 'cubic-bezier(0.22, 0.7, 0.3, 1)' },
      );
    });
    let done = 0;
    const onFinish = () => {
      if (++done >= anims.length) setCount(0);
    };
    anims.forEach((a) => a.addEventListener('finish', onFinish));
    return () => anims.forEach((a) => a.cancel());
  }, [count]);

  if (count === 0) return null;
  return (
    <div className="deal-anim" ref={layerRef} aria-hidden>
      {Array.from({ length: count }).map((_, i) => (
        <span key={i} className="deal-anim__card" />
      ))}
    </div>
  );
}
