// MobileProductDetail.jsx — full-screen product overlay, compact single-screen layout
const MobileProductDetail = ({ p, onClose, onAdd, user }) => {
  if (!p) return null;

  const [qty, setQty] = React.useState(1);
  const [grind, setGrind] = React.useState('WHOLE BEAN');
  const [showSub, setShowSub] = React.useState(false);
  const [subCadence, setSubCadence] = React.useState('MONTHLY');
  const [subQty, setSubQty] = React.useState(1);
  const [subStatus, setSubStatus] = React.useState(null);
  const cadenceOpts = window.OBC_SUB_CADENCE_OPTIONS || [];
  const subDiscount = window.OBC_SUB_DISCOUNT || 5;
  const subPrice = Math.round(p.price * (1 - subDiscount / 100) * 100) / 100;

  const handleSubscribe = async () => {
    if (!user) { setSubStatus('LOGIN_REQUIRED'); return; }
    setSubStatus('CREATING');
    try {
      const res = await window.OBC_API.createSubscription(p.id, subCadence, subQty, grind);
      if (res.ok !== false) setSubStatus('SUCCESS');
      else setSubStatus('ERROR');
    } catch { setSubStatus('ERROR'); }
  };

  React.useEffect(() => { setQty(1); setGrind('WHOLE BEAN'); setShowSub(false); setSubStatus(null); setSubCadence('MONTHLY'); setSubQty(1); }, [p.id]);
  React.useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  const meta = window.OBC_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: 'mobileDetailSlideUp 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' }}>
          /shop/{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 — flex column to fill remaining space */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'auto', padding: '0 16px' }}>

        {/* 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: '#FFF',
              letterSpacing: '0.02em', textTransform: 'uppercase',
              lineHeight: 1, margin: 0,
            }}>
              {p.name}
            </h1>
            <div style={{
              marginTop: 6, fontSize: 11, letterSpacing: '0.15em',
              color: p.accent, fontWeight: 700, textTransform: 'uppercase',
            }}>
              {p.roast}
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <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 / 12OZ
            </div>
          </div>
        </div>

        {/* TERMINAL LOG + SVG WATERMARK */}
        <div style={{
          marginTop: 12, padding: 12, height: 130,
          background: p.accent + '1A', border: '1px solid ' + p.accent + '66',
          color: p.accent, fontSize: 11, lineHeight: 1.6, position: 'relative',
          overflow: 'hidden', display: 'flex', flexDirection: 'column',
        }}>
          <img
            src={'assets/sku/' + p.id + '.svg'}
            alt=""
            style={{
              position: 'absolute', right: 8, bottom: 8, width: 64, height: 64,
              opacity: 0.18, pointerEvents: 'none',
            }}
          />
          {p.log && p.log.map((l, i) => (
            <div key={i} style={{ position: 'relative' }}>{'>'} {l}</div>
          ))}
          <div style={{ flex: 1 }} />
          <div style={{
            color: '#E0E0E0', fontSize: 9, letterSpacing: '0.12em',
            fontWeight: 600, position: 'relative',
          }}>
            // 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>
        )}

        {/* TASTING NOTES — 2 per row */}
        <div style={{ marginTop: 12 }}>
          <div style={{
            fontSize: 10, letterSpacing: '0.18em', color: '#A0A0A0',
            fontWeight: 700, marginBottom: 8,
          }}>
            {'>'} TASTING NOTES
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {p.notes.map((note, i) => (
              <span key={i} style={{
                padding: '6px 12px', border: '1px solid ' + p.accent + '44',
                color: p.accent, fontSize: 11, letterSpacing: '0.1em',
                fontWeight: 600, background: p.accent + '14', textAlign: 'center',
              }}>
                {note}
              </span>
            ))}
          </div>
        </div>

        {/* METADATA — 2-col grid */}
        <div style={{
          marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12,
        }}>
          {[
            { label: 'ORIGIN', value: p.origin },
            { label: 'PROCESS', value: p.process },
            { label: 'STRENGTH', value: null },
            { label: 'WEIGHT', value: '12OZ' },
          ].map((m) => (
            <div key={m.label}>
              <div style={{ fontSize: 9, letterSpacing: '0.18em', color: '#A0A0A0', fontWeight: 700, marginBottom: 4 }}>
                {m.label}
              </div>
              {m.label === 'STRENGTH' ? (
                <div style={{ color: p.accent, fontSize: 13 }}>
                  {[1,2,3,4,5].map((i) => (
                    React.createElement('span', { key: i, style: { opacity: i <= p.strength ? 1 : 0.2 } }, '⚡')
                  ))}
                </div>
              ) : (
                <div style={{
                  fontSize: 12, color: '#FFF', letterSpacing: '0.02em',
                }}>
                  {m.value}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* GRIND + QUANTITY — single row */}
        <div style={{
          marginTop: 14, display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{ display: 'flex', gap: 4, flex: 1 }}>
            {['WHOLE BEAN', 'GROUND'].map((g) => (
              <button
                key={g}
                onClick={() => setGrind(g)}
                style={{
                  flex: 1, padding: '10px 6px',
                  background: grind === g ? p.accent : 'transparent',
                  color: grind === g ? '#000' : '#B8B8B8',
                  border: '1px solid ' + (grind === g ? 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,
                }}
              >
                {g}
              </button>
            ))}
          </div>
          <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>

        {/* spacer pushes add button to bottom when content is short */}
        <div style={{ flex: 1, minHeight: 12 }} />

        {/* ADD-TO-CART */}
        <div style={{ paddingBottom: 8 }}>
          <button
            onClick={() => { onAdd(p, qty, grind); }}
            style={{
              width: '100%', background: p.accent, color: '#000',
              border: '1px solid ' + p.accent, padding: '14px',
              fontFamily: "'JetBrains Mono', monospace",
              fontSize: 12, fontWeight: 800, letterSpacing: '0.15em',
              cursor: 'pointer', borderRadius: 2, minHeight: 48,
            }}
          >
            {'>'} ./add-to-cart {p.name} x {String(qty).padStart(2, '0')} &mdash; ${p.price * qty}
          </button>
          <div style={{
            marginTop: 6, fontSize: 10, color: '#A0A0A0', letterSpacing: '0.1em',
            textAlign: 'center',
          }}>
            roasted to order · ships in 2 days
          </div>
        </div>

        {/* SUBSCRIBE SECTION */}
        <div style={{
          marginBottom: 16, border: '1px solid rgba(178,102,255,0.3)',
          background: showSub ? 'rgba(178,102,255,0.04)' : 'transparent',
        }}>
          <button onClick={() => setShowSub(!showSub)} style={{
            width: '100%', background: 'transparent', border: 'none', padding: '12px 14px',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: '0.12em',
            cursor: 'pointer', color: '#B266FF', fontWeight: 700, minHeight: 44,
          }}>
            <span>{'>'} ./subscribe — save {subDiscount}%</span>
            <span style={{ fontSize: 11, color: '#BFBFBF' }}>{showSub ? '[ - ]' : '[ + ]'}</span>
          </button>

          {showSub && (
            <div style={{ padding: '0 14px 14px' }}>
              <div style={{ fontSize: 9, letterSpacing: '0.2em', color: '#6E6E6E', marginBottom: 6 }}>{'>'} CADENCE</div>
              <div style={{ display: 'flex', gap: 4, marginBottom: 12 }}>
                {cadenceOpts.map((c) => (
                  <button key={c.id} onClick={() => setSubCadence(c.id)} style={{
                    flex: 1, background: subCadence === c.id ? '#B266FF' : 'transparent',
                    color: subCadence === c.id ? '#000' : '#B8B8B8',
                    border: '1px solid ' + (subCadence === c.id ? '#B266FF' : 'rgba(255,255,255,0.18)'),
                    padding: '8px 4px', fontFamily: "'JetBrains Mono', monospace",
                    fontSize: 9, letterSpacing: '0.08em', cursor: 'pointer', borderRadius: 2,
                    fontWeight: 700, minHeight: 38,
                  }}>{c.label}</button>
                ))}
              </div>

              <div style={{ fontSize: 9, letterSpacing: '0.2em', color: '#6E6E6E', marginBottom: 6 }}>{'>'} BAGS PER SHIPMENT</div>
              <div style={{ display: 'inline-flex', border: '1px solid rgba(178,102,255,0.3)', marginBottom: 12 }}>
                <button onClick={() => setSubQty(Math.max(1, subQty - 1))} style={{
                  background: 'transparent', color: '#B8B8B8', border: 'none',
                  borderRight: '1px solid rgba(178,102,255,0.3)',
                  padding: '8px 14px', fontFamily: 'inherit', fontSize: 16,
                  cursor: 'pointer', minHeight: 38,
                }}>-</button>
                <span style={{
                  padding: '8px 12px', color: '#FFF', minWidth: 36,
                  textAlign: 'center', fontSize: 14, fontWeight: 700,
                  display: 'grid', placeItems: 'center',
                }}>{subQty}</span>
                <button onClick={() => setSubQty(Math.min(4, subQty + 1))} style={{
                  background: 'transparent', color: '#B8B8B8', border: 'none',
                  borderLeft: '1px solid rgba(178,102,255,0.3)',
                  padding: '8px 14px', fontFamily: 'inherit', fontSize: 16,
                  cursor: 'pointer', minHeight: 38,
                }}>+</button>
              </div>

              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
                <div>
                  <span style={{ fontSize: 20, fontWeight: 800, color: '#B266FF' }}>${subPrice}</span>
                  <span style={{ fontSize: 11, color: '#BFBFBF', marginLeft: 4 }}>/ bag</span>
                  <span style={{ fontSize: 10, color: '#9A9A9A', marginLeft: 6, textDecoration: 'line-through' }}>${p.price}</span>
                </div>
                <span style={{ fontSize: 10, color: '#B266FF', letterSpacing: '0.1em' }}>x{subQty} = ${(subPrice * subQty).toFixed(2)}</span>
              </div>

              {subStatus === 'LOGIN_REQUIRED' && (
                <div style={{ padding: 8, border: '1px solid #FF8C42', color: '#FF8C42', fontSize: 10, marginBottom: 10, letterSpacing: '0.06em' }}>
                  // log in to subscribe
                </div>
              )}
              {subStatus === 'SUCCESS' && (
                <div style={{ padding: 8, border: '1px solid #00FF41', color: '#00FF41', fontSize: 10, marginBottom: 10, letterSpacing: '0.06em' }}>
                  // subscribed to {p.name}. manage in account.
                </div>
              )}
              {subStatus === 'ERROR' && (
                <div style={{ padding: 8, border: '1px solid #FF3344', color: '#FF3344', fontSize: 10, marginBottom: 10, letterSpacing: '0.06em' }}>
                  // subscription failed. try again.
                </div>
              )}

              <button onClick={handleSubscribe} disabled={subStatus === 'CREATING' || subStatus === 'SUCCESS'} style={{
                width: '100%', background: subStatus === 'SUCCESS' ? 'transparent' : '#B266FF',
                color: subStatus === 'SUCCESS' ? '#00FF41' : '#000',
                border: '1px solid ' + (subStatus === 'SUCCESS' ? '#00FF41' : '#B266FF'),
                padding: '12px', fontFamily: "'JetBrains Mono', monospace",
                fontSize: 11, fontWeight: 800, letterSpacing: '0.15em',
                cursor: 'pointer', borderRadius: 2, minHeight: 44,
                opacity: subStatus === 'CREATING' ? 0.6 : 1,
              }}>
                {subStatus === 'CREATING' ? '// subscribing...' : subStatus === 'SUCCESS' ? '[ ✓ ] SUBSCRIBED' : '> ./subscribe ' + p.name}
              </button>

              <div style={{ marginTop: 8, fontSize: 9, color: '#9A9A9A', lineHeight: 1.6, textAlign: 'center' }}>
                // {subDiscount}% off each subscription shipment · +12h early access · cancel anytime
              </div>
            </div>
          )}
        </div>
      </div>

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

window.MobileProductDetail = MobileProductDetail;
