// MobileMerchDetail.jsx — full-screen merch product overlay, tier-aware customization
const MobileMerchDetail = ({ 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 [handleText, setHandleText] = 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 requiredTierName = p.minTier != null && tiers[p.minTier] ? tiers[p.minTier].name : 'UNKNOWN';
  const requiredTierAccent = p.minTier != null && tiers[p.minTier] ? tiers[p.minTier].accent : '#FF3344';

  const merchDiscount = helpers.getMerchDiscount ? helpers.getMerchDiscount(spend) : 0;
  const discountedPrice = merchDiscount > 0 ? Math.round(p.price * (1 - merchDiscount / 100) * 100) / 100 : p.price;

  const tierIdx = helpers.getTierIndex ? helpers.getTierIndex(spend) : 0;
  const currentTier = tiers[tierIdx] || tiers[0];

  const RANK_PATCH_PRICE = 5;
  const HANDLE_PRINT_PRICE = 8;
  const unitPrice = discountedPrice
    + (rankPatch && canPatch ? RANK_PATCH_PRICE : 0)
    + (handlePrint && canHandle && handleText.trim() ? HANDLE_PRINT_PRICE : 0);
  const totalPrice = Math.round(unitPrice * qty * 100) / 100;

  const progress = locked && helpers.getProgress ? helpers.getProgress(spend) : null;

  React.useEffect(() => {
    setQty(1);
    setSelectedSize(p.sizes ? p.sizes[0] : null);
    setSelectedColor(p.colors ? p.colors[0] : null);
    setRankPatch(false);
    setHandlePrint(false);
    setHandleText('');
  }, [p.id]);

  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

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

  const meta = window.OBC_MERCH_LINE_META || {};
  const lineData = meta[p.line] ? { id: p.line, ...meta[p.line] } : null;

  return (
    <div
      style={{
        position: 'fixed', inset: 0, background: '#0A0A0A',
        zIndex: 100, display: 'flex', flexDirection: 'column',
        fontFamily: "'JetBrains Mono', monospace",
        animation: 'mobileMerchDetailSlideUp 200ms ease-out',
      }}
    >
      {/* CLOSE BAR */}
      <div style={{
        padding: '10px 16px', display: 'flex', alignItems: 'center',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        background: '#000', flexShrink: 0,
      }}>
        {lineData && (
          <span style={{
            padding: '3px 8px', border: '1px solid ' + lineData.color + '66',
            fontSize: 8, letterSpacing: '0.15em', color: lineData.color,
            fontWeight: 700, marginRight: 8,
          }}>
            {lineData.label}
          </span>
        )}
        <span style={{ fontSize: 10, color: '#A0A0A0', letterSpacing: '0.15em' }}>
          /merch/{p.id}
        </span>
        <button
          onClick={onClose}
          style={{
            marginLeft: 'auto', background: 'transparent',
            border: '1px solid rgba(255,255,255,0.2)', color: '#B8B8B8',
            padding: '6px 12px', fontFamily: 'inherit', fontSize: 11,
            letterSpacing: '0.12em', cursor: 'pointer', minHeight: 36,
          }}
        >
          [x]
        </button>
      </div>

      {/* BODY */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'auto', padding: '0 16px' }}>

        {/* IMAGE PLACEHOLDER */}
        <div style={{
          marginTop: 14, height: 200,
          background: `${p.accent}1A`, border: `1px solid ${p.accent}66`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{ fontSize: 80, opacity: 0.3, lineHeight: 1, color: p.accent, pointerEvents: 'none' }}>
            {p.glyph}
          </div>
          <div style={{
            fontSize: 10, letterSpacing: '0.2em', color: '#6E6E6E',
            fontWeight: 600, marginTop: 10,
          }}>
            // IMAGE PENDING
          </div>
        </div>

        {/* NAME + PRICE ROW */}
        <div style={{
          display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between',
          gap: 12, paddingTop: 14,
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h1 style={{
              fontSize: 28, fontWeight: 800, color: p.accent,
              letterSpacing: '0.02em', textTransform: 'uppercase',
              lineHeight: 1, margin: 0,
            }}>
              {p.name}
            </h1>
            <div style={{
              marginTop: 6, fontSize: 11, letterSpacing: '0.15em',
              color: '#A0A0A0', fontWeight: 700, textTransform: 'uppercase',
            }}>
              {p.type} &middot; {p.mitre || ''}
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            {merchDiscount > 0 ? (
              <div>
                <div style={{ fontSize: 14, color: '#6E6E6E', textDecoration: 'line-through', lineHeight: 1 }}>
                  ${p.price}
                </div>
                <div style={{ fontSize: 28, fontWeight: 800, color: '#FFF', lineHeight: 1, marginTop: 2 }}>
                  ${discountedPrice}
                </div>
                <div style={{ fontSize: 9, color: currentTier.accent, letterSpacing: '0.1em', marginTop: 4 }}>
                  {merchDiscount}% {currentTier.name}
                </div>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 28, fontWeight: 800, color: '#FFF', lineHeight: 1 }}>
                  ${p.price}
                </div>
                <div style={{ fontSize: 9, color: '#A0A0A0', letterSpacing: '0.1em', marginTop: 4 }}>
                  USD
                </div>
              </div>
            )}
          </div>
        </div>

        {/* TERMINAL LOG */}
        {p.log && p.log.length > 0 && (
          <div style={{
            marginTop: 12, padding: 12,
            background: p.accent + '1A', border: '1px solid ' + p.accent + '44',
            color: p.accent, fontSize: 11, lineHeight: 1.6,
          }}>
            {p.log.map((l, i) => (
              <div key={i}>{'>'} {l}</div>
            ))}
            <div style={{
              color: '#E0E0E0', fontSize: 9, letterSpacing: '0.12em',
              fontWeight: 600, marginTop: 6,
            }}>
              // exit 0<span style={{ background: p.accent, color: '#000', marginLeft: 4, padding: '0 3px' }}>_</span>
            </div>
          </div>
        )}

        {/* DESCRIPTION */}
        {p.description && (
          <div style={{
            marginTop: 10, fontSize: 13, lineHeight: 1.6,
            color: '#BFBFBF', letterSpacing: '0.02em',
          }}>
            {p.description}
          </div>
        )}

        {/* MATERIAL / WEIGHT / FEATURES */}
        <div style={{
          marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
        }}>
          <div>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 4 }}>
              MATERIAL
            </div>
            <div style={{ fontSize: 12, color: '#FFF', letterSpacing: '0.02em' }}>
              {p.material}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 4 }}>
              WEIGHT
            </div>
            <div style={{ fontSize: 12, color: '#FFF', letterSpacing: '0.02em' }}>
              {p.weight || '—'}
            </div>
          </div>
        </div>
        {p.features && p.features.length > 0 && (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 6 }}>
              {'>'} FEATURES
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {p.features.map((f, i) => (
                <span key={i} style={{
                  padding: '5px 10px', border: '1px solid ' + p.accent + '44',
                  color: p.accent, fontSize: 10, letterSpacing: '0.1em',
                  fontWeight: 600, background: p.accent + '14',
                }}>
                  {f}
                </span>
              ))}
            </div>
          </div>
        )}

        {/* SIZE SELECTOR */}
        {p.sizes && p.sizes.length > 0 && (
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 6 }}>
              {'>'} SIZE
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              {p.sizes.map((s) => (
                <button
                  key={s}
                  onClick={() => setSelectedSize(s)}
                  style={{
                    flex: 1, padding: '10px 6px',
                    background: selectedSize === s ? p.accent : 'transparent',
                    color: selectedSize === s ? '#000' : '#B8B8B8',
                    border: '1px solid ' + (selectedSize === s ? p.accent : 'rgba(255,255,255,0.18)'),
                    fontFamily: "'JetBrains Mono', monospace",
                    fontSize: 10, fontWeight: 700, letterSpacing: '0.08em',
                    cursor: 'pointer', borderRadius: 2, minHeight: 42,
                  }}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        )}

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

        {/* CUSTOMIZATION TOGGLES */}
        {(canPatch || canHandle) && (
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 8 }}>
              {'>'} CUSTOMIZATIONS
            </div>

            {canPatch && (
              <button
                onClick={() => setRankPatch(!rankPatch)}
                style={{
                  width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px', marginBottom: 6, cursor: 'pointer',
                  background: rankPatch ? p.accent + '14' : 'transparent',
                  border: '1px solid ' + (rankPatch ? p.accent : 'rgba(255,255,255,0.15)'),
                  fontFamily: "'JetBrains Mono', monospace", minHeight: 44,
                }}
              >
                <span style={{ fontSize: 12, color: rankPatch ? p.accent : '#6E6E6E', fontWeight: 700 }}>
                  {rankPatch ? '[*]' : '[ ]'}
                </span>
                <span style={{ flex: 1, textAlign: 'left', fontSize: 11, letterSpacing: '0.1em', color: rankPatch ? p.accent : '#B8B8B8', fontWeight: 700 }}>
                  RANK PATCH
                </span>
                <span style={{ fontSize: 10, color: currentTier.accent, letterSpacing: '0.08em' }}>
                  {currentTier.glyph} {currentTier.name}
                </span>
                <span style={{ fontSize: 11, color: '#A0A0A0', fontWeight: 700 }}>
                  +${RANK_PATCH_PRICE}
                </span>
              </button>
            )}

            {canHandle && (
              <div>
                <button
                  onClick={() => setHandlePrint(!handlePrint)}
                  style={{
                    width: '100%', display: 'flex', alignItems: 'center', gap: 10,
                    padding: '10px 12px', cursor: 'pointer',
                    background: handlePrint ? p.accent + '14' : 'transparent',
                    border: '1px solid ' + (handlePrint ? p.accent : 'rgba(255,255,255,0.15)'),
                    fontFamily: "'JetBrains Mono', monospace", minHeight: 44,
                  }}
                >
                  <span style={{ fontSize: 12, color: handlePrint ? p.accent : '#6E6E6E', fontWeight: 700 }}>
                    {handlePrint ? '[*]' : '[ ]'}
                  </span>
                  <span style={{ flex: 1, textAlign: 'left', fontSize: 11, letterSpacing: '0.1em', color: handlePrint ? p.accent : '#B8B8B8', fontWeight: 700 }}>
                    HANDLE EMBROIDERY
                  </span>
                  <span style={{ fontSize: 11, color: '#A0A0A0', fontWeight: 700 }}>
                    +${HANDLE_PRINT_PRICE}
                  </span>
                </button>
                {handlePrint && (
                  <input
                    type="text"
                    value={handleText}
                    onChange={(e) => setHandleText(e.target.value)}
                    placeholder="your handle"
                    maxLength={24}
                    style={{
                      width: '100%', marginTop: 6, padding: '10px 12px',
                      background: '#050505', border: '1px solid ' + p.accent + '44',
                      color: p.accent, fontFamily: "'JetBrains Mono', monospace",
                      fontSize: 12, letterSpacing: '0.08em', outline: 'none',
                      boxSizing: 'border-box', minHeight: 42,
                    }}
                  />
                )}
              </div>
            )}
          </div>
        )}

        {/* TIER LOCK BANNER */}
        {locked && progress && (
          <div style={{
            marginTop: 14, padding: '14px',
            border: '1px solid ' + requiredTierAccent + '66',
            background: requiredTierAccent + '0A',
          }}>
            <div style={{
              fontSize: 12, letterSpacing: '0.12em', color: '#FF3344',
              fontWeight: 700, marginBottom: 10,
            }}>
              {'>'} ACCESS DENIED — REQUIRES {requiredTierName}
            </div>
            <div style={{
              height: 4, background: 'rgba(255,255,255,0.1)', marginBottom: 8,
            }}>
              <div style={{
                height: '100%', background: requiredTierAccent,
                width: progress.percent + '%', transition: 'width 300ms',
              }}></div>
            </div>
            <div style={{ fontSize: 9, color: '#6E6E6E', letterSpacing: '0.1em' }}>
              ${progress.remaining} more to unlock · {progress.percent}% progress
            </div>
          </div>
        )}

        {/* spacer */}
        <div style={{ flex: 1, minHeight: 12 }} />

        {/* QUANTITY + ADD TO CART */}
        <div style={{ paddingBottom: 8 }}>
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginBottom: 10,
          }}>
            <div style={{ display: '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', fontSize: 16,
                  cursor: 'pointer', minHeight: 42,
                }}
              >-</button>
              <span style={{
                padding: '8px 12px', color: '#FFF', minWidth: 36,
                textAlign: 'center', fontSize: 14, fontWeight: 700,
                display: 'grid', placeItems: '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', fontSize: 16,
                  cursor: 'pointer', minHeight: 42,
                }}
              >+</button>
            </div>
          </div>

          <button
            onClick={handleAdd}
            disabled={locked}
            style={{
              width: '100%',
              background: locked ? 'transparent' : p.accent,
              color: locked ? '#FF3344' : '#000',
              border: '1px solid ' + (locked ? '#FF3344' : p.accent),
              padding: '14px',
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 12, fontWeight: 800, letterSpacing: '0.15em',
              cursor: locked ? 'not-allowed' : 'pointer',
              borderRadius: 2, minHeight: 48,
              opacity: locked ? 0.7 : 1,
            }}
          >
            {locked
              ? '> ACCESS DENIED'
              : `> ./add-to-cart ${p.name} x ${String(qty).padStart(2, '0')} — $${totalPrice}`}
          </button>
          {!locked && (
            <div style={{
              marginTop: 6, fontSize: 10, color: '#A0A0A0', letterSpacing: '0.1em',
              textAlign: 'center',
            }}>
              made to order · ships in 5-7 days
            </div>
          )}
        </div>
      </div>

      <style>{`
        @keyframes mobileMerchDetailSlideUp {
          from { transform: translateY(100%); opacity: 0; }
          to   { transform: translateY(0);    opacity: 1; }
        }
      `}</style>
    </div>
  );
};

window.MobileMerchDetail = MobileMerchDetail;
