// Modals: AuthModal, CartDrawer, RevealModal (simplified, no full lightning sequence)
const { useState: useStM, useEffect: useEfM, useRef: useRfM } = React;

function AuthModal({ open, onClose, onSignIn }) {
  const [mode, setMode] = useStM('signin');
  const [email, setEmail] = useStM('');
  const [pwd, setPwd] = useStM('');
  if (!open) return null;
  return (
    <div className="auth-modal open" style={{display:'flex',position:'fixed',inset:0,zIndex:9999,alignItems:'center',justifyContent:'center',padding:'1.5rem',background:'rgba(6,0,13,0.85)',backdropFilter:'blur(12px)'}} onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="auth-card" style={{background:'linear-gradient(135deg, var(--purple-900), var(--logo-bg))',border:'1px solid var(--border-gold)',borderRadius:20,padding:'2.2rem 2rem',maxWidth:440,width:'100%',textAlign:'center',position:'relative',boxShadow:'0 0 60px rgba(224,184,83,0.25)'}}>
        <button onClick={onClose} style={{position:'absolute',top:14,right:14,width:36,height:36,border:'1px solid var(--border-subtle)',background:'transparent',color:'var(--text-muted)',borderRadius:8,cursor:'pointer'}}>✕</button>
        <div style={{width:64,height:64,margin:'0 auto 1rem',borderRadius:16,background:'var(--logo-bg)',border:'1px solid var(--border-gold)',padding:3,boxShadow:'0 0 30px rgba(224,184,83,0.3)',overflow:'hidden'}}>
          <img src="assets/logo.png" alt="" style={{width:'100%',height:'100%',objectFit:'cover',borderRadius:13}} />
        </div>
        <h3 style={{fontFamily:'var(--font-display)',fontSize:'1.4rem',fontWeight:700,color:'var(--text-primary)',marginBottom:'0.4rem'}}>{mode==='signin' ? 'Welcome, traveler' : 'Begin your journey'}</h3>
        <p style={{fontFamily:'var(--font-magic)',fontStyle:'italic',color:'var(--text-secondary)',fontSize:'0.95rem',marginBottom:'1.4rem'}}>{mode==='signin' ? 'Sign in to access your vault and store credit.' : 'Create an account to track your pulls.'}</p>
        <div style={{display:'flex',gap:6,padding:6,background:'var(--glass-bg)',borderRadius:11,border:'1px solid var(--border-subtle)',marginBottom:'1.3rem'}}>
          {[['signin','Sign In'],['signup','Create Account']].map(([k,l]) => (
            <button key={k} onClick={() => setMode(k)} style={{flex:1,background: mode===k ? 'linear-gradient(135deg, var(--purple-700), var(--purple-600))' : 'transparent',border:'none',color: mode===k ? 'var(--gold-glow)' : 'var(--text-muted)',padding:'0.6rem',borderRadius:8,fontFamily:'var(--font-display)',fontSize:'0.72rem',fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',cursor:'pointer'}}>{l}</button>
          ))}
        </div>
        <form onSubmit={e => { e.preventDefault(); onSignIn({ email, name: email.split('@')[0] || 'Wizard' }); }} style={{display:'flex',flexDirection:'column',gap:10}}>
          {mode==='signup' && <input className="auth-input" placeholder="Display name" style={authInputStyle} />}
          <input type="email" placeholder="Email" value={email} onChange={e=>setEmail(e.target.value)} required style={authInputStyle} />
          <input type="password" placeholder="Password" value={pwd} onChange={e=>setPwd(e.target.value)} required style={authInputStyle} />
          {mode==='signin' && <div style={{textAlign:'right',marginTop:-4}}><a href="#" onClick={e=>e.preventDefault()} style={{fontFamily:'var(--font-magic)',fontSize:'0.85rem',color:'var(--purple-400)',fontStyle:'italic',textDecoration:'none'}}>Forgot password?</a></div>}
          <button type="submit" className="btn-primary" style={{marginTop:8,width:'100%',padding:'0.95rem'}}>✦ Enter the Realm</button>
        </form>
        <div style={{marginTop:'1.4rem',padding:'0.9rem',background:'var(--gold-alpha)',border:'1px dashed var(--border-gold)',borderRadius:10,fontFamily:'var(--font-magic)',fontStyle:'italic',fontSize:'0.85rem',color:'var(--gold-warm)'}}>
          ✦ Sign in to track your pulls, save your collection, and use store credit
        </div>
      </div>
    </div>
  );
}

const authInputStyle = {
  background: 'rgba(10,4,32,0.6)',
  border: '1px solid var(--border-mid)',
  borderRadius: 11,
  padding: '0.85rem 1.1rem',
  color: 'var(--text-primary)',
  fontFamily: 'var(--font-magic)',
  fontStyle: 'italic',
  fontSize: '1rem',
  outline: 'none',
  width: '100%',
};

function CartDrawer({ open, items, onClose, onRemove }) {
  const sub = items.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <>
      {open && <div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(6,0,13,0.7)',backdropFilter:'blur(8px)',zIndex:9998}} />}
      <aside style={{position:'fixed',top:0,right: open ? 0 : -460,bottom:0,width:'min(440px, 100vw)',background:'linear-gradient(180deg, var(--logo-bg), var(--purple-1000))',borderLeft:'1px solid var(--border-gold)',zIndex:9999,transition:'right 0.4s cubic-bezier(0.16,1,0.3,1)',display:'flex',flexDirection:'column',boxShadow:'-30px 0 80px rgba(0,0,0,0.5)'}}>
        <div style={{padding:'1.4rem 1.5rem',borderBottom:'1px solid var(--border-subtle)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{fontFamily:'var(--font-display)',fontSize:'1rem',fontWeight:700,color:'var(--text-primary)',letterSpacing:'0.04em'}}>Your Vault {items.length > 0 && <span style={{color:'var(--gold-warm)'}}>({items.length})</span>}</div>
          <button onClick={onClose} style={{background:'transparent',border:'1px solid var(--border-subtle)',color:'var(--text-muted)',width:34,height:34,borderRadius:8,cursor:'pointer'}}>✕</button>
        </div>
        <div style={{flex:1,overflowY:'auto',padding:'1rem 1.25rem'}}>
          {items.length === 0 ? (
            <div style={{textAlign:'center',padding:'3rem 1rem',color:'var(--text-muted)',fontFamily:'var(--font-magic)',fontStyle:'italic'}}>
              <div style={{fontSize:'3rem',marginBottom:'0.5rem'}}>⛁</div>
              <p>Your vault is empty.</p>
              <p style={{fontSize:'0.85rem',marginTop:'0.4rem'}}>Add some enchanted cards.</p>
            </div>
          ) : items.map(it => (
            <div key={it.id} style={{display:'flex',alignItems:'center',gap:12,padding:'0.8rem',borderRadius:10,background:'var(--glass-bg)',border:'1px solid var(--border-subtle)',marginBottom:8}}>
              <div style={{width:40,height:40,borderRadius:8,background:`radial-gradient(circle, ${window.WW_DATA.games[it.game].color}, var(--logo-bg))`,display:'flex',alignItems:'center',justifyContent:'center',fontSize:'1.4rem'}}>{window.WW_DATA.games[it.game].emoji}</div>
              <div style={{flex:1,minWidth:0}}>
                <div style={{fontFamily:'var(--font-display)',fontSize:'0.85rem',color:'var(--text-primary)',fontWeight:700}}>{it.name}</div>
                <div style={{fontFamily:'var(--font-magic)',fontStyle:'italic',fontSize:'0.78rem',color:'var(--text-muted)'}}>{it.set} · qty {it.qty}</div>
              </div>
              <span style={{fontFamily:'var(--font-display)',color:'var(--gold-glow)',fontWeight:700}}>${(it.price * it.qty).toFixed(2)}</span>
              <button onClick={() => onRemove(it.id)} style={{background:'transparent',border:'none',color:'var(--text-faint)',cursor:'pointer',fontSize:'1rem'}}>✕</button>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div style={{padding:'1.25rem 1.5rem',borderTop:'1px solid var(--border-subtle)'}}>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:'0.5rem',fontFamily:'var(--font-magic)',color:'var(--text-secondary)'}}><span>Subtotal</span><span>${sub.toFixed(2)}</span></div>
            <div style={{display:'flex',justifyContent:'space-between',marginBottom:'1rem',fontFamily:'var(--font-magic)',fontSize:'0.85rem',fontStyle:'italic',color:'var(--text-muted)'}}><span>Shipping</span><span>Calculated at checkout</span></div>
            <button className="btn-primary" style={{width:'100%',padding:'1rem'}}>✦ Checkout</button>
          </div>
        )}
      </aside>
    </>
  );
}

function RevealModal({ pack, onClose }) {
  const [phase, setPhase] = useStM('shake');   // shake → burst → reveal
  useEfM(() => {
    if (!pack) return;
    setPhase('shake');
    const t1 = setTimeout(() => setPhase('burst'), 900);
    const t2 = setTimeout(() => setPhase('reveal'), 1500);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [pack]);

  if (!pack) return null;
  const tier = window.WW_DATA.tierColors[pack.tier];
  const fakePull = {
    name: pack.tier === 'legendary' ? 'Black Lotus' : pack.tier === 'very-rare' ? 'Mox Sapphire' : pack.tier === 'rare' ? 'Foil Orcish Bowmasters' : 'Lightning Bolt',
    set: pack.tier === 'legendary' ? 'Beta · 1993' : 'Modern Horizons 3',
    value: pack.tier === 'legendary' ? 4250 : pack.tier === 'very-rare' ? 320 : pack.tier === 'rare' ? 38 : 4.50,
  };

  return (
    <div onClick={e => e.target === e.currentTarget && onClose()} style={{position:'fixed',inset:0,zIndex:10000,display:'flex',alignItems:'center',justifyContent:'center',padding:'1.5rem',background:'rgba(6,0,13,0.92)',backdropFilter:'blur(14px)'}}>
      <div style={{
        position:'relative',
        background:`radial-gradient(circle at 50% 0%, ${tier.cb}22, transparent 60%), linear-gradient(135deg, var(--purple-900), var(--logo-bg))`,
        border:`1px solid ${tier.c}`,
        borderRadius:20,
        padding:'2.5rem 2rem 2rem',
        maxWidth:460,
        width:'100%',
        textAlign:'center',
        boxShadow:`0 0 80px ${tier.c}66`,
        transform: phase === 'shake' ? 'scale(1)' : 'scale(1.02)',
        transition: 'transform 0.4s',
      }}>
        <button onClick={onClose} style={{position:'absolute',top:14,right:14,width:36,height:36,border:'1px solid var(--border-subtle)',background:'transparent',color:'var(--text-muted)',borderRadius:8,cursor:'pointer'}}>✕</button>

        {/* Orb stage */}
        <div style={{
          width: phase === 'reveal' ? 90 : 140,
          height: phase === 'reveal' ? 90 : 140,
          margin: '0 auto 1.25rem',
          borderRadius:'50%',
          background:`radial-gradient(circle at 35% 30%, ${tier.cb} 0%, ${tier.c} 35%, color-mix(in srgb, ${tier.c} 50%, var(--logo-bg)) 70%, var(--logo-bg) 100%)`,
          boxShadow:`0 0 ${phase === 'burst' ? 200 : 60}px ${tier.c}99, inset 0 -10px 20px rgba(0,0,0,0.4), inset 0 8px 16px ${tier.cb}88`,
          display:'flex',alignItems:'center',justifyContent:'center',
          fontFamily:'var(--font-display)',fontWeight:900,fontSize:'3rem',color:'var(--purple-1000)',
          animation: phase === 'shake' ? 'orbShake 0.15s infinite' : 'none',
          transition: 'all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1)',
        }}>{phase === 'reveal' ? '✦' : '?'}</div>

        {phase === 'reveal' ? (
          <>
            <div style={{fontFamily:'var(--font-display)',fontSize:'0.7rem',fontWeight:700,letterSpacing:'0.3em',textTransform:'uppercase',color:tier.cb,marginBottom:'0.4rem'}}>— {pack.tierLabel} PULL —</div>
            <h3 style={{fontFamily:'var(--font-display)',fontSize:'1.6rem',fontWeight:700,color:'var(--text-primary)',marginBottom:'0.6rem'}}>You conjured <span className="italic-gold">a {pack.tierLabel.toLowerCase()}</span>!</h3>
            <div style={{fontFamily:'var(--font-display)',fontSize:'1.25rem',color:'var(--text-primary)',marginBottom:'0.2rem',fontWeight:700}}>{fakePull.name}</div>
            <div style={{fontFamily:'var(--font-magic)',fontStyle:'italic',color:'var(--text-muted)',marginBottom:'1.2rem'}}>{fakePull.set}</div>
            <div style={{padding:'1rem',background:'var(--gold-alpha)',border:'1px solid var(--border-gold)',borderRadius:11,marginBottom:'1.2rem',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
              <span style={{fontFamily:'var(--font-magic)',fontStyle:'italic',color:'var(--text-secondary)'}}>Estimated value</span>
              <span style={{fontFamily:'var(--font-display)',fontSize:'1.4rem',fontWeight:700,color:'var(--gold-glow)'}}>${fakePull.value.toLocaleString()}</span>
            </div>
            <div style={{display:'flex',gap:8,justifyContent:'center'}}>
              <button onClick={onClose} className="btn-ghost" style={{fontSize:'0.7rem',padding:'0.7rem 1.1rem'}}>◈ Keep it</button>
              <button onClick={onClose} className="btn-primary" style={{fontSize:'0.7rem',padding:'0.7rem 1.1rem'}}>✦ Sell back ${Math.round(fakePull.value * 0.7)}</button>
            </div>
          </>
        ) : (
          <>
            <div style={{fontFamily:'var(--font-display)',fontSize:'0.72rem',fontWeight:700,letterSpacing:'0.3em',textTransform:'uppercase',color:tier.cb,marginBottom:'0.5rem'}}>{pack.tierLabel}</div>
            <div style={{fontFamily:'var(--font-display)',fontSize:'1.4rem',fontWeight:700,color:'var(--text-primary)',marginBottom:'0.4rem'}}>{pack.name}</div>
            <div style={{fontFamily:'var(--font-magic)',fontStyle:'italic',color:'var(--text-muted)'}}>{phase === 'shake' ? 'Channeling the rift…' : 'Burst!'}</div>
          </>
        )}
      </div>
      <style>{`@keyframes orbShake { 0% { transform: translateX(0) rotate(0); } 25% { transform: translateX(-3px) rotate(-2deg); } 50% { transform: translateX(3px) rotate(2deg); } 75% { transform: translateX(-2px) rotate(-1deg); } 100% { transform: translateX(0) rotate(0); } }`}</style>
    </div>
  );
}

Object.assign(window, { AuthModal, CartDrawer, RevealModal });
