// Burger House — Order page (sample, demo-only state)

const FULFILMENT = [
  { id: 'pickup',   label: 'Pickup',     desc: 'Ready in 12–18 min',  icon: '🛍' },
  { id: 'delivery', label: 'Delivery',   desc: '25–35 min · £2.50',   icon: '🛵' },
  { id: 'dinein',   label: 'Dine-in',    desc: 'Pay at the table',    icon: '🪑' },
];

const ORDER_BRANCHES = [
  { id: 'bristol-clifton',    name: 'Bristol — Clifton',     wait: '14 min', distance: '0.4 mi' },
  { id: 'london-shoreditch',  name: 'London — Shoreditch',   wait: '18 min', distance: '102 mi' },
  { id: 'london-soho',        name: 'London — Soho',         wait: '21 min', distance: '105 mi' },
  { id: 'manchester-nq',      name: 'Manchester — NQ',       wait: '12 min', distance: '162 mi' },
  { id: 'edinburgh-old-town', name: 'Edinburgh — Old Town',  wait: '9 min',  distance: '371 mi' },
  { id: 'cardiff-city',       name: 'Cardiff — City Centre', wait: '15 min', distance: '38 mi'  },
];

const generateSlots = () => {
  const now = new Date();
  now.setMinutes(Math.ceil(now.getMinutes() / 15) * 15 + 15, 0, 0);
  return Array.from({ length: 8 }, (_, i) => {
    const t = new Date(now.getTime() + i * 15 * 60000);
    return { id: i, label: t.toTimeString().slice(0, 5) };
  });
};

const QtyBtn = ({ label, onClick, disabled }) => (
  <button
    onClick={onClick} disabled={disabled}
    style={{
      all: 'unset', cursor: disabled ? 'not-allowed' : 'pointer',
      width: 26, height: 26, borderRadius: '50%',
      background: 'var(--surface-2)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: 14, lineHeight: 1, color: 'var(--ink)',
      opacity: disabled ? 0.4 : 1,
    }}>{label}</button>
);

const OrderItemRow = ({ item, onChange, onRemove }) => (
  <div className="row gap-12" style={{ padding: '14px 0', borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
    <img src={`public/${item.id}.jpg`} alt={item.name} style={{ width: 56, height: 56, borderRadius: 12, objectFit: 'cover', flexShrink: 0 }} />
    <div className="col" style={{ flex: 1, minWidth: 0, gap: 2 }}>
      <span style={{ fontSize: 14, fontWeight: 600 }}>{item.name}</span>
      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{item.calories} kcal · £{item.price.toFixed(2)}</span>
    </div>
    <div className="row gap-8" style={{ alignItems: 'center' }}>
      <QtyBtn label="−" onClick={() => onChange(Math.max(0, item.qty - 1))} disabled={item.qty <= 0} />
      <span className="mono" style={{ width: 18, textAlign: 'center', fontSize: 13 }}>{item.qty}</span>
      <QtyBtn label="+" onClick={() => onChange(item.qty + 1)} />
    </div>
    <span className="mono" style={{ width: 60, textAlign: 'right', fontSize: 14 }}>£{(item.qty * item.price).toFixed(2)}</span>
    <button onClick={onRemove} style={{ all: 'unset', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 16, padding: 4 }} aria-label="Remove">×</button>
  </div>
);

const MenuTile = ({ p, onAdd }) => (
  <article className="lift" onClick={onAdd} style={{
    background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14,
    overflow: 'hidden', cursor: 'pointer', display: 'flex', flexDirection: 'column',
  }}>
    <div style={{ aspectRatio: '4/3', overflow: 'hidden', background: 'var(--surface-2)' }}>
      <img src={`public/${p.id}.jpg`} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
    </div>
    <div className="col" style={{ padding: 14, gap: 6, flex: 1 }}>
      <div className="row between" style={{ alignItems: 'baseline' }}>
        <span style={{ fontSize: 14, fontWeight: 600 }}>{p.name}</span>
        <span className="mono" style={{ fontSize: 13 }}>£{p.price.toFixed(2)}</span>
      </div>
      <span className="muted" style={{ fontSize: 12, lineHeight: 1.4 }}>{p.tagline}</span>
      <button className="btn btn-ghost btn-sm" style={{ marginTop: 'auto', alignSelf: 'flex-start', height: 28, padding: '0 12px', fontSize: 12 }}>
        Add +
      </button>
    </div>
  </article>
);

const OrderPage = () => {
  const [fulfilment, setFulfilment] = React.useState('pickup');
  const [branch, setBranch] = React.useState(ORDER_BRANCHES[0].id);
  const [slot, setSlot] = React.useState(0);
  const [promo, setPromo] = React.useState('');
  const [promoApplied, setPromoApplied] = React.useState(false);
  const [cart, setCart] = React.useState({
    'house-classic': { ...PRODUCTS.find(p => p.id === 'house-classic'), qty: 1 },
    'crinkle-fries': { ...PRODUCTS.find(p => p.id === 'crinkle-fries'), qty: 1 },
  });

  const slots = React.useMemo(generateSlots, []);

  const addToCart = (p) => setCart(c => ({
    ...c,
    [p.id]: { ...p, qty: (c[p.id]?.qty || 0) + 1 },
  }));
  const updateQty = (id, qty) => setCart(c => {
    if (qty <= 0) { const { [id]: _, ...rest } = c; return rest; }
    return { ...c, [id]: { ...c[id], qty } };
  });
  const removeItem = (id) => setCart(c => { const { [id]: _, ...rest } = c; return rest; });

  const items = Object.values(cart);
  const subtotal = items.reduce((s, i) => s + i.qty * i.price, 0);
  const deliveryFee = fulfilment === 'delivery' ? 2.50 : 0;
  const discount = promoApplied ? subtotal * 0.10 : 0;
  const total = subtotal + deliveryFee - discount;

  const applyPromo = (e) => {
    e.preventDefault();
    if (promo.trim().toUpperCase() === 'WELCOME10') setPromoApplied(true);
  };

  const menuPreview = PRODUCTS.filter(p => !cart[p.id]).slice(0, 6);

  return (
    <>
      {/* Header */}
      <section style={{ padding: '40px 0 16px' }}>
        <div className="container">
          <span className="eyebrow">Order</span>
          <h1 className="display" style={{ fontSize: 'clamp(36px, 4.5vw, 60px)', margin: '12px 0 8px', lineHeight: 1.05 }}>Build your order.</h1>
          <p style={{ fontSize: 16, color: 'var(--ink-2)', maxWidth: 540, margin: 0 }}>
            Pickup, delivery, or dine-in. Your basket follows you across pages — points apply at checkout.
          </p>
        </div>
      </section>

      <section style={{ padding: '24px 0 80px' }}>
        <div className="container order-grid" style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 24, alignItems: 'flex-start' }}>
          {/* LEFT — fulfilment + menu */}
          <div className="col gap-20" style={{ minWidth: 0 }}>
            {/* Fulfilment toggle */}
            <div className="card" style={{ padding: 18 }}>
              <span className="eyebrow">How would you like it?</span>
              <div className="row gap-12 fulfil-row" style={{ marginTop: 12 }}>
                {FULFILMENT.map(f => (
                  <button
                    key={f.id}
                    onClick={() => setFulfilment(f.id)}
                    style={{
                      all: 'unset', cursor: 'pointer', flex: 1, minWidth: 140,
                      padding: 14, borderRadius: 14,
                      background: fulfilment === f.id ? 'var(--accent-soft)' : 'var(--surface-2)',
                      border: `1.5px solid ${fulfilment === f.id ? 'var(--accent)' : 'transparent'}`,
                      display: 'flex', flexDirection: 'column', gap: 4,
                    }}>
                    <span style={{ fontSize: 22 }}>{f.icon}</span>
                    <span style={{ fontSize: 14, fontWeight: 600 }}>{f.label}</span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{f.desc}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Branch + slot */}
            <div className="card" style={{ padding: 18 }}>
              <div className="row between" style={{ marginBottom: 12 }}>
                <span className="eyebrow">{fulfilment === 'delivery' ? 'Deliver from' : 'Pick up from'}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>6 branches</span>
              </div>
              <select
                value={branch}
                onChange={e => setBranch(e.target.value)}
                style={{
                  width: '100%', padding: '12px 14px',
                  borderRadius: 12, border: '1px solid var(--line)',
                  background: 'var(--surface-2)', fontSize: 14, color: 'var(--ink)',
                  fontFamily: 'inherit',
                }}>
                {ORDER_BRANCHES.map(b => (
                  <option key={b.id} value={b.id}>{b.name} · {b.distance} · ~{b.wait} wait</option>
                ))}
              </select>

              <div style={{ marginTop: 18 }}>
                <span className="eyebrow">Time slot</span>
                <div className="row gap-8" style={{ marginTop: 10, flexWrap: 'wrap' }}>
                  {slots.map(s => (
                    <button
                      key={s.id}
                      onClick={() => setSlot(s.id)}
                      className="mono"
                      style={{
                        all: 'unset', cursor: 'pointer',
                        padding: '8px 14px', borderRadius: 999, fontSize: 12,
                        background: slot === s.id ? 'var(--ink)' : 'var(--surface-2)',
                        color: slot === s.id ? 'var(--bg)' : 'var(--ink-2)',
                      }}>{s.label}</button>
                  ))}
                </div>
              </div>
            </div>

            {/* Cart */}
            <div className="card" style={{ padding: 0 }}>
              <div className="row between" style={{ padding: 18, borderBottom: '1px solid var(--line)', alignItems: 'center' }}>
                <span className="eyebrow">Your basket</span>
                <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{items.length} item{items.length === 1 ? '' : 's'}</span>
              </div>
              <div style={{ padding: '0 18px' }}>
                {items.length === 0 ? (
                  <p style={{ padding: '24px 0', textAlign: 'center', color: 'var(--ink-3)', fontSize: 14, margin: 0 }}>Your basket is empty. Add something below.</p>
                ) : items.map(i => (
                  <OrderItemRow
                    key={i.id} item={i}
                    onChange={qty => updateQty(i.id, qty)}
                    onRemove={() => removeItem(i.id)}
                  />
                ))}
              </div>
            </div>

            {/* Suggested */}
            <div>
              <div className="row between" style={{ marginBottom: 12 }}>
                <span className="eyebrow">Add to your order</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Frequently picked together</span>
              </div>
              <div className="suggested-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 14 }}>
                {menuPreview.map(p => <MenuTile key={p.id} p={p} onAdd={() => addToCart(p)} />)}
              </div>
            </div>
          </div>

          {/* RIGHT — sticky checkout */}
          <aside className="card order-summary" style={{ padding: 22, position: 'sticky', top: 88 }}>
            <span className="eyebrow">Summary</span>
            <h3 className="display" style={{ margin: '8px 0 18px', fontSize: 24 }}>Checkout</h3>

            {/* Promo */}
            <form onSubmit={applyPromo} className="row gap-8" style={{ marginBottom: 18 }}>
              <input
                value={promo}
                onChange={e => setPromo(e.target.value)}
                placeholder="Promo code"
                style={{
                  flex: 1, padding: '10px 12px', borderRadius: 10,
                  border: '1px solid var(--line)', background: 'var(--surface-2)',
                  fontSize: 13, color: 'var(--ink)', fontFamily: 'inherit',
                }}/>
              <button className="btn btn-ghost btn-sm" type="submit" style={{ height: 38 }}>Apply</button>
            </form>
            {promoApplied && <div className="mono" style={{ fontSize: 11, color: 'var(--positive, #4a6b3a)', marginBottom: 10 }}>WELCOME10 applied — 10% off</div>}

            {/* Totals */}
            <div className="col gap-8" style={{ paddingBottom: 12, borderBottom: '1px solid var(--line)' }}>
              <div className="row between"><span style={{ fontSize: 13, color: 'var(--ink-2)' }}>Subtotal</span><span className="mono" style={{ fontSize: 13 }}>£{subtotal.toFixed(2)}</span></div>
              {fulfilment === 'delivery' && <div className="row between"><span style={{ fontSize: 13, color: 'var(--ink-2)' }}>Delivery</span><span className="mono" style={{ fontSize: 13 }}>£{deliveryFee.toFixed(2)}</span></div>}
              {promoApplied && <div className="row between"><span style={{ fontSize: 13, color: 'var(--accent)' }}>Discount</span><span className="mono" style={{ fontSize: 13, color: 'var(--accent)' }}>−£{discount.toFixed(2)}</span></div>}
            </div>
            <div className="row between" style={{ padding: '14px 0', alignItems: 'baseline' }}>
              <span style={{ fontSize: 15, fontWeight: 600 }}>Total</span>
              <span className="display" style={{ fontSize: 28 }}>£{total.toFixed(2)}</span>
            </div>

            <button className="btn btn-primary" disabled={items.length === 0} style={{ width: '100%', height: 48, fontSize: 14 }}>
              {items.length === 0 ? 'Add items to continue' : `Place order · £${total.toFixed(2)}`}
            </button>

            <div className="row gap-8" style={{ marginTop: 12, alignItems: 'center', flexWrap: 'wrap' }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>Pay with</span>
              {['Apple Pay', 'Google Pay', 'Card'].map(m => (
                <span key={m} className="pill" style={{ height: 22, padding: '0 10px', fontSize: 11 }}>{m}</span>
              ))}
            </div>

            <div className="mono" style={{ marginTop: 14, fontSize: 11, color: 'var(--ink-3)', lineHeight: 1.5 }}>
              You'll earn <span style={{ color: 'var(--accent)' }}>{Math.round(total * 10)} points</span> on this order.
            </div>
          </aside>
        </div>
      </section>

      <Footer />
    </>
  );
};

Object.assign(window, { OrderPage });
