import { formatCredits, formatCreditsExact, toCentsBigInt } from '../api';
import { rarityColor } from '../rarities';

/** Instance sell/bet price, else catalog FT reference (BigInt cents). */
export function itemValueCents(item) {
  if (!item) return 0n;
  if (item.valueCents != null && item.valueCents !== '') {
    return toCentsBigInt(item.valueCents);
  }
  return toCentsBigInt(item.marketValue);
}

export function formatFloat(f) {
  const n = Number(f);
  if (!Number.isFinite(n)) return '';
  return n.toFixed(6);
}

export default function ItemTile({
  item,
  showValue = true,
  showWear = true,
  selected = false,
  favorite = false,
  staked = false,
  onClick,
  disabled = false,
}) {
  const color = rarityColor(item.rarity);
  const clickable = typeof onClick === 'function';
  const hasImage = Boolean(item.imageUrl);
  const value = itemValueCents(item);
  const wear = item.wear;
  const floatTitle =
    wear && item.floatValue != null
      ? `${wear} · ${formatFloat(item.floatValue)}${
          item.paintSeed != null ? ` · seed ${item.paintSeed}` : ''
        }`
      : wear || undefined;

  const titleParts = [];
  if (staked) titleParts.push('Vault');
  if (favorite) titleParts.push('Favorite');
  if (item.rarity) titleParts.push(item.rarity);
  if (floatTitle) titleParts.push(floatTitle);
  else titleParts.push(item.name);
  if (showValue) titleParts.push(`${formatCreditsExact(value)} cr`);

  return (
    <div
      className={`item-tile${selected ? ' selected' : ''}${favorite ? ' favorite' : ''}${
        staked ? ' staked' : ''
      }${clickable ? ' selectable' : ''}${disabled ? ' disabled' : ''}`}
      style={{ borderTopColor: color }}
      onClick={disabled ? undefined : onClick}
      role={clickable ? 'button' : undefined}
      tabIndex={clickable && !disabled ? 0 : undefined}
      title={titleParts.join(' · ')}
      onKeyDown={
        clickable && !disabled
          ? (e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                onClick();
              }
            }
          : undefined
      }
    >
      <div className={`item-visual${hasImage ? ' has-img' : ''}`} style={{ color }}>
        {favorite ? <span className="item-favorite-badge" aria-label="Favorite">★</span> : null}
        {staked ? <span className="item-vault-badge" aria-label="Vault">V</span> : null}
        {hasImage ? (
          <img src={item.imageUrl} alt="" loading="lazy" />
        ) : (
          item.name.slice(0, 2).toUpperCase()
        )}
      </div>
      <div className="item-name">{item.name}</div>
      {showWear && wear ? (
        <div className="item-wear" title={floatTitle}>
          {wear}
        </div>
      ) : null}
      {showValue && (
        <div className="item-meta item-price" title={`${formatCreditsExact(value)} cr`}>
          {formatCredits(value)} cr
        </div>
      )}
    </div>
  );
}
