import React, { useContext } from 'react';
import { CardContext } from '../../store/CardContext';
import PrintingRow from '../PrintingRow/PrintingRow';

const BADGE = {
  monster: { background: '#3a2000', color: '#d4820a' },
  spell:   { background: '#002820', color: '#10a06a' },
  trap:    { background: '#280020', color: '#c040a0' },
  other:   { background: '#202020', color: '#666' },
};

function typeBadge(type) {
  const t = type.toLowerCase();
  if (t.includes('monster')) return BADGE.monster;
  if (t.includes('spell'))   return BADGE.spell;
  if (t.includes('trap'))    return BADGE.trap;
  return BADGE.other;
}

const PRINTING_COLS = '80px 1fr 150px 100px';

function CardRow({ card }) {
  const { expandedCardId, setExpandedCardId, ownedAmounts } = useContext(CardContext);
  const isExpanded = expandedCardId === card.id;

  const totalOwned = card.printings?.reduce((sum, p) => {
    const key = `${p.set_id}-${p.rarity_id}`;
    return sum + (ownedAmounts[card.id]?.[key] ?? p.amount_owned ?? 0);
  }, 0) ?? 0;

  return (
    <div style={{ borderBottom: '1px solid #1e1e1e' }}>
      <div
        className="card-row-header"
        onClick={() => setExpandedCardId(isExpanded ? null : card.id)}
        style={{
          display: 'flex', alignItems: 'center', gap: '12px',
          padding: '11px 16px',
          background: isExpanded ? '#1c1c1c' : 'transparent',
        }}
      >
        <span style={{ flex: 1, fontSize: '13px', color: '#d8d8d8' }}>{card.name}</span>
        <span style={{
          fontSize: '11px', padding: '2px 8px', borderRadius: '10px',
          fontWeight: 500, whiteSpace: 'nowrap',
          ...typeBadge(card.type),
        }}>
          {card.type}
        </span>
        <span style={{
          fontSize: '12px', whiteSpace: 'nowrap', minWidth: '48px', textAlign: 'right',
          color: totalOwned > 0 ? '#aaa' : '#444',
        }}>
          {totalOwned > 0 ? `×${totalOwned}` : '—'}
        </span>
      </div>

      {isExpanded && card.printings?.length > 0 && (
        <div style={{ background: '#161616', paddingBottom: '6px' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: PRINTING_COLS,
            gap: '8px', padding: '5px 16px 5px 32px',
            fontSize: '10px', color: '#444',
            textTransform: 'uppercase', letterSpacing: '0.05em',
            borderBottom: '1px solid #222',
          }}>
            <span>Code</span><span>Set</span><span>Rarity</span><span>Owned</span>
          </div>
          {card.printings.map(printing => (
            <PrintingRow
              key={`${card.id}-${printing.set_id}-${printing.rarity_id}`}
              card_id={card.id}
              printing={printing}
              cols={PRINTING_COLS}
            />
          ))}
        </div>
      )}
    </div>
  );
}

export default CardRow;
