// MerchCard.jsx — packaging-replica card for merch items. Tier-aware.
const MerchCard = ({ p, onOpen, onAdd, user }) => {
  const [selectedSize, setSelectedSize] = React.useState(p.sizes ? p.sizes[0] : null);
  const [selectedColor, setSelectedColor] = React.useState(p.colors ? p.colors[0] : null);
  const [rankPatch, setRankPatch] = React.useState(false);
  const [handlePrint, setHandlePrint] = React.useState(false);

  const sku = `OBC-MERCH-${p.id}`;
  const mitre = p.mitre || '';
  const spend = (user && user.tierData && user.tierData.lifetime_spend) || 0;
  const helpers = window.OBC_TIER_HELPERS || {};
  const tiers = window.OBC_TIERS || [];

  const locked = p.minTier != null && helpers.canPurchaseMerch && !helpers.canPurchaseMerch(spend, p.minTier);
  const canPatch = p.rankPatchEligible && helpers.canAddRankPatch && helpers.canAddRankPatch(spend);
  const canHandle = p.handlePrintEligible && helpers.canAddHandlePrint && helpers.canAddHandlePrint(spend);

  const requiredTierName = p.minTier != null && tiers[p.minTier] ? tiers[p.minTier].name : 'UNKNOWN';
  const weight = p.weight || '';

  const labelStyle = { color: '#E0E0E0', fontSize: 12, letterSpacing: '0.18em', fontWeight: 700, textTransform: 'uppercase' };
  const valueStyle = { color: '#FFFFFF', marginTop: 6, lineHeight: 1.45, fontSize: 14, letterSpacing: '0.04em', fontWeight: 500 };

  const handleAdd = () => {
    if (locked) return;
    const customizations = {};
    if (rankPatch && canPatch) customizations.rankPatch = true;
    if (handlePrint && canHandle) customizations.handlePrint = true;
    onAdd(p, 1, { size: selectedSize, color: selectedColor, customizations });
  };

  return (
    <div
      onClick={() => onOpen(p)}
      style={{
        background: '#000',
        border: '1px solid rgba(255,255,255,0.36)',
        display: 'flex',
        flexDirection: 'column',
        cursor: 'pointer',
        minHeight: 580,
        position: 'relative',
        transition: 'border-color 120ms ease-out, box-shadow 120ms ease-out, transform 120ms ease-out',
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.borderColor = p.accent;
        e.currentTarget.style.boxShadow = `0 0 0 1px ${p.accent}, 0 0 32px ${p.accent}55`;
        e.currentTarget.style.transform = 'translateY(-3px)';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.borderColor = 'rgba(255,255,255,0.36)';
        e.currentTarget.style.boxShadow = 'none';
        e.currentTarget.style.transform = 'translateY(0)';
      }}
    >
      {/* HEADER STRIP */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 18px', borderBottom: '1px solid rgba(255,255,255,0.28)',
        background: '#0A0A0A', fontSize: 12, letterSpacing: '0.2em', color: '#E0E0E0', fontWeight: 700,
      }}>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background: p.accent, boxShadow: `0 0 10px ${p.accent}` }}></span>
        <span style={{ color: p.accent, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sku}</span>
        <span style={{ marginLeft: 'auto', color: '#BFBFBF', whiteSpace: 'nowrap' }}>{mitre}</span>
      </div>

      {/* NAME + TYPE */}
      <div style={{ padding: '24px 22px 12px' }}>
        <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: '0.02em', textTransform: 'uppercase', color: p.accent, lineHeight: 0.95 }}>
          {p.name}
        </div>
        <div style={{ fontSize: 12, letterSpacing: '0.26em', color: '#E0E0E0', marginTop: 12, fontWeight: 700, textTransform: 'uppercase', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {p.type}
        </div>
      </div>

      {/* IMAGE PLACEHOLDER — same dimensions as ProductCard terminal log */}
      <div style={{
        margin: '14px 22px 0', padding: '18px',
        background: `${p.accent}1A`, border: `1px solid ${p.accent}66`, color: p.accent,
        fontSize: 14, lineHeight: 1.7, height: 210, position: 'relative',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        overflow: 'hidden',
      }}>
        <div style={{ fontSize: 72, opacity: 0.35, lineHeight: 1, pointerEvents: 'none' }}>{p.glyph}</div>
        <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', marginTop: 10, fontWeight: 600 }}>// IMAGE PENDING</div>
        <div style={{ position: 'absolute', bottom: 10, left: 18, right: 18, fontSize: 11, lineHeight: 1.6, opacity: 0.6 }}>
          {p.log.slice(0, 2).map((l, i) => (<div key={i}>{'>'} {l}</div>))}
        </div>
      </div>

      {/* METADATA GRID */}
      <div style={{
        margin: '20px 22px 0',
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '18px 22px',
      }}>
        <div>
          <div style={labelStyle}>MATERIAL</div>
          <div style={valueStyle}>{p.material}</div>
        </div>
        <div>
          <div style={labelStyle}>TYPE</div>
          <div style={valueStyle}>{p.type}</div>
        </div>
        <div>
          <div style={labelStyle}>WEIGHT</div>
          <div style={valueStyle}>{weight}</div>
        </div>
        <div>
          <div style={labelStyle}>FEATURES</div>
          <div style={valueStyle}>{(p.features || []).slice(0, 2).join(' · ')}</div>
        </div>
      </div>

      <div style={{ flex: 1 }}></div>

      {/* SIZE + COLOR + CUSTOMIZATION + PRICE + BUY */}
      <div style={{
        padding: '16px 22px 16px', borderTop: '1px dashed rgba(255,255,255,0.50)',
        marginTop: 20,
      }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* SIZE SELECTOR */}
        {p.sizes && p.sizes.length > 0 && (
          <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
            {p.sizes.map((s) => (
              <button key={s} onClick={() => setSelectedSize(s)} style={{
                padding: '6px 12px', fontSize: 10, fontWeight: 700, letterSpacing: '0.12em',
                fontFamily: 'inherit', cursor: 'pointer', borderRadius: 2,
                background: selectedSize === s ? p.accent : 'transparent',
                color: selectedSize === s ? '#000' : '#B8B8B8',
                border: `1px solid ${selectedSize === s ? p.accent : 'rgba(255,255,255,0.18)'}`,
              }}>{s}</button>
            ))}
          </div>
        )}

        {/* COLOR SELECTOR */}
        {p.colors && p.colors.length > 0 && (
          <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
            {p.colors.map((c) => (
              <button key={c} onClick={() => setSelectedColor(c)} style={{
                padding: '6px 12px', fontSize: 10, fontWeight: 700, letterSpacing: '0.12em',
                fontFamily: 'inherit', cursor: 'pointer', borderRadius: 2,
                background: selectedColor === c ? p.accent : 'transparent',
                color: selectedColor === c ? '#000' : '#B8B8B8',
                border: `1px solid ${selectedColor === c ? p.accent : 'rgba(255,255,255,0.18)'}`,
              }}>{c}</button>
            ))}
          </div>
        )}

        {/* CUSTOMIZATION BADGES */}
        {(canPatch || canHandle) && (
          <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
            {canPatch && (
              <button onClick={() => setRankPatch(!rankPatch)} style={{
                padding: '4px 8px', fontSize: 9, fontWeight: 700, letterSpacing: '0.1em',
                fontFamily: 'inherit', cursor: 'pointer', borderRadius: 2,
                background: rankPatch ? p.accent : 'transparent',
                color: rankPatch ? '#000' : '#B8B8B8',
                border: `1px solid ${rankPatch ? p.accent : 'rgba(255,255,255,0.18)'}`,
              }}>RANK PATCH</button>
            )}
            {canHandle && (
              <button onClick={() => setHandlePrint(!handlePrint)} style={{
                padding: '4px 8px', fontSize: 9, fontWeight: 700, letterSpacing: '0.1em',
                fontFamily: 'inherit', cursor: 'pointer', borderRadius: 2,
                background: handlePrint ? p.accent : 'transparent',
                color: handlePrint ? '#000' : '#B8B8B8',
                border: `1px solid ${handlePrint ? p.accent : 'rgba(255,255,255,0.18)'}`,
              }}>HANDLE</button>
            )}
          </div>
        )}

        {/* PRICE + ADD (or LOCKED) */}
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
          <div>
            <div style={labelStyle}>PRICE</div>
            <div style={{ fontSize: 30, fontWeight: 800, color: '#FFFFFF', lineHeight: 1, marginTop: 6 }}>
              ${p.price}<span style={{ fontSize: 14, color: '#CCCCCC', marginLeft: 6, letterSpacing: '0.1em', fontWeight: 600 }}>USD</span>
            </div>
          </div>
          {locked ? (
            <button style={{
              background: 'transparent', color: '#FF3344',
              padding: '12px 18px', fontSize: 11, fontWeight: 800, letterSpacing: '0.15em',
              border: '1px solid #FF3344', fontFamily: 'inherit', cursor: 'not-allowed', opacity: 0.8,
            }}>
              [ LOCKED ]
            </button>
          ) : (
            <button
              onClick={handleAdd}
              style={{
                background: p.accent, color: '#000',
                padding: '12px 18px', fontSize: 14, fontWeight: 800, letterSpacing: '0.2em',
                border: `1px solid ${p.accent}`, fontFamily: 'inherit', cursor: 'pointer',
              }}
            >
              [ADD]
            </button>
          )}
        </div>
      </div>

      {/* TIER LOCK OVERLAY */}
      {locked && (
        <div style={{
          position: 'absolute', inset: 0,
          background: 'rgba(0,0,0,0.75)',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          zIndex: 10,
        }}>
          <div style={{ fontSize: 36, marginBottom: 12, opacity: 0.6 }}>&#128274;</div>
          <div style={{
            padding: '10px 18px', border: '1px solid #FF3344', color: '#FF3344',
            fontSize: 12, letterSpacing: '0.15em', fontWeight: 700,
          }}>
            [ LOCKED — REQUIRES {requiredTierName} ]
          </div>
        </div>
      )}

      {/* BARCODE FOOTER */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '12px 18px', borderTop: '1px solid rgba(255,255,255,0.28)',
        background: '#0A0A0A',
      }}>
        <div style={{ display: 'flex', gap: 1, height: 22, alignItems: 'center' }}>
          {[2,1,3,1,2,1,1,3,2,1,2,3,1,2,1,1,2,3,1,2,1,3,2,1,1,2,1,3,2,1].map((w, i) => (
            <div key={i} style={{ width: w, height: '100%', background: i % 2 === 0 ? '#BFBFBF' : 'transparent' }}></div>
          ))}
        </div>
        <span style={{ marginLeft: 'auto', fontSize: 11, letterSpacing: '0.22em', color: '#BFBFBF', fontWeight: 600, textAlign: 'right', lineHeight: 1.4 }}>
          OPERATOR BREWING<br/>{weight}
        </span>
      </div>
    </div>
  );
};

window.MerchCard = MerchCard;
