// === SHOP SCREEN ===
const ShopScreen = ({ theme, initialCategory, cart, onAddToCart, onViewCart, onBack }) => {
  const m = theme.mobile;
  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [tab, setTab] = React.useState(initialCategory || 'space-infuser');
  const [added, setAdded] = React.useState(null);

  React.useEffect(() => {
    fetch('/api/shop/items')
      .then(r => r.json())
      .then(data => { setItems(data); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  const filtered = items.filter(i => i.category === tab);
  const cartCount = cart.reduce((s, c) => s + c.qty, 0);

  const handleAdd = (item) => {
    onAddToCart(item);
    setAdded(item.id);
    setTimeout(() => setAdded(null), 1200);
  };

  const tabLabel = { 'space-infuser': 'Space Infusers', 'car-diffuser': 'Car Diffusers' };

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.ink, paddingTop: m ? 54 : 90 }}>
      {/* Header */}
      <div style={{ padding: m ? '32px 24px 0' : '48px 72px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <Meta theme={theme} style={{ marginBottom: 8 }}>— home &amp; car</Meta>
          <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 32 : 52, fontWeight: 300, fontStyle: 'italic', lineHeight: 1.05, color: theme.ink }}>
            {tabLabel[tab]}
          </div>
        </div>
        {cartCount > 0 && (
          <button onClick={onViewCart} style={{
            background: theme.ink, color: theme.bg, border: 'none', cursor: 'pointer',
            fontFamily: '"Montserrat", sans-serif', fontSize: 12, letterSpacing: '0.14em',
            textTransform: 'uppercase', padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <span>Cart</span>
            <span style={{ background: theme.accent, color: '#fff', borderRadius: '50%', width: 22, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11 }}>{cartCount}</span>
          </button>
        )}
      </div>

      {/* Category tabs */}
      <div style={{ padding: m ? '24px 24px 0' : '32px 72px 0', display: 'flex', gap: 0, borderBottom: `1px solid ${theme.line}` }}>
        {Object.entries(tabLabel).map(([key, label]) => (
          <button key={key} onClick={() => setTab(key)} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: m ? '10px 16px' : '12px 24px',
            fontFamily: '"Montserrat", sans-serif', fontSize: 12, letterSpacing: '0.16em', textTransform: 'uppercase',
            color: tab === key ? theme.ink : theme.muted,
            borderBottom: tab === key ? `2px solid ${theme.ink}` : '2px solid transparent',
            marginBottom: -1, transition: 'color 200ms',
          }}>{label}</button>
        ))}
      </div>

      {/* Product grid */}
      <div style={{ padding: m ? '32px 24px' : '48px 72px' }}>
        {loading ? (
          <div style={{ textAlign: 'center', padding: '80px 0', color: theme.muted, fontFamily: '"Montserrat", sans-serif', fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Loading…</div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '80px 0', color: theme.muted, fontFamily: '"Montserrat", sans-serif', fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase' }}>No items yet</div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr 1fr' : 'repeat(3, 1fr)', gap: m ? 20 : 32 }}>
            {filtered.map(item => (
              <div key={item.id} style={{ display: 'flex', flexDirection: 'column' }}>
                {/* Image */}
                <div style={{ aspectRatio: '3/4', background: theme.tintMuted || '#eee', marginBottom: 16, overflow: 'hidden', position: 'relative' }}>
                  {item.imageUrl ? (
                    <img src={`/${item.imageUrl}`} alt={item.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  ) : (
                    <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: theme.muted, opacity: 0.5 }}>No image</div>
                    </div>
                  )}
                </div>
                {/* Info */}
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                  <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 14 : 17, fontWeight: 400, color: theme.ink, marginBottom: 6 }}>{item.name}</div>
                  {item.description && (
                    <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 12 : 14, fontWeight: 300, color: theme.ink, opacity: 0.65, lineHeight: 1.55, marginBottom: 12, flex: 1 }}>{item.description}</div>
                  )}
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
                    <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 16 : 20, fontStyle: 'italic', color: theme.ink }}>R {item.price.toFixed(0)}</div>
                    <button onClick={() => handleAdd(item)} style={{
                      background: added === item.id ? theme.accent : theme.ink,
                      color: theme.bg || '#f4efe8', border: 'none', cursor: 'pointer',
                      fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase',
                      padding: '10px 16px', transition: 'background 300ms',
                    }}>
                      {added === item.id ? 'Added ✓' : '+ Add to cart'}
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Back */}
      <div style={{ padding: m ? '0 24px 48px' : '0 72px 64px' }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.18em',
          textTransform: 'uppercase', color: theme.muted, padding: 0,
        }}>← back</button>
      </div>
    </div>
  );
};

// === CART SCREEN ===
const CartScreen = ({ theme, cart, onUpdateQty, onRemove, onCheckout, onBack }) => {
  const m = theme.mobile;
  const total = cart.reduce((s, c) => s + c.item.price * c.qty, 0);

  if (cart.length === 0) return (
    <div style={{ minHeight: '100vh', background: theme.bg, paddingTop: m ? 54 : 90, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 24 }}>
      <Meta theme={theme}>Your cart is empty</Meta>
      <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: theme.muted }}>← keep browsing</button>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.ink, paddingTop: m ? 54 : 90 }}>
      <section style={{ maxWidth: 720, margin: '0 auto', padding: m ? '40px 24px 80px' : '64px 48px 100px' }}>
        <Meta theme={theme} style={{ marginBottom: 12 }}>— your cart</Meta>
        <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 32 : 48, fontWeight: 300, fontStyle: 'italic', lineHeight: 1.05, marginBottom: m ? 32 : 48 }}>Review your order</div>

        {cart.map(({ item, qty }) => (
          <div key={item.id} style={{ display: 'flex', gap: 20, padding: '20px 0', borderBottom: `1px solid ${theme.line}`, alignItems: 'center' }}>
            {item.imageUrl && <img src={`/${item.imageUrl}`} alt={item.name} style={{ width: 64, height: 80, objectFit: 'cover', flexShrink: 0 }} />}
            {!item.imageUrl && <div style={{ width: 64, height: 80, background: theme.tintMuted || '#eee', flexShrink: 0 }} />}
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 14 : 17, marginBottom: 4 }}>{item.name}</div>
              <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 13 : 15, fontStyle: 'italic', color: theme.muted }}>R {item.price.toFixed(0)} each</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <button onClick={() => onUpdateQty(item.id, qty - 1)} style={{ background: 'none', border: `1px solid ${theme.line}`, width: 32, height: 32, cursor: 'pointer', fontFamily: '"Montserrat", sans-serif', fontSize: 18, color: theme.ink }}>−</button>
              <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 16, minWidth: 20, textAlign: 'center' }}>{qty}</span>
              <button onClick={() => onUpdateQty(item.id, qty + 1)} style={{ background: 'none', border: `1px solid ${theme.line}`, width: 32, height: 32, cursor: 'pointer', fontFamily: '"Montserrat", sans-serif', fontSize: 18, color: theme.ink }}>+</button>
              <button onClick={() => onRemove(item.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: theme.muted, fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.12em', marginLeft: 8 }}>Remove</button>
            </div>
            <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 15 : 18, fontStyle: 'italic', minWidth: 70, textAlign: 'right' }}>R {(item.price * qty).toFixed(0)}</div>
          </div>
        ))}

        {/* Totals */}
        <div style={{ padding: '24px 0', borderBottom: `1px solid ${theme.line}` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: theme.muted }}>Subtotal</span>
            <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 17, fontStyle: 'italic' }}>R {total.toFixed(0)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 13, letterSpacing: '0.14em', textTransform: 'uppercase', color: theme.muted }}>Shipping</span>
            <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 17, fontStyle: 'italic' }}>R 120</span>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', padding: '20px 0 32px' }}>
          <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 15, letterSpacing: '0.14em', textTransform: 'uppercase' }}>Total</span>
          <span style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 24 : 32, fontStyle: 'italic' }}>R {(total + 120).toFixed(0)}</span>
        </div>

        <div style={{ display: 'flex', flexDirection: m ? 'column' : 'row', gap: 20, alignItems: m ? 'stretch' : 'center' }}>
          <button onClick={onCheckout} style={{
            background: theme.ink, color: theme.bg || '#f4efe8', border: 'none', cursor: 'pointer',
            fontFamily: '"Montserrat", sans-serif', fontSize: m ? 17 : 20, fontStyle: 'italic',
            padding: m ? '18px 28px' : '20px 44px', display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <span>Checkout</span><span>→</span>
          </button>
          <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: theme.muted }}>← keep shopping</button>
        </div>
      </section>
    </div>
  );
};

// === SHOP CHECKOUT SCREEN ===
const ShopCheckoutField = ({ label, fk, type='text', placeholder, span=1, required=false, theme, m, form, set }) => (
  <label style={{ gridColumn: m ? 'span 2' : `span ${span}`, display: 'flex', flexDirection: 'column', gap: 6 }}>
    <Meta theme={theme}>{label}{required ? ' *' : ''}</Meta>
    <input type={type} value={form[fk]} onChange={e => set(fk, e.target.value)} placeholder={placeholder}
      style={{ fontFamily: '"Montserrat", sans-serif', fontSize: 16, fontWeight: 300, background: 'transparent', border: 'none', borderBottom: `1px solid ${theme.line}`, padding: '8px 0', color: theme.ink, outline: 'none', width: '100%' }} />
  </label>
);

const ShopCheckoutScreen = ({ theme, cart, onComplete, onBack }) => {
  const m = theme.mobile;
  const total = cart.reduce((s, c) => s + c.item.price * c.qty, 0);
  const [form, setForm] = React.useState({ name: '', email: '', phone: '', address: '', city: '', postal: '' });
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState('');

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valid = form.name && form.email && form.address && form.city;

  const submit = () => {
    if (!valid || submitting) return;
    setSubmitting(true); setError('');

    var itemsJson = JSON.stringify(
      cart.map(c => ({ id: c.item.id, name: c.item.name, price: c.item.price, qty: c.qty }))
    );
    var grandTotal = total + 120;

    fetch('/api/paystack/initialize', {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: form.email, name: form.name, phone: form.phone,
        address: form.address, city: form.city, postal: form.postal,
        amount: Math.round(grandTotal * 100), orderType: 'shop', itemsJson: itemsJson,
      })
    })
    .then(r => r.ok ? r.json() : r.text().then(t => { throw new Error(t); }))
    .then(data => {
      setSubmitting(false);
      try {
        var popup = new window.PaystackPop();
        popup.resumeTransaction(data.accessCode, {
          onSuccess: function(response) {
            onComplete(data.orderNumber);
            fetch('/api/paystack/verify', {
              method: 'POST', headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ reference: response.reference, orderType: 'shop' })
            }).catch(() => {});
          },
          onCancel: function() { setSubmitting(false); }
        });
      } catch(e) {
        setError('Payment error: ' + (e.message || String(e)));
      }
    })
    .catch(err => { setSubmitting(false); setError('Could not start payment: ' + (err.message || err)); });
  };

  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.ink, paddingTop: m ? 54 : 90 }}>
      <section style={{ maxWidth: 640, margin: '0 auto', padding: m ? '40px 24px 80px' : '64px 48px 100px' }}>
        <Meta theme={theme} style={{ marginBottom: 12 }}>— checkout</Meta>
        <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 32 : 48, fontWeight: 300, fontStyle: 'italic', lineHeight: 1.05, marginBottom: m ? 32 : 48 }}>Delivery details</div>

        <div style={{ display: 'grid', gridTemplateColumns: m ? '1fr' : '1fr 1fr', gap: 24, marginBottom: 40 }}>
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="Full name" fk="name" required placeholder="Your name" span={2} />
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="Email" fk="email" type="email" required placeholder="you@example.com" />
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="Phone" fk="phone" type="tel" placeholder="+27 xx xxx xxxx" />
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="Street address" fk="address" required placeholder="123 Main Street" span={2} />
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="City / Town" fk="city" required placeholder="City" />
          <ShopCheckoutField theme={theme} m={m} form={form} set={set} label="Postal code" fk="postal" placeholder="0001" />
        </div>

        {/* Order summary */}
        <div style={{ background: theme.tintMuted || '#ede8e0', padding: 20, marginBottom: 32 }}>
          <Meta theme={theme} style={{ marginBottom: 12 }}>— order summary</Meta>
          {cart.map(({ item, qty }) => (
            <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontFamily: '"Montserrat", sans-serif', fontSize: 14 }}>
              <span>{item.name} × {qty}</span>
              <span>R {(item.price * qty).toFixed(0)}</span>
            </div>
          ))}
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontFamily: '"Montserrat", sans-serif', fontSize: 14, borderTop: `1px solid ${theme.line}`, marginTop: 8 }}>
            <span>Shipping</span><span>R 120</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: '"Montserrat", sans-serif', fontSize: 18, fontStyle: 'italic', marginTop: 8 }}>
            <span>Total</span><span>R {(total + 120).toFixed(0)}</span>
          </div>
        </div>

        {error && <div style={{ color: '#c62828', fontFamily: '"Montserrat", sans-serif', fontSize: 14, marginBottom: 20 }}>{error}</div>}

        <div style={{ display: 'flex', flexDirection: m ? 'column' : 'row', gap: 20, alignItems: m ? 'stretch' : 'center' }}>
          <button onClick={submit} disabled={!valid || submitting} style={{
            background: valid ? theme.ink : theme.line, color: theme.bg || '#f4efe8', border: 'none',
            cursor: valid ? 'pointer' : 'not-allowed', opacity: submitting ? 0.6 : 1,
            fontFamily: '"Montserrat", sans-serif', fontSize: m ? 17 : 20, fontStyle: 'italic',
            padding: m ? '18px 28px' : '20px 44px', display: 'flex', alignItems: 'center', gap: 14, transition: 'background 200ms',
          }}>
            <span>{submitting ? 'Processing…' : `Pay R ${(total + 120).toFixed(0)} · Paystack`}</span>{!submitting && <span>→</span>}
          </button>
          <button onClick={onBack} style={{ background: 'none', border: 'none', cursor: 'pointer', fontFamily: '"Montserrat", sans-serif', fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: theme.muted }}>← back to cart</button>
        </div>
      </section>
    </div>
  );
};

// === SHOP ORDER SUCCESS ===
const ShopSuccessScreen = ({ theme, orderNumber, onHome }) => {
  const m = theme.mobile;
  return (
    <div style={{ minHeight: '100vh', background: theme.bg, color: theme.ink, paddingTop: m ? 54 : 90, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: '0 24px' }}>
      <Meta theme={theme} style={{ marginBottom: 20 }}>— order confirmed</Meta>
      <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 40 : 64, fontWeight: 300, fontStyle: 'italic', lineHeight: 1.05, marginBottom: 24 }}>
        Thank you.
      </div>
      <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 16 : 20, fontWeight: 300, color: theme.ink, opacity: 0.7, maxWidth: 480, lineHeight: 1.6, marginBottom: 12 }}>
        Your order <strong style={{ fontStyle: 'italic' }}>{orderNumber}</strong> has been placed. We'll be in touch by email with your tracking details once it ships.
      </div>
      <div style={{ fontFamily: '"Montserrat", sans-serif', fontSize: m ? 14 : 16, fontWeight: 300, color: theme.muted, marginBottom: 48 }}>
        Questions? Email us at <a href="mailto:hello@moyahaus.co.za" style={{ color: theme.accent }}>hello@moyahaus.co.za</a>
      </div>
      <button onClick={onHome} style={{
        background: theme.ink, color: theme.bg || '#f4efe8', border: 'none', cursor: 'pointer',
        fontFamily: '"Montserrat", sans-serif', fontSize: m ? 15 : 17, fontStyle: 'italic',
        padding: m ? '16px 28px' : '18px 40px',
      }}>Back to home →</button>
    </div>
  );
};

Object.assign(window, { ShopScreen, CartScreen, ShopCheckoutScreen, ShopSuccessScreen });
