// MerchDetail.jsx — full overlay for merch product details. Tier-aware.
const MerchDetail = ({ p, onClose, onAdd, user }) => {
  if (!p) return null;
  const [qty, setQty] = React.useState(1);
  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 [handleName, setHandleName] = React.useState('');

  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 discount = helpers.getMerchDiscount ? helpers.getMerchDiscount(spend) : 0;

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

  const RANK_PATCH_PRICE = 5;
  const HANDLE_PRINT_PRICE = 8;

  const basePrice = p.price;
  const discountedPrice = discount > 0 ? Math.round(basePrice * (1 - discount / 100) * 100) / 100 : basePrice;
  let unitPrice = discountedPrice;
  if (rankPatch && canPatch) unitPrice += RANK_PATCH_PRICE;
  if (handlePrint && canHandle && handleName.trim()) unitPrice += HANDLE_PRINT_PRICE;

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

  // Find user's current tier for rank patch display
  const userTier = (user && user.tierData && user.tierData.tier != null) ? user.tierData.tier : 0;
  const userTierName = tiers[userTier] ? tiers[userTier].name : 'NEWCOMER';

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.92)', zIndex: 100, padding: 32, overflow: 'auto' }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 1080, margin: '0 auto', background: '#0A0A0A', border: `1px solid ${p.accent}`, padding: 32, position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 14, right: 14, background: 'transparent', border: '1px solid rgba(255,255,255,0.2)', color: '#B8B8B8', padding: '4px 10px', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11, letterSpacing: '0.18em' }}>[ ESC ] CLOSE</button>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 36 }}>
          {/* LEFT: image placeholder + specs */}
          <div style={{ background: '#000', border: '1px solid rgba(255,255,255,0.22)', padding: 24, minHeight: 460, display: 'flex', flexDirection: 'column' }}>
            <div style={{ fontSize: 11, letterSpacing: '0.25em', color: '#BFBFBF', fontWeight: 600 }}>// RENDER</div>
            <div style={{
              marginTop: 16, padding: 16, flex: 1,
              background: `${p.accent}14`, border: `1px solid ${p.accent}55`,
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{ fontSize: 96, opacity: 0.3, lineHeight: 1, color: p.accent }}>{p.glyph}</div>
              <div style={{ fontSize: 11, letterSpacing: '0.22em', color: '#E0E0E0', marginTop: 14, fontWeight: 600 }}>// RENDER PENDING</div>
            </div>
            <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, fontSize: 11, letterSpacing: '0.18em' }}>
              <div><div style={{ color: '#BFBFBF', fontWeight: 600 }}>MATERIAL</div><div style={{ color: '#FFF', marginTop: 5, lineHeight: 1.55, fontSize: 12, letterSpacing: '0.06em' }}>{p.material}</div></div>
              <div><div style={{ color: '#BFBFBF', fontWeight: 600 }}>WEIGHT</div><div style={{ color: '#FFF', marginTop: 5, fontSize: 12, letterSpacing: '0.06em' }}>{weight}</div></div>
              <div style={{ gridColumn: '1 / -1' }}><div style={{ color: '#BFBFBF', fontWeight: 600 }}>FEATURES</div><div style={{ color: '#FFF', marginTop: 5, lineHeight: 1.55, fontSize: 12, letterSpacing: '0.06em' }}>{(p.features || []).join(' · ')}</div></div>
            </div>
            <div style={{ marginTop: 22, paddingTop: 14, borderTop: '1px dashed rgba(255,255,255,0.32)', display: 'flex', justifyContent: 'space-between', fontSize: 10, letterSpacing: '0.22em', color: '#BFBFBF' }}>
              <span style={{ color: p.accent }}>{p.glyph} OPERATOR BREWING CO.</span><span>{weight}</span>
            </div>
          </div>

          {/* RIGHT: product info + buy */}
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.25em', color: '#BFBFBF', fontWeight: 600 }}>// /merch/{p.id}</div>
            <div style={{ marginTop: 8, fontSize: 44, fontWeight: 800, color: '#FFF', letterSpacing: '0.04em', textTransform: 'uppercase', lineHeight: 1 }}>{p.name}</div>
            <div style={{ marginTop: 10, fontSize: 12, letterSpacing: '0.22em', color: p.accent, fontWeight: 700 }}>// {p.type} · {p.mitre || ''}</div>

            {/* TERMINAL LOG */}
            <div style={{ marginTop: 18, padding: 14, background: `${p.accent}0D`, border: `1px solid ${p.accent}44`, fontSize: 13, lineHeight: 1.7, color: p.accent }}>
              {p.log.map((l, i) => (<div key={i}>{'>'} {l}</div>))}
            </div>

            {p.description && (
              <div style={{ marginTop: 22, fontSize: 14, lineHeight: 1.7, color: '#E8E8E8', letterSpacing: '0.02em' }}>
                {p.description}
              </div>
            )}

            {/* PRICE */}
            <div style={{ marginTop: 24, fontSize: 30, color: '#FFF', fontWeight: 800, lineHeight: 1 }}>
              {discount > 0 && (
                <span style={{ fontSize: 18, color: '#9A9A9A', textDecoration: 'line-through', marginRight: 10 }}>${basePrice}</span>
              )}
              ${discountedPrice}<span style={{ fontSize: 13, color: '#BFBFBF', marginLeft: 8, letterSpacing: '0.1em', fontWeight: 600 }}>USD</span>
              {discount > 0 && (
                <span style={{ fontSize: 11, color: p.accent, marginLeft: 10, letterSpacing: '0.12em' }}>-{discount}% TIER DISCOUNT</span>
              )}
            </div>

            {/* SIZE SELECTOR */}
            {p.sizes && p.sizes.length > 0 && (
              <div style={{ marginTop: 24 }}>
                <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 8 }}>{'>'} SIZE</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {p.sizes.map((s) => (
                    <button key={s} onClick={() => setSelectedSize(s)} style={{
                      background: selectedSize === s ? p.accent : 'transparent',
                      color: selectedSize === s ? '#000' : '#B8B8B8',
                      border: `1px solid ${selectedSize === s ? p.accent : 'rgba(255,255,255,0.18)'}`,
                      padding: '8px 12px', fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.15em', cursor: 'pointer', borderRadius: 2, fontWeight: 700,
                    }}>{s}</button>
                  ))}
                </div>
              </div>
            )}

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

            {/* CUSTOMIZATION PANEL */}
            {(canPatch || canHandle) && (
              <div style={{ marginTop: 22, padding: 14, border: '1px solid rgba(255,255,255,0.18)', background: 'rgba(255,255,255,0.02)' }}>
                <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 12 }}>{'>'} CUSTOMIZATIONS</div>

                {canPatch && (
                  <button onClick={() => setRankPatch(!rankPatch)} style={{
                    display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                    background: 'transparent', border: 'none', padding: '8px 0',
                    fontFamily: 'inherit', fontSize: 12, letterSpacing: '0.1em', cursor: 'pointer', color: '#E0E0E0', textAlign: 'left',
                  }}>
                    <span style={{ color: rankPatch ? p.accent : '#6E6E6E' }}>{rankPatch ? '[*]' : '[ ]'}</span>
                    <span>ADD RANK PATCH (+${RANK_PATCH_PRICE})</span>
                    <span style={{ marginLeft: 'auto', fontSize: 10, color: '#9A9A9A', letterSpacing: '0.12em' }}>{userTierName}</span>
                  </button>
                )}

                {canHandle && (
                  <div>
                    <button onClick={() => setHandlePrint(!handlePrint)} style={{
                      display: 'flex', alignItems: 'center', gap: 10, width: '100%',
                      background: 'transparent', border: 'none', padding: '8px 0',
                      fontFamily: 'inherit', fontSize: 12, letterSpacing: '0.1em', cursor: 'pointer', color: '#E0E0E0', textAlign: 'left',
                    }}>
                      <span style={{ color: handlePrint ? p.accent : '#6E6E6E' }}>{handlePrint ? '[*]' : '[ ]'}</span>
                      <span>ADD HANDLE EMBROIDERY (+${HANDLE_PRINT_PRICE})</span>
                    </button>
                    {handlePrint && (
                      <div style={{ marginTop: 6, position: 'relative' }}>
                        <span style={{ position: 'absolute', left: 10, top: 10, color: p.accent, fontSize: 13 }}>@</span>
                        <input
                          value={handleName}
                          onChange={(e) => setHandleName(e.target.value)}
                          placeholder="your_handle"
                          maxLength={24}
                          style={{
                            width: '100%', background: '#0A0A0A', border: `1px solid ${p.accent}55`,
                            color: '#FFF', fontFamily: 'inherit', fontSize: 13, padding: '10px 12px 10px 28px', borderRadius: 2,
                          }}
                          onFocus={(e) => { e.target.style.borderColor = p.accent; e.target.style.boxShadow = `0 0 0 1px ${p.accent}`; }}
                          onBlur={(e) => { e.target.style.borderColor = `${p.accent}55`; e.target.style.boxShadow = 'none'; }}
                        />
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* TIER LOCK MESSAGE */}
            {locked && (
              <div style={{
                marginTop: 22, padding: 16,
                border: '1px solid #FF3344', background: 'rgba(255,51,68,0.06)',
                color: '#FF3344', fontSize: 13, letterSpacing: '0.1em', fontWeight: 700, lineHeight: 1.7,
              }}>
                <div>{'>'} ACCESS DENIED — REQUIRES {requiredTierName}</div>
                <div style={{ marginTop: 10, height: 4, background: 'rgba(255,255,255,0.1)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{
                    height: '100%', background: '#FF3344',
                    width: p.minTier > 0 ? `${Math.min(100, (userTier / p.minTier) * 100)}%` : '0%',
                    borderRadius: 2, transition: 'width 300ms ease-out',
                  }}></div>
                </div>
                <div style={{ marginTop: 6, fontSize: 10, color: '#9A9A9A', letterSpacing: '0.15em' }}>
                  {userTierName} → {requiredTierName}
                </div>
              </div>
            )}

            {/* QUANTITY */}
            {!locked && (
              <div style={{ marginTop: 24 }}>
                <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 8 }}>{'>'} QUANTITY</div>
                <div style={{ display: 'inline-flex', border: '1px solid rgba(255,255,255,0.2)' }}>
                  <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ background: 'transparent', color: '#B8B8B8', border: 'none', borderRight: '1px solid rgba(255,255,255,0.2)', padding: '8px 14px', fontFamily: 'inherit', cursor: 'pointer' }}>-</button>
                  <span style={{ padding: '8px 16px', color: '#FFF', minWidth: 40, textAlign: 'center' }}>{String(qty).padStart(2, '0')}</span>
                  <button onClick={() => setQty(qty + 1)} style={{ background: 'transparent', color: '#B8B8B8', border: 'none', borderLeft: '1px solid rgba(255,255,255,0.2)', padding: '8px 14px', fontFamily: 'inherit', cursor: 'pointer' }}>+</button>
                </div>
              </div>
            )}

            {/* ADD BUTTON */}
            {!locked && (
              <button onClick={handleAdd} style={{
                marginTop: 28, width: '100%', background: p.accent, color: '#000', border: `1px solid ${p.accent}`,
                padding: '16px', fontFamily: 'inherit', fontSize: 14, fontWeight: 800, letterSpacing: '0.22em', cursor: 'pointer', borderRadius: 2,
              }}>
                {'>'} ./add-to-cart {p.name} x {String(qty).padStart(2, '0')}
              </button>
            )}

            {/* SPEC FOOTER */}
            <div style={{ marginTop: 14, padding: 12, border: '1px dashed rgba(255,255,255,0.18)', fontSize: 11, color: '#B8B8B8', lineHeight: 1.7 }}>
              <div style={{ color: '#00FF41' }}>$ ./merch-spec --sku={p.id}</div>
              <div>&nbsp;&nbsp;made to order. ships in 3-5 days.</div>
              {discount > 0 && <div>&nbsp;&nbsp;tier discount: {discount}% applied.</div>}
              <div>&nbsp;&nbsp;<span style={{ color: '#6E6E6E' }}>// wear the exploit. own the room.</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.MerchDetail = MerchDetail;
