import {
  COLOR_GLYPHS,
  COLOR_HEX,
  COLOR_NAMES,
  cardColor,
  cardValue,
  isHandshake,
} from "../game/cards";

interface CardProps {
  card: number;
  compact?: boolean;
  /** Card-back sized face-up card, for the rival's publicly known cards: the
   *  hand row is only as tall as a card back, so a full card would burst it. */
  mini?: boolean;
  selected?: boolean;
  hinted?: boolean;
  disabled?: boolean;
  onClick?: () => void;
  style?: React.CSSProperties;
  innerRef?: (element: HTMLElement | null) => void;
}

export function Card({
  card,
  compact = false,
  mini = false,
  selected = false,
  hinted = false,
  disabled = false,
  onClick,
  style: styleOverride,
  innerRef,
}: CardProps) {
  const color = cardColor(card);
  const value = cardValue(card);
  const handshake = isHandshake(card);
  const className = `card ${compact ? "card--compact" : ""} ${mini ? "card--mini" : ""} ${selected ? "card--selected" : ""} ${hinted ? "card--hinted" : ""}`;
  const style = { "--card-color": COLOR_HEX[color], ...styleOverride } as React.CSSProperties;
  const content = (
    <>
      <span className="card__corner card__corner--top">
        <b>{value}</b><i>{COLOR_GLYPHS[color]}</i>
      </span>
      <span className={`card__center ${handshake ? "card__center--handshake" : ""}`}>
        {handshake ? (
          <><i>{COLOR_GLYPHS[color]}</i><small>HANDSHAKE</small></>
        ) : (
          <><b>{value}</b><i>{COLOR_GLYPHS[color]}</i></>
        )}
      </span>
      <span className="card__corner card__corner--bottom">
        <b>{value}</b><i>{COLOR_GLYPHS[color]}</i>
      </span>
      {/* Covers the mirrored face while a flipping card is turned past edge-on;
          the motion layer fades it out at the halfway point of the flip. */}
      <span className="card__flip-cover" aria-hidden="true"><i>✦</i></span>
    </>
  );
  if (!onClick) {
    return (
      <div ref={innerRef} className={className} style={style} aria-label={`${COLOR_NAMES[color]} ${value}`}>
        {content}
      </div>
    );
  }
  return (
    <button
      ref={innerRef}
      type="button"
      className={className}
      style={style}
      onClick={onClick}
      disabled={disabled}
      aria-label={`${COLOR_NAMES[color]} ${value}`}
    >
      {content}
    </button>
  );
}

export function CardBack({
  count,
  innerRef,
}: {
  count?: number;
  innerRef?: (element: HTMLElement | null) => void;
}) {
  return (
    <div
      ref={innerRef}
      className="card card--back"
      aria-label={count === undefined ? "Hidden card" : `${count} cards`}
    >
      <span className="card__back-frame"><i>✦</i></span>
      {count !== undefined && <span className="card__count">{count}</span>}
    </div>
  );
}
