/* Cart drawer + checkout */

const { useState: useStateCart } = React;

function CartDrawer({ open, onClose, items, setItems, accent, dark, onCheckout }) {
  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const surface = dark ? '#073c3a' : '#fbf5e6';
  const border = dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.10)';
  const mute = dark ? 'rgba(247,238,219,0.6)' : '#6b6253';
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const total = subtotal;

  const updateQty = (id, d) => {
    setItems(items.map(i => i.id === id ? { ...i, qty: Math.max(0, i.qty + d) } : i).filter(i => i.qty > 0));
  };

  return (
    <React.Fragment>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(7,39,37,0.45)',
        backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity .25s ease', zIndex: 60,
      }}></div>
      <aside style={{
        position: 'fixed', top: 0, right: 0, height: '100vh',
        width: 'min(440px, 100vw)', background: surface, color: fg,
        boxShadow: '-30px 0 60px rgba(0,0,0,0.20)',
        transform: open ? 'translateX(0)' : 'translateX(105%)',
        transition: 'transform .3s cubic-bezier(.2,.8,.2,1)', zIndex: 61,
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '22px 24px', borderBottom: `1px solid ${border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent }}>Your pot</div>
            <h3 style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 24, margin: '4px 0 0', letterSpacing: '-0.01em' }}>
              {items.length} {items.length === 1 ? 'item' : 'items'}
            </h3>
          </div>
          <button onClick={onClose} aria-label="Close cart" style={{
            width: 36, height: 36, borderRadius: '50%',
            background: 'transparent', border: `1px solid ${border}`,
            color: fg, fontSize: 18, cursor: 'pointer',
          }}>×</button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px' }}>
          {items.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '60px 0', color: mute }}>
              <div style={{ fontSize: 48, opacity: 0.4 }}>🍲</div>
              <div style={{ marginTop: 10, fontSize: 15 }}>Your pot is empty.</div>
              <div style={{ marginTop: 6, fontSize: 13 }}>Add a few dishes from the menu.</div>
            </div>
          ) : items.map(i => (
            <div key={i.id} style={{
              display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 14,
              padding: '14px 0', borderBottom: `1px solid ${border}`, alignItems: 'center',
            }}>
              <FoodPhoto imageId={i.imageId} fallbackLabel={i.name} tone={dark ? 'dark' : 'light'} accent={accent} radius={10} ratio="1/1" />
              <div>
                <div style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 600, fontSize: 15, letterSpacing: '-0.005em' }}>{i.name}</div>
                <div style={{ color: mute, fontSize: 12, marginTop: 2 }}>{ngn(i.price)}</div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 8 }}>
                  <QtyBtn dark={dark} onClick={()=>updateQty(i.id, -1)}>−</QtyBtn>
                  <span style={{ minWidth: 22, textAlign: 'center', fontWeight: 600, fontSize: 14 }}>{i.qty}</span>
                  <QtyBtn dark={dark} onClick={()=>updateQty(i.id, +1)}>+</QtyBtn>
                </div>
              </div>
              <div style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 15 }}>{ngn(i.price * i.qty)}</div>
            </div>
          ))}
        </div>

        {items.length > 0 && (
          <div style={{ borderTop: `1px solid ${border}`, padding: '20px 24px' }}>
            <Row label="Subtotal" value={ngn(subtotal)} mute={mute} fg={fg} />
            <Row label="Packs" value="Quoted at checkout" mute={mute} fg={fg} />
            <Row label="Delivery" value="Quoted at checkout" mute={mute} fg={fg} />
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              padding: '14px 0 18px', borderTop: `1px dashed ${border}`, marginTop: 8,
            }}>
              <span style={{ fontSize: 13, color: mute, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>Total</span>
              <span style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 26, color: fg, letterSpacing: '-0.01em' }}>{ngn(total)}</span>
            </div>
            <Btn variant="orange" fullWidth size="lg" onClick={onCheckout}>Checkout →</Btn>
            <div style={{ fontSize: 11, color: mute, textAlign: 'center', marginTop: 12 }}>
              Prices exclusive of packs & delivery — added above.
            </div>
          </div>
        )}
      </aside>
    </React.Fragment>
  );
}

function QtyBtn({ children, onClick, dark }) {
  return (
    <button onClick={onClick} style={{
      width: 26, height: 26, borderRadius: '50%',
      background: dark ? 'rgba(247,238,219,0.10)' : 'rgba(14,110,106,0.08)',
      color: dark ? '#f7eedb' : '#0e6e6a',
      border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 600,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    }}>{children}</button>
  );
}

function Row({ label, value, mute, fg }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', fontSize: 14 }}>
      <span style={{ color: mute }}>{label}</span>
      <span style={{ color: fg, fontWeight: 500 }}>{value}</span>
    </div>
  );
}

/* ------------------------ Checkout modal ------------------------ */

function CheckoutModal({ open, onClose, items, accent, dark, onPlaced }) {
  const [step, setStep] = useStateCart(1);
  const [form, setForm] = useStateCart({ name: '', phone: '', email: '', address: '', area: 'Select area', notes: '', pay: 'transfer', when: 'asap' });

  React.useEffect(() => { if (open) { setStep(1); } }, [open]);

  const fg = dark ? '#f7eedb' : '#0e6e6a';
  const surface = dark ? '#073c3a' : '#fbf5e6';
  const border = dark ? 'rgba(247,238,219,0.14)' : 'rgba(14,110,106,0.14)';
  const mute = dark ? 'rgba(247,238,219,0.6)' : '#6b6253';
  const inputBg = dark ? 'rgba(247,238,219,0.06)' : '#fff';
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const total = subtotal + (items.length ? 2000 : 0);

  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));

  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(7,39,37,0.55)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      zIndex: 70, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={(e)=>e.stopPropagation()} style={{
        background: surface, color: fg, borderRadius: 28,
        width: 'min(640px, 100%)', maxHeight: '92vh', overflow: 'auto',
        boxShadow: '0 40px 90px rgba(0,0,0,0.35)',
        border: `1px solid ${border}`,
      }}>
        <div style={{ padding: '24px 28px', borderBottom: `1px solid ${border}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.16em', textTransform: 'uppercase', color: accent }}>Step {step} of 3</div>
            <h3 style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 26, margin: '4px 0 0', letterSpacing: '-0.01em' }}>
              {step === 1 ? 'Delivery details' : step === 2 ? 'Payment' : 'Order placed'}
            </h3>
          </div>
          <button onClick={onClose} style={{ width: 36, height: 36, borderRadius: '50%', background: 'transparent', border: `1px solid ${border}`, color: fg, fontSize: 18, cursor: 'pointer' }}>×</button>
        </div>

        <div style={{ padding: '24px 28px' }}>
          {step === 1 && (
            <div style={{ display: 'grid', gap: 14 }}>
              <Field label="Full name" value={form.name} onChange={(v)=>upd('name', v)} bg={inputBg} fg={fg} border={border} mute={mute} />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <Field label="Phone" value={form.phone} onChange={(v)=>upd('phone', v)} bg={inputBg} fg={fg} border={border} mute={mute} ph="0704 …" />
                <Field label="Email (optional)" value={form.email} onChange={(v)=>upd('email', v)} bg={inputBg} fg={fg} border={border} mute={mute} />
              </div>
              <Field label="Delivery address" value={form.address} onChange={(v)=>upd('address', v)} bg={inputBg} fg={fg} border={border} mute={mute} ph="House no., street, landmark" />
              <SelectField label="Area" value={form.area} onChange={(v)=>upd('area', v)} bg={inputBg} fg={fg} border={border} mute={mute}
                options={['Select area', 'Lagos Island', 'Lagos Mainland', 'Outside Lagos']} />
              <div>
                <Label mute={mute}>When?</Label>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {['asap','lunch','dinner','schedule'].map(w => (
                    <button key={w} onClick={()=>upd('when', w)} style={{
                      padding: '10px 16px', borderRadius: 999,
                      background: form.when === w ? accent : 'transparent',
                      color: form.when === w ? '#fff' : fg,
                      border: `1px solid ${form.when === w ? accent : border}`,
                      fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: '"Plus Jakarta Sans", system-ui',
                    }}>{w === 'asap' ? 'ASAP (≤60 min)' : w === 'lunch' ? 'Lunch 12-2' : w === 'dinner' ? 'Dinner 6-8' : 'Schedule…'}</button>
                  ))}
                </div>
              </div>
              <Field label="Notes for the chef" value={form.notes} onChange={(v)=>upd('notes', v)} bg={inputBg} fg={fg} border={border} mute={mute} multi ph="Less pepper, extra plantain, etc." />
            </div>
          )}

          {step === 2 && (
            <div style={{ display: 'grid', gap: 18 }}>
              <div>
                <Label mute={mute}>Payment method</Label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                  {[
                    { id: 'transfer', label: 'Bank Transfer', sub: 'Recommended' },
                    { id: 'card', label: 'Card', sub: 'Paystack' },
                    { id: 'cod', label: 'Pay on delivery', sub: 'Cash / POS' },
                  ].map(p => (
                    <button key={p.id} onClick={()=>upd('pay', p.id)} style={{
                      padding: 14, borderRadius: 16, textAlign: 'left',
                      background: form.pay === p.id ? (dark ? 'rgba(232,122,31,0.18)' : 'rgba(232,122,31,0.10)') : 'transparent',
                      color: fg,
                      border: `1.5px solid ${form.pay === p.id ? accent : border}`,
                      cursor: 'pointer', fontFamily: '"Plus Jakarta Sans", system-ui',
                    }}>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{p.label}</div>
                      <div style={{ fontSize: 11, color: mute, marginTop: 4 }}>{p.sub}</div>
                    </button>
                  ))}
                </div>
              </div>

              <div style={{ padding: 18, borderRadius: 16, background: dark ? 'rgba(247,238,219,0.06)' : '#fff', border: `1px solid ${border}` }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: mute, marginBottom: 12 }}>Order summary</div>
                {items.map(i => (
                  <div key={i.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, padding: '4px 0' }}>
                    <span>{i.qty} × {i.name}</span>
                    <span>{ngn(i.price * i.qty)}</span>
                  </div>
                ))}
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: mute, padding: '8px 0 4px', borderTop: `1px dashed ${border}`, marginTop: 8 }}>
                  <span>Packs & delivery</span><span>Quoted after order</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, alignItems: 'baseline' }}>
                  <span style={{ fontSize: 13, color: mute, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>Total</span>
                  <span style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 26, letterSpacing: '-0.01em' }}>{ngn(total)}</span>
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div style={{ textAlign: 'center', padding: '20px 0 10px' }}>
              <div style={{
                width: 72, height: 72, borderRadius: '50%',
                background: accent, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 34, fontWeight: 700, marginBottom: 18,
              }}>✓</div>
              <h4 style={{ fontFamily: '"Bricolage Grotesque", system-ui', fontWeight: 700, fontSize: 28, margin: 0, letterSpacing: '-0.01em' }}>Pot is on its way</h4>
              <p style={{ color: mute, marginTop: 10, fontSize: 15, lineHeight: 1.55 }}>
                Order #DP-{Math.floor(10000 + Math.random()*89999)} confirmed for <strong style={{ color: fg }}>{form.name || 'you'}</strong>. We'll WhatsApp <strong style={{ color: fg }}>{form.phone || 'your number'}</strong> when the rider is rolling.
              </p>
              <div style={{ marginTop: 24, padding: 14, borderRadius: 14, background: dark ? 'rgba(247,238,219,0.06)' : '#fff', border: `1px solid ${border}`, fontSize: 13, color: mute, fontStyle: 'italic', fontFamily: '"Fraunces", serif' }}>
                "Food is love. Thank you for trusting us with yours." — Chef Aduke
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: '18px 28px 24px', borderTop: `1px solid ${border}`, display: 'flex', justifyContent: 'space-between', gap: 12 }}>
          {step === 1 && <React.Fragment>
            <Btn variant={dark ? 'ghostDark' : 'ghost'} onClick={onClose}>Back to cart</Btn>
            <Btn variant="orange" onClick={()=>setStep(2)} disabled={!form.name || !form.phone || !form.address}>Continue to payment →</Btn>
          </React.Fragment>}
          {step === 2 && <React.Fragment>
            <Btn variant={dark ? 'ghostDark' : 'ghost'} onClick={()=>setStep(1)}>← Back</Btn>
            <Btn variant="orange" onClick={()=>{ setStep(3); onPlaced && onPlaced(); }}>Place order — {ngn(total)}</Btn>
          </React.Fragment>}
          {step === 3 && <Btn variant="orange" fullWidth onClick={onClose}>Done</Btn>}
        </div>
      </div>
    </div>
  );
}

function Label({ children, mute }) {
  return <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: mute, marginBottom: 8 }}>{children}</div>;
}

function Field({ label, value, onChange, bg, fg, border, mute, ph, multi }) {
  const Comp = multi ? 'textarea' : 'input';
  return (
    <label style={{ display: 'block' }}>
      <Label mute={mute}>{label}</Label>
      <Comp value={value} onChange={(e)=>onChange(e.target.value)} placeholder={ph} rows={multi ? 3 : undefined} style={{
        width: '100%', background: bg, color: fg, border: `1px solid ${border}`,
        borderRadius: 12, padding: '12px 14px', fontSize: 15,
        fontFamily: '"Plus Jakarta Sans", system-ui', outline: 'none',
        resize: multi ? 'vertical' : 'none',
      }} />
    </label>
  );
}

function SelectField({ label, value, onChange, options, bg, fg, border, mute }) {
  return (
    <label style={{ display: 'block' }}>
      <Label mute={mute}>{label}</Label>
      <select value={value} onChange={(e)=>onChange(e.target.value)} style={{
        width: '100%', background: bg, color: fg, border: `1px solid ${border}`,
        borderRadius: 12, padding: '12px 14px', fontSize: 15,
        fontFamily: '"Plus Jakarta Sans", system-ui', outline: 'none',
      }}>
        {options.map(o => <option key={o} value={o}>{o}</option>)}
      </select>
    </label>
  );
}

Object.assign(window, { CartDrawer, CheckoutModal });
