import { useState, type CSSProperties } from 'react';
import type { Seat } from '../game/types';
import { PlayingCard } from './PlayingCard';
import { avatarHue, avatarUrl as getAvatarUrl } from '../game/avatar';
import './SeatView.css';

interface Props {
  seat: Seat;
  /** full = 头像+牌；pod = 仅头像信息；cards = 仅手牌 */
  variant?: 'full' | 'pod' | 'cards';
  /** 当前发话玩家的倒计时剩余比例（0~1）；undefined 表示不显示倒计时环 */
  countdown?: number;
  /** 强制秀牌：对手暗牌也翻开展示 */
  reveal?: boolean;
}

const RING_R = 46;
const RING_C = 2 * Math.PI * RING_R;

function CountdownRing({ pct }: { pct: number }) {
  const p = Math.max(0, Math.min(1, pct));
  const low = p <= 0.34;
  return (
    <svg className="seat__timer" viewBox="0 0 100 100" aria-hidden>
      <circle className="seat__timer-track" cx="50" cy="50" r={RING_R} />
      <circle
        className={`seat__timer-arc ${low ? 'seat__timer-arc--low' : ''}`}
        cx="50"
        cy="50"
        r={RING_R}
        style={{
          strokeDasharray: RING_C,
          strokeDashoffset: RING_C * (1 - p),
        }}
      />
    </svg>
  );
}

const STATUS_TAG: Record<Seat['status'], { text: string; kind: NonNullable<Seat['tagKind']> } | null> = {
  playing: null,
  folded: { text: '丢!', kind: 'fold' },
  knocked: { text: '敲', kind: 'knock' },
  rested: { text: '休', kind: 'rest' },
};

export function SeatView({ seat, variant = 'full', countdown, reveal = false }: Props) {
  const folded = seat.status === 'folded';
  // 统一徽标：优先用显式 tag，否则从状态推断
  const fallback = STATUS_TAG[seat.status];
  const tagText = seat.tag ?? fallback?.text;
  const tagKind = seat.tagKind ?? fallback?.kind;
  const showPod = variant === 'full' || variant === 'pod';
  const showCards = variant === 'full' || variant === 'cards';

  // 每位玩家一个稳定且互相区分的色相（作为头像加载失败时的回退底色）
  const hue = avatarHue(seat.id);

  // 真人头像照片（每位玩家一张不同的脸）；加载失败时回退到姓氏字
  const avatarUrl = getAvatarUrl(seat.id);
  const [imgOk, setImgOk] = useState(true);

  // 本人手牌：独立一排（底部），全部明示
  const heroCards = (
    <div className="seat__cards-wrap">
      <div className="seat__cards">
        {seat.cards.map((card) => (
          <PlayingCard key={card.id} card={card} revealed size="md" />
        ))}
      </div>
    </div>
  );

  // 对手明牌：头像下方一排（强制秀牌时全亮）
  const oppFaceUp = reveal ? seat.cards : seat.cards.filter((c) => c.faceUp);
  const oppCards = !seat.isHero && !folded && oppFaceUp.length > 0 && (
    <div className="seat__cards-wrap">
      <div className="seat__cards">
        {oppFaceUp.map((card) => (
          <PlayingCard key={card.id} card={card} revealed={reveal || card.faceUp} size="sm" />
        ))}
      </div>
      {seat.cardHint && <span className="seat__cardhint">{seat.cardHint}</span>}
    </div>
  );

  // 开局两张底牌：叠在头像上方（暗牌显示牌背）；丢牌后消失
  const holeRaw = seat.cards.filter((c) => !c.faceUp);
  const holeCards = !seat.isHero && !folded && holeRaw.length > 0 && (
    <div className="seat__hole">
      {holeRaw.map((card) => (
        <PlayingCard key={card.id} card={card} revealed={reveal} size="xs" />
      ))}
    </div>
  );

  /* 竖排铭牌：头像在上，名字/金额在下；状态徽标与下注筹码统一在头像右侧 */
  const plate = (
    <div className="seat__plate">
      <div className="seat__avatar-wrap">
        {holeCards}
        {typeof countdown === 'number' && <CountdownRing pct={countdown} />}
        <div
          className="seat__avatar"
          style={{ '--seat-hue': hue } as CSSProperties}
        >
          {imgOk ? (
            <img
              className="seat__avatar-img"
              src={avatarUrl}
              alt={seat.name}
              loading="lazy"
              onError={() => setImgOk(false)}
            />
          ) : (
            <span className="seat__avatar-mono">{seat.name.slice(0, 1)}</span>
          )}
        </div>
        {seat.isDealer && <span className="seat__dealer">庄</span>}
        {tagText && (
          <span className={`seat__tag seat__tag--${tagKind ?? 'rest'}`}>{tagText}</span>
        )}
        {seat.betThisRound > 0 && (
          <span className="seat__betchip">
            <span className="seat__betchip-ico">S</span>
            {seat.betThisRound}
          </span>
        )}
      </div>
      <div className="seat__info">
        <div className="seat__name">{seat.name}</div>
        <div className="seat__chips">
          <span className="coin seat__chips-coin" />
          {seat.chips.toLocaleString()}
        </div>
      </div>
    </div>
  );

  return (
    <div
      className={[
        'seat',
        seat.isHero ? 'seat--hero' : 'seat--opp',
        `seat--${variant}`,
        seat.isActive ? 'seat--active' : '',
        folded ? 'seat--folded' : '',
      ].join(' ')}
    >
      {showCards && (seat.isHero ? heroCards : oppCards)}
      {showPod && plate}
      {showCards && seat.isHero && seat.handHint && (
        <div className="seat__hint">{seat.handHint}</div>
      )}
    </div>
  );
}
