import { useState, type CSSProperties } from 'react';
import type { Card, JackpotHit, PlayerResult } from '../game/types';
import { avatarHue, avatarUrl } from '../game/avatar';
import { cardLabel, cardSymbol, isRed } from '../game/cards';
import './ResultOverlay.css';

interface Props {
  results: PlayerResult[];
  jackpotHit?: JackpotHit;
  onNext: () => void;
}

function ResultAvatar({ r }: { r: PlayerResult }) {
  const [imgOk, setImgOk] = useState(true);
  return (
    <span
      className="result-row__avatar"
      style={{ '--seat-hue': avatarHue(r.seatId) } as CSSProperties}
    >
      {imgOk ? (
        <img
          src={avatarUrl(r.seatId)}
          alt={r.name}
          loading="lazy"
          onError={() => setImgOk(false)}
        />
      ) : (
        <span className="result-row__mono">{r.name.slice(0, 1)}</span>
      )}
    </span>
  );
}

function MiniCard({ card }: { card: Card }) {
  const cls = card.suit === 'joker' ? 'mcard--joker' : isRed(card.suit) ? 'mcard--red' : 'mcard--black';
  return (
    <span className={`mcard ${cls}`}>
      <span className="mcard__rank">{cardLabel(card)}</span>
      <span className="mcard__suit">{cardSymbol(card)}</span>
    </span>
  );
}

const COINS = Array.from({ length: 16 }, (_, i) => i);

function CoinShower() {
  return (
    <div className="result-coins" aria-hidden>
      {COINS.map((i) => (
        <span
          key={i}
          className="coin result-coins__c"
          style={
            {
              left: `${(i * 6.1 + 4) % 96}%`,
              animationDelay: `${(i % 8) * 0.12}s`,
              animationDuration: `${1.1 + (i % 5) * 0.18}s`,
            } as CSSProperties
          }
        />
      ))}
    </div>
  );
}

export function ResultOverlay({ results, jackpotHit, onNext }: Props) {
  const anyWin = results.some((r) => r.delta > 0);
  return (
    <div className="result-mask">
      {(anyWin || jackpotHit) && <CoinShower />}
      <div className="result-card">
        {jackpotHit && (
          <div className="jackpot-hit">
            <div className="jackpot-hit__crown">🎉 爆奖 🎉</div>
            <div className="jackpot-hit__line">
              <b>{jackpotHit.player}</b> 拿到 <b>{jackpotHit.hand}</b>
              （{jackpotHit.percent}%）
            </div>
            <div className="jackpot-hit__amount">
              <span className="coin" />+{jackpotHit.amount.toLocaleString()}
            </div>
          </div>
        )}
        <div className="result-card__title">本局结算</div>
        <div className="result-list">
          {results.map((r) => (
            <div
              key={r.seatId}
              className={`result-row ${r.won ? 'result-row--win' : ''}`}
            >
              <div className="result-row__info">
                <ResultAvatar r={r} />
                <span className="result-row__name">{r.name}</span>
                <span className="result-row__hand">{r.special ?? r.handName}</span>
                <span
                  className={`result-row__delta ${
                    r.delta > 0 ? 'pos' : r.delta < 0 ? 'neg' : ''
                  }`}
                >
                  {r.delta > 0 ? `+${r.delta}` : r.delta}
                </span>
              </div>
              {r.headCards && r.tailCards && (
                <div className="result-row__decks">
                  <span className="result-deck">
                    <span className="result-deck__label">头</span>
                    {r.headCards.map((c) => (
                      <MiniCard key={c.id} card={c} />
                    ))}
                  </span>
                  <span className="result-deck">
                    <span className="result-deck__label">尾</span>
                    {r.tailCards.map((c) => (
                      <MiniCard key={c.id} card={c} />
                    ))}
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>
        <button className="result-next" onClick={onNext}>
          下一局
        </button>
      </div>
    </div>
  );
}
