// pages-extra.jsx — CartPage, LoginPage, SearchPage, CategoryPage, NotFoundPage
// ALL wired to real FF_API — no FF_PRODUCTS / FF_ORDERS mock data
const { useState: useStateX, useEffect: useEffectX, useMemo: useMemoX } = React;

// ─── CART PAGE ────────────────────────────────────────────────────────────────
function CartPage({ cart, updateQty, removeItem, goto, user }) {
  const subtotal = cart.reduce((s, i) => s + (parseInt(i.price)||0) * (parseInt(i.qty)||0), 0);
  const shipping  = subtotal >= 50000 ? 0 : 4900;
  const total     = subtotal + shipping;

  if (cart.length === 0) return (
    <main style={{ maxWidth:640, margin:'80px auto', padding:24, textAlign:'center' }}>
      <div style={{ fontSize:72 }}>🛍️</div>
      <h1 className="ff-display" style={{ fontSize:40, marginTop:12 }}>Your bag is empty</h1>
      <p style={{ color:'var(--ff-muted)', marginTop:8, fontSize:16 }}>You haven't added anything yet. The good stuff awaits.</p>
      <div style={{ display:'flex', gap:10, justifyContent:'center', marginTop:24 }}>
        <button className="ff-btn ff-btn--primary" onClick={()=>goto({page:'shop'})}>Shop now <Icon.Arrow/></button>
        <button className="ff-btn" onClick={()=>goto({page:'shop', filter:'viral'})}>See viral picks</button>
      </div>
    </main>
  );

  return (
    <main style={{ maxWidth:1100, margin:'0 auto', padding:'32px 24px 80px' }}>
      <div style={{ fontSize:13, color:'var(--ff-muted)', marginBottom:8 }}>
        <a onClick={()=>goto({page:'home'})} style={{ cursor:'pointer' }}>Home</a> › Cart
      </div>
      <h1 className="ff-display" style={{ fontSize:48, marginBottom:28 }}>Your bag ({cart.length})</h1>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 340px', gap:32 }} className="ff-shop-grid">
        {/* Items */}
        <div style={{ display:'grid', gap:14 }}>
          {cart.map(item => {
            const price = parseInt(item.price)||0;
            const qty   = parseInt(item.qty)||1;
            return (
              <div key={item.product_id} className="ff-card" style={{ padding:16, display:'flex', gap:16, alignItems:'center' }}>
                <div style={{ width:88, height:88, borderRadius:12, overflow:'hidden', flexShrink:0, border:'var(--ff-border)' }}>
                  {item.image ? (
                    <img src={item.image} alt={item.name} style={{ width:'100%', height:'100%', objectFit:'cover' }}/>
                  ) : (
                    <ProductArt product={{ id:item.product_id, name:item.name, cat:'home', swatch:item.swatch||'#FFC7A8' }} ratio="1/1" size="sm"/>
                  )}
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:700, fontSize:16 }}>{item.name}</div>
                  <div style={{ fontSize:13, color:'var(--ff-muted)', marginTop:2 }}>{fmtINR(price)} each</div>
                  {item.stock <= 5 && <div style={{ fontSize:12, color:'var(--ff-accent)', marginTop:2 }}>Only {item.stock} left!</div>}
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:10 }}>
                    <div className="ff-card" style={{ display:'flex', alignItems:'center', padding:'2px 4px', gap:0, boxShadow:'none' }}>
                      <button onClick={()=>updateQty(item.product_id, qty-1)} style={{ padding:'6px 10px', fontWeight:700, fontSize:16 }}>−</button>
                      <span style={{ minWidth:28, textAlign:'center', fontWeight:700 }}>{qty}</span>
                      <button onClick={()=>updateQty(item.product_id, qty+1)} style={{ padding:'6px 10px', fontWeight:700, fontSize:16 }}>+</button>
                    </div>
                    <button onClick={()=>removeItem(item.product_id)} style={{ fontSize:12, color:'var(--ff-muted)', marginLeft:8 }}>Remove</button>
                  </div>
                </div>
                <div style={{ fontFamily:"'Space Grotesk',sans-serif", fontWeight:700, fontSize:18, flexShrink:0 }}>
                  {fmtINR(price * qty)}
                </div>
              </div>
            );
          })}
        </div>

        {/* Summary */}
        <div>
          <div className="ff-card" style={{ padding:22, position:'sticky', top:110 }}>
            <h2 className="ff-display" style={{ fontSize:22, marginBottom:16 }}>Order summary</h2>
            <div style={{ display:'grid', gap:10, marginBottom:16 }}>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}>
                <span>Subtotal ({cart.length} items)</span><span>{fmtINR(subtotal)}</span>
              </div>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}>
                <span>Shipping</span>
                <span style={{ color: shipping===0 ? 'var(--ff-teal)' : 'inherit' }}>
                  {shipping === 0 ? 'Free 🎉' : fmtINR(shipping)}
                </span>
              </div>
              {shipping > 0 && (
                <div style={{ fontSize:12, color:'var(--ff-muted)', padding:'8px 12px', background:'var(--ff-lime)', borderRadius:8 }}>
                  Add {fmtINR(50000 - subtotal)} more for free shipping
                </div>
              )}
              <div style={{ borderTop:'var(--ff-border)', paddingTop:10, display:'flex', justifyContent:'space-between', fontWeight:700, fontSize:18 }}>
                <span>Total</span><span>{fmtINR(total)}</span>
              </div>
            </div>
            <button className="ff-btn ff-btn--primary ff-btn--block" style={{ fontSize:16 }}
              onClick={()=>{ if(!user) goto({openLogin:true}); else goto({page:'checkout'}); }}>
              {user ? `Checkout · ${fmtINR(total)}` : 'Log in to checkout'} <Icon.Arrow/>
            </button>
            <button className="ff-btn ff-btn--block" style={{ marginTop:8 }} onClick={()=>goto({page:'shop'})}>
              Continue shopping
            </button>
            <div style={{ display:'flex', alignItems:'center', gap:6, justifyContent:'center', marginTop:14, fontSize:12, color:'var(--ff-muted)' }}>
              <Icon.Check/> Secured by Razorpay · All sales final
            </div>
          </div>
        </div>
      </div>
    </main>
  );
}

// ─── LOGIN PAGE ───────────────────────────────────────────────────────────────
function LoginPage({ onLogin }) {
  const next = FF_QP('next') || FF_URLS.home;
  // Reuse the AuthModal logic inline on a full page
  const handleLogin = (user) => { location.href = next; };
  const handleRegister = async (email, password, name, phone) => {
    const result = await FF_API.auth.register(email, password, name, phone);
    if (result.ok) { handleLogin(result.data?.user); return { ok:true }; }
    return { ok:false, error: result.data?.error || 'Registration failed' };
  };
  return (
    <main style={{ minHeight:'80vh', display:'grid', placeItems:'center', padding:'40px 24px' }}>
      <div style={{ width:'min(480px,100%)' }}>
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <div style={{ fontSize:32, color:'var(--ff-accent)' }}>✦</div>
          <h1 className="ff-display" style={{ fontSize:36, marginTop:8 }}>Fussy Finds</h1>
          <p style={{ color:'var(--ff-muted)', marginTop:6, fontSize:14 }}>Log in or create an account to continue.</p>
        </div>
        <InlineAuth onLogin={handleLogin} onRegister={handleRegister}/>
        <div style={{ textAlign:'center', marginTop:20 }}>
          <a href={FF_URLS.home} style={{ fontSize:13, color:'var(--ff-muted)' }}>← Continue as guest</a>
        </div>
      </div>
    </main>
  );
}

// ─── INLINE AUTH — full 3-step OTP signup + login ───────────────────────────
function InlineAuth({ onLogin, onRegister }) {
  const [mode,    setMode]    = useStateX('login');
  const [step,    setStep]    = useStateX('login'); // login | email | otp | details
  const [email,   setEmail]   = useStateX('');
  const [otp,     setOtp]     = useStateX('');
  const [otpHint, setOtpHint] = useStateX('');
  const [name,    setName]    = useStateX('');
  const [phone,   setPhone]   = useStateX('');
  const [pass,    setPass]    = useStateX('');
  const [pw,      setPw]      = useStateX({len:false,upper:false,lower:false,num:false});
  const [resendCd,setResendCd]= useStateX(0);
  const [error,   setError]   = useStateX('');
  const [loading, setLoading] = useStateX(false);

  const { useState: useStateX2, useEffect: useEffectX } = React;
  useEffectX(() => {
    if (resendCd<=0) return;
    const t = setTimeout(()=>setResendCd(c=>c-1),1000);
    return ()=>clearTimeout(t);
  },[resendCd]);

  const switchMode = (m) => {
    setMode(m); setStep(m==='signup'?'email':'login');
    setError(''); setEmail(''); setPass(''); setName(''); setPhone('');
    setOtp('');
  };

  const sendOtp = async () => {
    if (!email.includes('@')) { setError('Enter a valid email'); return; }
    setError(''); setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=send-pre-otp',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email})});
      const d = await res.json();
      if (!res.ok) { setError(d.error||'Could not send code'); return; }
      setOtpHint(d.email||email); setStep('otp'); setResendCd(30);
    } finally { setLoading(false); }
  };

  const verifyOtp = async () => {
    if (otp.length<6) return;
    setError(''); setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=verify-pre-otp',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email,code:otp})});
      const d = await res.json();
      if (!res.ok) { setError(d.error||'Wrong code'); return; }
      setStep('details'); setOtp('');
    } finally { setLoading(false); }
  };

  const checkPw = (v) => {
    setPass(v);
    setPw({len:v.length>=8,upper:/[A-Z]/.test(v),lower:/[a-z]/.test(v),num:/[0-9]/.test(v)});
  };

  const createAccount = async () => {
    if (!name.trim()) { setError('Name required'); return; }
    if (!pw.len||!pw.upper||!pw.lower||!pw.num) { setError('Password does not meet requirements'); return; }
    setError(''); setLoading(true);
    try {
      const result = await FF_API.auth.register(email, pass, name, phone);
      if (!result.ok) { setError(result.data?.error||'Registration failed'); return; }
      try {
        const token = localStorage.getItem('ff_access_token');
        await fetch('/api/auth.php?action=mark-verified',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+token}});
      } catch {}
      onLogin && onLogin(result.data?.user);
    } finally { setLoading(false); }
  };

  const loginSubmit = async () => {
    if (!email||!pass) { setError('Email and password required'); return; }
    setError(''); setLoading(true);
    try {
      const result = await FF_API.auth.login(email, pass);
      if (result.ok) { onLogin && onLogin(result.data?.user); }
      else setError(result.data?.error||'Wrong email or password');
    } finally { setLoading(false); }
  };

  const resendCode = async () => {
    if (resendCd>0) return;
    setLoading(true);
    try {
      const res = await fetch('/api/auth.php?action=send-pre-otp',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email})});
      if (res.ok) { setResendCd(60); setOtp(''); setError(''); }
    } finally { setLoading(false); }
  };

  return (
    <div className="ff-card" style={{ padding:28 }}>
      {/* Mode tabs */}
      {(step==='login'||step==='email') && (
        <div style={{ display:'flex', gap:4, padding:3, background:'rgba(0,0,0,.06)', borderRadius:999, marginBottom:20 }}>
          {[{k:'login',l:'Log in'},{k:'signup',l:'Sign up'}].map(t=>(
            <button key={t.k} onClick={()=>switchMode(t.k)} style={{
              flex:1, padding:'8px 12px', borderRadius:999, fontSize:13, fontWeight:600,
              background:mode===t.k?'#fff':'transparent',
              boxShadow:mode===t.k?'var(--ff-shadow-sm)':'none',
              border:mode===t.k?'var(--ff-border)':'2px solid transparent',
            }}>{t.l}</button>
          ))}
        </div>
      )}

      {step==='login' && (
        <div style={{display:'grid',gap:10}}>
          <input className="ff-input" type="email" placeholder="Email" value={email} onChange={e=>setEmail(e.target.value)} autoFocus/>
          <input className="ff-input" type="password" placeholder="Password" value={pass} onChange={e=>setPass(e.target.value)} onKeyDown={e=>e.key==='Enter'&&loginSubmit()}/>
          {error && <div style={{fontSize:13,color:'var(--ff-accent)',padding:'8px 12px',background:'rgba(228,67,156,.08)',borderRadius:8}}>{error}</div>}
          <button className="ff-btn ff-btn--primary ff-btn--block" onClick={loginSubmit} disabled={loading}>{loading?'Logging in…':'Log in →'}</button>
        </div>
      )}

      {step==='email' && (
        <div style={{display:'grid',gap:12}}>
          <div style={{fontSize:12,color:'var(--ff-muted)'}}><span style={{background:'var(--ff-sun)',padding:'2px 8px',borderRadius:4,fontWeight:700}}>Step 1 of 3</span> Verify your email</div>
          <input className="ff-input" type="email" placeholder="your@email.com" value={email} onChange={e=>setEmail(e.target.value)} onKeyDown={e=>e.key==='Enter'&&sendOtp()} autoFocus/>
          {error && <div style={{fontSize:13,color:'var(--ff-accent)',padding:'8px 12px',background:'rgba(228,67,156,.08)',borderRadius:8}}>{error}</div>}
          <button className="ff-btn ff-btn--primary ff-btn--block" onClick={sendOtp} disabled={loading||!email.includes('@')}>{loading?'Sending…':'Send verification code →'}</button>
        </div>
      )}

      {step==='otp' && (
        <div style={{display:'grid',gap:12}}>
          <div style={{fontSize:12,color:'var(--ff-muted)'}}><span style={{background:'var(--ff-sun)',padding:'2px 8px',borderRadius:4,fontWeight:700}}>Step 2 of 3</span> Code sent to <strong>{otpHint}</strong></div>
          <input className="ff-input" placeholder="6-digit code" value={otp} maxLength={6}
            onChange={e=>setOtp(e.target.value.replace(/\D/g,'').slice(0,6))}
            onKeyDown={e=>e.key==='Enter'&&verifyOtp()}
            style={{textAlign:'center',fontSize:32,fontFamily:'monospace',fontWeight:700,letterSpacing:'.25em'}} autoFocus/>
          {error && <div style={{fontSize:13,color:'var(--ff-accent)',padding:'8px 12px',background:'rgba(228,67,156,.08)',borderRadius:8,textAlign:'center'}}>{error}</div>}
          <button className="ff-btn ff-btn--primary ff-btn--block" onClick={verifyOtp} disabled={loading||otp.length<6}>{loading?'Verifying…':'Verify ✓'}</button>
          <div style={{display:'flex',justifyContent:'space-between'}}>
            <button onClick={()=>setStep('email')} style={{fontSize:12,color:'var(--ff-muted)',background:'none',border:'none',cursor:'pointer'}}>← Change email</button>
            <button onClick={resendCode} disabled={resendCd>0||loading} style={{fontSize:12,color:resendCd>0?'var(--ff-muted)':'var(--ff-accent)',background:'none',border:'none',cursor:resendCd>0?'default':'pointer',fontWeight:500}}>{resendCd>0?`Resend in ${resendCd}s`:'Resend code'}</button>
          </div>
        </div>
      )}

      {step==='details' && (
        <div style={{display:'grid',gap:10}}>
          <div style={{fontSize:12,color:'var(--ff-muted)'}}><span style={{background:'var(--ff-lime)',padding:'2px 8px',borderRadius:4,fontWeight:700}}>Step 3 of 3</span> <span style={{color:'var(--ff-teal)',fontWeight:600}}>✓ {email}</span></div>
          <input className="ff-input" placeholder="Your full name *" value={name} onChange={e=>setName(e.target.value)} autoFocus/>
          <input className="ff-input" placeholder="Phone (optional)" value={phone} onChange={e=>setPhone(e.target.value.replace(/\D/g,'').slice(0,10))}/>
          <input className="ff-input" type="password" placeholder="Create password *" value={pass} onChange={e=>checkPw(e.target.value)}/>
          {pass.length>0 && (
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:4,fontSize:11}}>
              {[['8+ characters',pw.len],['Uppercase',pw.upper],['Lowercase',pw.lower],['Number',pw.num]].map(([l,ok])=>(
                <div key={l} style={{display:'flex',alignItems:'center',gap:4,color:ok?'var(--ff-teal)':'var(--ff-muted)'}}><span>{ok?'✓':'○'}</span>{l}</div>
              ))}
            </div>
          )}
          {error && <div style={{fontSize:13,color:'var(--ff-accent)',padding:'8px 12px',background:'rgba(228,67,156,.08)',borderRadius:8}}>{error}</div>}
          <button className="ff-btn ff-btn--primary ff-btn--block" onClick={createAccount}
            disabled={loading||!name.trim()||!pw.len||!pw.upper||!pw.lower||!pw.num}>
            {loading?'Creating account…':'Create account ✦'}
          </button>
        </div>
      )}

      <div style={{fontSize:11,color:'var(--ff-muted)',textAlign:'center',marginTop:14}}>
        By continuing you agree to our{' '}
        <a href="/terms" target="_blank" style={{color:'var(--ff-ink-2)',textDecoration:'underline'}}>Terms</a>
        {' '}&amp;{' '}
        <a href="/privacy" target="_blank" style={{color:'var(--ff-ink-2)',textDecoration:'underline'}}>Privacy Policy</a>.
      </div>
    </div>
  );
}

Object.assign(window, { CartPage, LoginPage, InlineAuth });
