// ProductDetail.jsx — full overlay with subscribe option
const ProductDetail = ({ 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 grinds = ['WHOLE BEAN', 'GROUND'];
  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'); }
  };

  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: package */}
          <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 }}>// PACKAGE</div>
            <div style={{ marginTop: 16, padding: 16, fontSize: 14, lineHeight: 1.8, background: `${p.accent}14`, border: `1px solid ${p.accent}55`, color: p.accent, flex: 1 }}>
              {p.log.map((l, i) => (<div key={i}>{'>'} {l}</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 }}>TASTING</div><div style={{ color: '#FFF', marginTop: 5, lineHeight: 1.55, fontSize: 12, letterSpacing: '0.06em' }}>{p.notes.join(' · ')}</div></div>
              <div><div style={{ color: '#BFBFBF', fontWeight: 600 }}>PROCESS</div><div style={{ color: '#FFF', marginTop: 5, fontSize: 12, letterSpacing: '0.06em' }}>{p.process}</div></div>
              <div><div style={{ color: '#BFBFBF', fontWeight: 600 }}>ORIGIN</div><div style={{ color: '#FFF', marginTop: 5, lineHeight: 1.55, fontSize: 12, letterSpacing: '0.06em' }}>{p.origin}</div></div>
              <div><div style={{ color: '#BFBFBF', fontWeight: 600 }}>STRENGTH</div><div style={{ marginTop: 5, color: p.accent, fontSize: 16 }}>{[1,2,3,4,5].map((i) => (<span key={i} style={{ opacity: i <= p.strength ? 1 : 0.2 }}>⚡</span>))}</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>NET WT. 12OZ (340G)</span>
            </div>
          </div>
          {/* right: buy */}
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.25em', color: '#BFBFBF', fontWeight: 600 }}>// /shop/{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.roast} · {p.notes[0]}</div>

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

            <div style={{ marginTop: 24, fontSize: 30, color: '#FFF', fontWeight: 800, lineHeight: 1 }}>
              ${p.price}<span style={{ fontSize: 13, color: '#BFBFBF', marginLeft: 8, letterSpacing: '0.1em', fontWeight: 600 }}>USD / 12OZ</span>
            </div>

            <div style={{ marginTop: 24 }}>
              <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 8 }}>{'>'} GRIND</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {grinds.map((g) => (
                  <button key={g} onClick={() => setGrind(g)} style={{
                    background: grind === g ? p.accent : 'transparent',
                    color: grind === g ? '#000' : '#B8B8B8',
                    border: `1px solid ${grind === g ? p.accent : 'rgba(255,255,255,0.18)'}`,
                    padding: '8px 12px', fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.15em', cursor: 'pointer', borderRadius: 2,
                  }}>{g}</button>
                ))}
              </div>
            </div>

            <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>

            <button onClick={() => { onAdd(p, qty, grind); }} 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} × {String(qty).padStart(2, '0')}
            </button>

            {/* subscribe section */}
            <div style={{ marginTop: 14, 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: '14px 16px',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                fontFamily: 'inherit', fontSize: 12, letterSpacing: '0.15em', cursor: 'pointer', color: '#B266FF', fontWeight: 700,
              }}>
                <span>{'>'} ./subscribe — save {subDiscount}%</span>
                <span style={{ fontSize: 11, color: '#BFBFBF' }}>{showSub ? '[ - ]' : '[ + ]'}</span>
              </button>

              {showSub && (
                <div style={{ padding: '0 16px 16px' }}>
                  <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 8 }}>{'>'} CADENCE</div>
                  <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
                    {cadenceOpts.map((c) => (
                      <button key={c.id} onClick={() => setSubCadence(c.id)} style={{
                        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 12px', fontFamily: 'inherit', fontSize: 10, letterSpacing: '0.12em', cursor: 'pointer', borderRadius: 2, fontWeight: 700,
                      }}>{c.label}</button>
                    ))}
                  </div>

                  <div style={{ fontSize: 10, letterSpacing: '0.22em', color: '#6E6E6E', marginBottom: 8 }}>{'>'} BAGS PER SHIPMENT</div>
                  <div style={{ display: 'inline-flex', border: '1px solid rgba(178,102,255,0.3)', marginBottom: 16 }}>
                    <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', cursor: 'pointer' }}>−</button>
                    <span style={{ padding: '8px 16px', color: '#FFF', minWidth: 40, textAlign: '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', cursor: 'pointer' }}>+</button>
                  </div>

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

                  {subStatus === 'LOGIN_REQUIRED' && (
                    <div style={{ padding: 10, border: '1px solid #FF8C42', color: '#FF8C42', fontSize: 11, marginBottom: 12, letterSpacing: '0.06em' }}>
                      // log in to subscribe
                    </div>
                  )}
                  {subStatus === 'SUCCESS' && (
                    <div style={{ padding: 10, border: '1px solid #00FF41', color: '#00FF41', fontSize: 11, marginBottom: 12, letterSpacing: '0.06em' }}>
                      // subscribed to {p.name}. manage in your account.
                    </div>
                  )}
                  {subStatus === 'ERROR' && (
                    <div style={{ padding: 10, border: '1px solid #FF3344', color: '#FF3344', fontSize: 11, marginBottom: 12, 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: '14px', fontFamily: 'inherit', fontSize: 13, fontWeight: 800, letterSpacing: '0.18em', cursor: 'pointer', borderRadius: 2,
                    opacity: subStatus === 'CREATING' ? 0.6 : 1,
                  }}>
                    {subStatus === 'CREATING' ? '// subscribing...' : subStatus === 'SUCCESS' ? '[ ✓ ] SUBSCRIBED' : `> ./subscribe ${p.name}`}
                  </button>

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

            <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' }}>$ ./brew-spec --sku={p.id}</div>
              <div>&nbsp;&nbsp;roasted to order. ships in 2 days.</div>
              <div>&nbsp;&nbsp;subscribe for {subDiscount}% off subscription shipments.</div>
              <div>&nbsp;&nbsp;<span style={{ color: '#6E6E6E' }}>// drink responsibly. pwn responsibly.</span></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ProductDetail = ProductDetail;
