import { useEffect, useRef, useState } from 'react';
import type { Card } from '../game/types';
import { evalGroup } from '../game/handEval';
import { PlayingCard } from './PlayingCard';
import './SplitView.css';

interface Props {
  cards: Card[];
  /** 分牌倒计时占比 0~1（满→空） */
  countdown?: number;
  onConfirm: (headIds: string[], mult: number) => void;
  onFold: () => void;
}

/** 倍数档：上排选择值 → 下排实际倍数（factor 即结算倍数） */
const MULTS = [
  { label: '×1', factor: '×2', value: 2 },
  { label: '×2', factor: '×4', value: 4 },
  { label: '×3', factor: '×6', value: 6 },
];

/**
 * 本人分牌（按官方界面）：上方头墩、下方尾墩，点牌面在两墩间交换归属；
 * 中部倍数选择 + 丢/确定分牌；实时显示两墩牌型名。
 */
export function SplitView({ cards, countdown = 1, onConfirm, onFold }: Props) {
  // 初始：前两张为头墩，其余为尾墩
  const [headIds, setHeadIds] = useState<string[]>(() =>
    cards.slice(0, 2).map((c) => c.id),
  );
  const [sel, setSel] = useState<string | null>(null);
  const [mult, setMult] = useState(0);

  // 倒计时归零自动按当前摆放确定分牌（armed 防止挂载时旧值误触发）
  const armedRef = useRef(false);
  const doneRef = useRef(false);
  useEffect(() => {
    if (countdown > 0.3) armedRef.current = true;
    if (!armedRef.current || doneRef.current || countdown > 0) return;
    doneRef.current = true;
    onConfirm(headIds, MULTS[mult].value);
  }, [countdown, headIds, mult, onConfirm]);

  const byId = (id: string) => cards.find((c) => c.id === id)!;
  const tailIds = cards.filter((c) => !headIds.includes(c.id)).map((c) => c.id);
  const headCards = headIds.map(byId);
  const tailCards = tailIds.map(byId);

  const headEval =
    headCards.length === 2 ? evalGroup([headCards[0], headCards[1]]) : null;
  const tailEval =
    tailCards.length === 2 ? evalGroup([tailCards[0], tailCards[1]]) : null;

  // 点牌：选中一张后再点另一墩的牌即交换两者归属
  const tap = (id: string) => {
    if (sel === null) {
      setSel(id);
      return;
    }
    if (sel === id) {
      setSel(null);
      return;
    }
    const selInHead = headIds.includes(sel);
    const idInHead = headIds.includes(id);
    if (selInHead !== idInHead) {
      setHeadIds((prev) =>
        selInHead ? prev.map((x) => (x === sel ? id : x)) : prev.map((x) => (x === id ? sel : x)),
      );
    }
    setSel(null);
  };

  const renderCard = (card: Card) => (
    <button
      key={card.id}
      type="button"
      className={`splitview__card ${sel === card.id ? 'is-sel' : ''}`}
      onClick={() => tap(card.id)}
    >
      <PlayingCard card={card} revealed size="md" />
    </button>
  );

  return (
    <div className="splitview-overlay">
      {/* 分牌倒计时条 */}
      <div className="splitview__timer">
        <span className="splitview__timer-bar" style={{ width: `${countdown * 100}%` }} />
      </div>

      {/* 倍数选择 */}
      <div className="splitview__mults">
        {MULTS.map((m, i) => (
          <button
            key={m.label}
            type="button"
            className={`splitview__mult ${mult === i ? 'is-on' : ''}`}
            onClick={() => setMult(i)}
          >
            <span className="splitview__mult-main">{m.label}</span>
            <span className="splitview__mult-sub">{m.factor}</span>
          </button>
        ))}
      </div>

      {/* 头墩 */}
      <div className="splitview__dun-label">{headEval ? headEval.name : '头墩'}</div>
      <div className="splitview__dun">{headCards.map(renderCard)}</div>

      {/* 操作区：丢 / 确定分牌 */}
      <div className="splitview__actions">
        <button type="button" className="splitview__rbtn splitview__rbtn--fold" onClick={onFold}>
          <span className="splitview__rbtn-main">丢</span>
        </button>
        <button
          type="button"
          className="splitview__confirm"
          onClick={() => onConfirm(headIds, MULTS[mult].value)}
        >
          确定分牌
        </button>
        <div className="splitview__rbtn splitview__rbtn--mult">
          <span className="splitview__rbtn-main">{MULTS[mult].factor}</span>
          <span className="splitview__rbtn-sub">倍数</span>
        </div>
      </div>

      {/* 尾墩 */}
      <div className="splitview__dun">{tailCards.map(renderCard)}</div>
      <div className="splitview__dun-label">{tailEval ? tailEval.name : '尾墩'}</div>
    </div>
  );
}
