import { useRef, useState } from 'react';
import type { BetAction } from '../game/types';
import './ActionBar.css';

interface Props {
  bobo: number;
  baseChip: number;
  currentBet: number;
  heroTotalBet: number;
  /** 是否轮到本人发话 */
  myTurn: boolean;
  /** 本轮前面是否已有人下注（有则不能“休”） */
  canRest: boolean;
  /** 当前轮次（第 1 轮「必发招｜可休」只能休/丢，不开放下注） */
  round: number;
  onAction: (action: BetAction, amount?: number) => void;
}

/** 上滑轨道高度（px），拖到顶端即“敲/全下” */
const TRACK_H = 170;

export function ActionBar({
  bobo,
  baseChip,
  currentBet,
  heroTotalBet,
  myTurn,
  canRest,
  round,
  onAction,
}: Props) {
  const remaining = Math.max(bobo - heroTotalBet, 0);
  const maxUnits = Math.max(1, Math.floor(remaining / baseChip));
  // 第 1 轮「必发招｜可休」：只能休 / 丢，不开放 大/跟/敲
  const firstRound = round <= 1;
  const canRaise = myTurn && remaining > 0 && !firstRound;

  const [dragging, setDragging] = useState(false);
  const [level, setLevel] = useState(1);
  const startYRef = useRef(0);

  const atMax = level >= maxUnits;
  const amount = level * baseChip;

  const computeLevel = (clientY: number) => {
    const dy = Math.max(0, startYRef.current - clientY);
    const ratio = Math.min(1, dy / TRACK_H);
    if (maxUnits <= 1) return 1;
    return Math.min(maxUnits, Math.max(1, Math.round(ratio * (maxUnits - 1)) + 1));
  };

  const onDown = (e: React.PointerEvent) => {
    if (!canRaise) return;
    e.preventDefault();
    (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
    startYRef.current = e.clientY;
    setLevel(1);
    setDragging(true);
  };
  const onMove = (e: React.PointerEvent) => {
    if (!dragging) return;
    setLevel(computeLevel(e.clientY));
  };
  const commit = () => {
    if (!dragging) return;
    setDragging(false);
    if (atMax) onAction('knock');
    else onAction('raise', amount);
  };

  return (
    <div className="actionbar">
      {firstRound && (
        <div className="actionbar__phase">必发招 ｜ 可休</div>
      )}
      <div className="actionbar__buttons">
        <button
          className="pbtn pbtn--fold"
          disabled={!myTurn}
          onClick={() => onAction('fold')}
        >
          <span className="pbtn__main">丢</span>
          <span className="pbtn__sub">弃牌</span>
        </button>
        <button
          className="pbtn pbtn--rest"
          disabled={!myTurn || !canRest}
          onClick={() => onAction('rest')}
        >
          <span className="pbtn__main">休</span>
          <span className="pbtn__sub">过牌</span>
        </button>
        {!firstRound && (
        <button
          className="pbtn pbtn--call"
          disabled={!myTurn || currentBet === 0}
          onClick={() => onAction('call')}
        >
          <span className="pbtn__main">跟</span>
          <span className="pbtn__sub">{currentBet}</span>
        </button>
        )}

        {/* 大：按住上滑下注，拖到顶端=敲（全下） */}
        {!firstRound && (
        <div className="raise-ctrl">
          {dragging && (
            <div className="raise-track">
              <div className={`raise-track__top ${atMax ? 'raise-track__top--max' : ''}`}>
                {atMax ? (
                  <>
                    <span className="raise-track__amt">敲 · 全下</span>
                    <span className="raise-track__hint">松开下注</span>
                  </>
                ) : (
                  <>
                    <span className="raise-track__amt">+{amount}</span>
                    <span className="raise-track__hint">上滑加注 · 松开下注</span>
                  </>
                )}
              </div>
              <div className="raise-track__bar">
                <div
                  className={`raise-track__fill ${atMax ? 'raise-track__fill--max' : ''}`}
                  style={{ height: `${((level - 1) / Math.max(1, maxUnits - 1)) * 100}%` }}
                />
              </div>
            </div>
          )}
          <button
            className={`pbtn pbtn--raise ${dragging ? 'pbtn--raise-active' : ''}`}
            disabled={!canRaise}
            onPointerDown={onDown}
            onPointerMove={onMove}
            onPointerUp={commit}
            onPointerCancel={commit}
          >
            <span className="pbtn__main">大</span>
            <span className="pbtn__sub">{dragging ? (atMax ? '敲' : `+${amount}`) : '加注'}</span>
          </button>
        </div>
        )}

        {!firstRound && (
        <button
          className="pbtn pbtn--knock"
          disabled={!myTurn || remaining <= 0}
          onClick={() => onAction('knock')}
        >
          <span className="pbtn__main">敲</span>
          <span className="pbtn__sub">{remaining}</span>
        </button>
        )}
      </div>
    </div>
  );
}
