const { useState, useEffect, useRef } = React;

// ── Stripe ────────────────────────────────────────────────────
const STRIPE_KEY = 'pk_live_51TP436Le73F2og81ZJej0aJQNLMOlgNFH0lBeTsXIuzfvxbM8kkwnURbNnge8ecaEsDl2OHKeHJk5l7V41exuZS700D69UAs8y';
let stripeInstance = null;
function getStripe() {
  if (!stripeInstance && window.Stripe) stripeInstance = window.Stripe(STRIPE_KEY);
  return stripeInstance;
}

// ── Pass catalogue ────────────────────────────────────────────
const PASS_LIMITS = {
  'transmission-vip':   { total: 75,   sold: 0 },
  'sounds-brown-eyes':  { total: 100,  sold: 0 },
  'sounds-silhouette':  { total: 100,  sold: 0 },
  'sounds-take-my-time':{ total: 100,  sold: 0 },
  'fan-club':           { total: 1000, sold: 0 },
};

function getPassAvailability(passId) {
  const limit = PASS_LIMITS[passId];
  if (!limit) return { limited: false };
  const remaining = limit.total - limit.sold;
  return { limited: true, total: limit.total, sold: limit.sold, remaining, soldOut: remaining <= 0 };
}
const PASSES = {
  'transmission-vip': {
    id: 'transmission-vip',
    name: 'Transmission EP Content Pass',
    price: 20.00,
    artwork: 'uploads/Transmission Artwork no title.jpg',
    description: 'Unlock early access to the Transmission EP — all five tracks streamed in full, exclusive behind-the-scenes content, and first access to future FonDeW releases.',
    contentLabel: 'Transmission EP',
    perks: [
      'Full EP stream — all 5 tracks',
      'Exclusive behind-the-scenes content',
      'First access to future releases',
      'VIP community access',
    ],
  },
  'sounds-brown-eyes': {
    id: 'sounds-brown-eyes', name: 'Brown Eyes Content Pass', price: 20.00,
    contentLabel: 'Brown Eyes', artwork: 'uploads/The Sounds EP artwork.png',
    description: 'Unlock exclusive content for Brown Eyes — lyric video and more.',
    perks: ['Brown Eyes exclusive content'],
  },
  'sounds-silhouette': {
    id: 'sounds-silhouette', name: 'Silhouette Content Pass', price: 20.00,
    contentLabel: 'Silhouette', artwork: 'uploads/The Sounds EP artwork.png',
    description: 'Unlock exclusive content for Silhouette — lyric video, art timelapse, and 5 artwork variations.',
    perks: ['Silhouette lyric video', 'Art timelapse', '5 artwork variations'],
  },
  'sounds-take-my-time': {
    id: 'sounds-take-my-time', name: 'Take My Time Content Pass', price: 20.00,
    contentLabel: 'Take My Time', artwork: 'uploads/The Sounds EP artwork.png',
    description: 'Unlock exclusive content for Take My Time — lyric video, art timelapse, and 4 artwork variations.',
    perks: ['Take My Time lyric video', 'Art timelapse', '4 artwork variations'],
  },
  'fan-club': {
    id: 'fan-club', name: 'The Burrow Club Pass', price: 15.00,
    contentLabel: 'The Burrow Club', artwork: 'uploads/Club Pass v2 art.png',
    description: 'Exclusive access to FonDeW\'s inner circle. Members-only content, early releases, and more.',
    perks: ['Members-only content', 'Early access to releases', 'Behind the scenes', 'VIP community'],
  },
};

// ── Pass Purchase Modal ───────────────────────────────────────
function PassModal({ passId, onClose, onBack }) {
  const { user, addPass, hasPass, openModal } = useAuth();
  const pass = PASSES[passId];
  const [step, setStep] = useState('details');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [cardName, setCardName] = useState('');
  const cardRef = useRef(null);
  const cardElementRef = useRef(null);
  const overlayRef = useRef(null);

  useEffect(() => {
    if (!user) { onClose(); openModal('signin'); }
  }, [user]);

  // Mount Stripe Card Element when payment step shown
  useEffect(() => {
    if (step !== 'payment') return;
    const stripe = getStripe();
    if (!stripe || !cardRef.current) return;
    const elements = stripe.elements();
    const card = elements.create('card', {
      style: {
        base: {
          color: '#fff',
          fontFamily: "'Barlow', sans-serif",
          fontSize: '15px',
          '::placeholder': { color: 'rgba(255,255,255,0.3)' },
        },
        invalid: { color: '#f87171' },
      },
    });
    card.mount(cardRef.current);
    cardElementRef.current = card;
    return () => { card.destroy(); cardElementRef.current = null; };
  }, [step]);

  const handlePurchase = async e => {
    e.preventDefault();
    setError('');
    setLoading(true);
    const stripe = getStripe();
    if (!stripe || !cardElementRef.current) {
      // Stripe not loaded — simulate for testing
      await new Promise(r => setTimeout(r, 1500));
      addPass({ id: pass.id, name: pass.name, price: pass.price });
      setLoading(false); setStep('success'); return;
    }
    const { paymentMethod, error: stripeError } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElementRef.current,
      billing_details: { name: cardName },
    });
    if (stripeError) {
      setError(stripeError.message);
      setLoading(false); return;
    }
    // TODO: Send paymentMethod.id to backend to create + confirm PaymentIntent
    // For now simulate success — replace with real backend call at launch
    await new Promise(r => setTimeout(r, 800));
    addPass({ id: pass.id, name: pass.name, price: pass.price });
    setLoading(false); setStep('success');
  };

  // Already owns pass — show wallet view not error
  if (hasPass(passId)) return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(8px)' }}>
      <div className="liquid-glass" style={{ borderRadius: 24, padding: '40px 32px', width: '100%', maxWidth: 400, textAlign: 'center' }} onClick={e => e.stopPropagation()}>
        <div style={{ fontSize: '3rem', marginBottom: 16 }}>✅</div>
        <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.6rem', color: '#fff', marginBottom: 12 }}>You already have access!</h2>
        <p style={{ color: 'rgba(255,255,255,0.45)', fontSize: '0.85rem', marginBottom: 24 }}>Your {pass.name} is active. Scroll down to access the {pass.contentLabel}.</p>
        <button className="btn-accent" onClick={onClose} style={{ padding: '10px 28px' }}>Got it</button>
      </div>
    </div>
  );

  return (
    <div ref={overlayRef} onClick={e => e.target === overlayRef.current && onClose()}
      style={{ position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(0,0,0,0.8)', backdropFilter: 'blur(10px)' }}>
      <div className="liquid-glass" style={{ borderRadius: 24, padding: '36px 32px', width: '100%', maxWidth: 480, position: 'relative', maxHeight: '90vh', overflowY: 'auto' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, background: 'none', border: 'none', color: 'rgba(255,255,255,0.4)', fontSize: '1.2rem', cursor: 'pointer' }}>✕</button>
        {onBack && step === 'details' && <button onClick={onBack} style={{ position: 'absolute', top: 18, left: 16, background: 'none', border: 'none', color: 'rgba(255,255,255,0.5)', fontSize: '0.82rem', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="15 18 9 12 15 6"/></svg> Back
        </button>}

        {step === 'success' ? (
          /* ── Success ── */
          <div style={{ textAlign: 'center', padding: '16px 0' }}>
            <div style={{ fontSize: '3.5rem', marginBottom: 16 }}>🎉</div>
            <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.8rem', color: '#fff', marginBottom: 12 }}>Purchase complete.</h2>
            <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.88rem', lineHeight: 1.6, marginBottom: 28 }}>
              Your <strong style={{ color: 'var(--accent)' }}>{pass.name}</strong> is now in your wallet. You may now access the {pass.contentLabel} content.
            </p>
            <button className="btn-accent" onClick={onClose} style={{ padding: '11px 32px', fontSize: '0.9rem' }}>
              Access {pass.contentLabel} →
            </button>
          </div>

        ) : step === 'payment' ? (
          /* ── Payment ── */
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
              <button onClick={() => setStep('details')} style={{ background: 'none', border: 'none', color: 'rgba(255,255,255,0.4)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontSize: '0.8rem' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="15 18 9 12 15 6"/></svg> Back
              </button>
              <h3 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.3rem', color: '#fff' }}>Checkout</h3>
            </div>

            {/* Order summary */}
            <div className="liquid-glass" style={{ borderRadius: 14, padding: '14px 16px', marginBottom: 24, display: 'flex', alignItems: 'center', gap: 14 }}>
              <img src={pass.artwork} alt={pass.name} style={{ width: 48, height: 48, borderRadius: 8, objectFit: 'cover' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, fontSize: '0.88rem', color: '#fff' }}>{pass.name}</div>
                <div style={{ fontSize: '0.75rem', color: 'rgba(255,255,255,0.4)', marginTop: 2 }}>One-time purchase</div>
              </div>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.3rem', color: 'var(--accent)' }}>${pass.price.toFixed(2)}</div>
            </div>

            <form onSubmit={handlePurchase} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Name on Card</label>
                <input className="glass-input" type="text" placeholder="Full name" required value={cardName} onChange={e => setCardName(e.target.value)} />
              </div>
              <div>
                <label style={{ display: 'block', fontSize: '0.72rem', color: 'rgba(255,255,255,0.4)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Card Details</label>
                <div ref={cardRef} style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 12, padding: '14px 16px' }} />
              </div>
              {error && <div style={{ fontSize: '0.8rem', color: '#f87171', padding: '8px 12px', background: 'rgba(248,113,113,0.1)', borderRadius: 8, border: '1px solid rgba(248,113,113,0.2)' }}>{error}</div>}
              <button type="submit" className="btn-accent" disabled={loading}
                style={{ width: '100%', justifyContent: 'center', padding: '13px', fontSize: '0.92rem', marginTop: 4, opacity: loading ? 0.7 : 1 }}>
                {loading ? (
                  <span style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center' }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ animation: 'spin 1s linear infinite' }}><path d="M21 12a9 9 0 11-6.219-8.56"/></svg>
                    Processing...
                  </span>
                ) : `Pay $${pass.price.toFixed(2)}`}
              </button>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 4 }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
                <span style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.3)' }}>Secured by Stripe · SSL encrypted</span>
              </div>
            </form>
          </>

        ) : (
          /* ── Details ── */
          <>
            <div style={{ borderRadius: 16, overflow: 'hidden', marginBottom: 24, position: 'relative' }}>
              <img src={pass.artwork} alt={pass.name} style={{ width: '100%', display: 'block', maxHeight: 200, objectFit: 'cover' }} />
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(0,0,0,0.6) 0%, transparent 50%)' }} />
              <div style={{ position: 'absolute', bottom: 14, left: 16 }}>
                <div className="section-badge" style={{ fontSize: '0.65rem' }}>Access Pass</div>
              </div>
            </div>

            <h2 style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '1.7rem', color: '#fff', marginBottom: 8, letterSpacing: '-0.5px' }}>
              {pass.id === 'transmission-vip'
                ? <>Transmission <span style={{ fontSize: '0.22em', letterSpacing: '0.05em', verticalAlign: 'baseline', opacity: 0.7 }}>EP</span></>
                : pass.id === 'sounds-brown-eyes' ? 'Brown Eyes'
                : pass.id === 'sounds-silhouette' ? 'Silhouette'
                : pass.id === 'sounds-take-my-time' ? 'Take My Time'
                : pass.name}
            </h2>
            <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '0.85rem', lineHeight: 1.65, marginBottom: 16 }}>{pass.description}</p>

            {/* Availability */}
            {(() => {
              const avail = getPassAvailability(pass.id);
              if (!avail.limited) return null;
              const pct = ((avail.total - avail.remaining) / avail.total) * 100;
              return (
                <div style={{ marginBottom: 24 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.72rem', marginBottom: 6 }}>
                    <span style={{ color: 'rgba(255,255,255,0.4)' }}>Limited Edition · {avail.total} passes total</span>
                    <span style={{ color: avail.remaining <= 10 ? '#f87171' : 'var(--accent)', fontWeight: 600 }}>{avail.remaining} remaining</span>
                  </div>
                  <div style={{ height: 4, background: 'rgba(255,255,255,0.08)', borderRadius: 2 }}>
                    <div style={{ height: '100%', width: `${pct}%`, background: avail.remaining <= 10 ? '#f87171' : 'var(--accent)', borderRadius: 2, transition: 'width 0.5s ease' }} />
                  </div>
                </div>
              );
            })()}

            <div style={{ marginBottom: 28 }}>
              <div style={{ fontSize: '0.72rem', fontWeight: 600, color: 'rgba(255,255,255,0.3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 12 }}>What's included</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {pass.perks.map((p, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'rgba(201,168,76,0.15)', border: '1px solid rgba(201,168,76,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg>
                    </div>
                    <span style={{ fontSize: '0.85rem', color: 'rgba(255,255,255,0.7)' }}>{p}</span>
                  </div>
                ))}
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 0', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
              <div>
                <div style={{ fontSize: '0.72rem', color: 'rgba(255,255,255,0.3)', marginBottom: 2 }}>One-time purchase</div>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontStyle: 'italic', fontSize: '2rem', color: '#fff' }}>${pass.price.toFixed(2)}</div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                <button className="btn-accent" onClick={() => setStep('payment')} style={{ padding: '12px 28px', fontSize: '0.92rem' }}>
                  🔑 Get Pass
                </button>
              </div>
            </div>
          </>
        )}
      </div>
      <style>{`
        @keyframes popIn { 0%{transform:scale(0.5);opacity:0} 70%{transform:scale(1.1)} 100%{transform:scale(1);opacity:1} }
        @keyframes spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

// ── VIP Button for Transmission section ───────────────────────
function TransmissionVipContent({ compact }) {
  const { user, hasPass, openModal } = useAuth();
  const [showPurchase, setShowPurchase] = useState(false);
  const unlocked = hasPass('transmission-vip');

  const handleVip = e => {
    if (e) e.preventDefault();
    if (unlocked) { window.location.href = 'transmission.html'; return; }
    // LAUNCH TONIGHT — temporarily disabled
    alert('Access passes go live tonight! Check back soon.');
  };

  return (
    <>
      <button
        onClick={handleVip}
        style={{ padding: '5px 12px', borderRadius: 9999, background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.10)', color: '#fff', fontSize: '0.75rem', fontWeight: 500, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        {unlocked ? 'Explore' : '🔑 VIP Access'}
      </button>
      {showPurchase && ReactDOM.createPortal(
        <PassModal passId="transmission-vip" onClose={() => setShowPurchase(false)} />,
        document.body
      )}
    </>
  );
}

Object.assign(window, { PassModal, TransmissionVipContent, PASSES });
