// Takeaway: menu -> cart -> checkout -> confirmation
const { useState: useStateTA, useMemo: useMemoTA, useEffect: useEffectTA } = React;

function TakeawayModal({ open, onClose }) {
  const { t, lang } = useT();
  const store = useLnStore();
  const mode = store.serviceModes.takeaway;
  if (mode !== 'online') {
    return <ServiceFallbackModal open={open} onClose={onClose} service="takeaway" />;
  }
  const tt = t.takeaway;
  const [step, setStep] = useStateTA('menu');
  const [activeCat, setActiveCat] = useStateTA(MENU_CATEGORIES[0].id);
  const [cart, setCart] = useStateTA({});
  const [bump, setBump] = useStateTA(0);
  const [pickupTime, setPickupTime] = useStateTA('asap');
  const [checkout, setCheckout] = useStateTA({ name: '', phone: '', email: '', note: '', payment: 'card' });
  const [errors, setErrors] = useStateTA({});
  const [orderRef] = useStateTA(() => 'LN-' + Math.floor(Math.random()*9000+1000));

  useEffectTA(() => {
    if (!open) {
      setTimeout(() => {
        setStep('menu'); setCart({}); setCheckout({ name: '', phone: '', email: '', note: '', payment: 'card' }); setErrors({});
      }, 250);
    }
  }, [open]);

  const add = (id) => { setCart(c => ({ ...c, [id]: (c[id] || 0) + 1 })); setBump(b => b + 1); };
  const dec = (id) => {
    setCart(c => {
      const n = (c[id] || 0) - 1; const next = { ...c };
      if (n <= 0) delete next[id]; else next[id] = n; return next;
    });
  };

  const cartLines = useMemoTA(() => Object.entries(cart).map(([id, qty]) => {
    const item = MENU_ITEMS.find(i => i.id === id);
    const info = t.dishes[id];
    return { ...item, name: info.name, qty, lineTotal: item.price * qty };
  }), [cart, lang]);

  const subtotal = cartLines.reduce((s, l) => s + l.lineTotal, 0);
  const fee = subtotal > 0 ? 1.5 : 0;
  const total = subtotal + fee;
  const itemsInCart = cartLines.reduce((s, l) => s + l.qty, 0);
  const filtered = MENU_ITEMS.filter(i => i.cat === activeCat);

  const submitCheckout = () => {
    const e = {};
    if (!checkout.name.trim()) e.name = tt.errReq;
    if (!/^[0-9 +().-]{6,}$/.test(checkout.phone.trim())) e.phone = tt.errPhone;
    if (checkout.email && !/^\S+@\S+\.\S+$/.test(checkout.email.trim())) e.email = tt.errEmail;
    setErrors(e);
    if (Object.keys(e).length === 0) {
      lnAddOrder({
        ref: orderRef,
        items: cartLines.map(l => ({ id: l.id, name: l.name, qty: l.qty, price: l.price })),
        subtotal, fee, total,
        pickupTime,
        customer: { name: checkout.name, phone: checkout.phone, email: checkout.email, note: checkout.note },
        payment: checkout.payment,
      });
      setStep('done');
    }
  };

  const timeText = pickupTime === 'asap' ? tt.doneTimeAsap : tt.doneTimeIn(pickupTime);

  return (
    <Modal open={open} onClose={onClose} width={1080} title={step === 'done' ? null : (step === 'menu' ? tt.titleMenu : tt.titleCheckout)}>
      {step === 'menu' && (
        <div className="ta-menu-grid" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 360px', minHeight: 'min(680px, 78vh)' }}>
          <div className="ta-menu-col" style={{ borderRight: '1px solid var(--line)' }}>
            <div style={{ display: 'flex', gap: 6, padding: '14px 24px', borderBottom: '1px solid var(--line)', overflowX: 'auto', position: 'sticky', top: 0, background: 'var(--paper)', zIndex: 2 }}>
              {MENU_CATEGORIES.map(c => {
                const active = c.id === activeCat;
                return (
                  <button key={c.id} onClick={() => setActiveCat(c.id)}
                    style={{ padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 600,
                      background: active ? 'var(--ink)' : 'transparent',
                      color: active ? 'var(--paper)' : 'var(--ink-soft)',
                      border: active ? '1px solid var(--ink)' : '1px solid var(--line)',
                      whiteSpace: 'nowrap' }}>
                    {t.cats[c.id]}
                  </button>
                );
              })}
            </div>
            <div className="ta-menu-list" style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
              {filtered.map(item => {
                const qty = cart[item.id] || 0;
                const info = t.dishes[item.id];
                return (
                  <div key={item.id} className="ta-item" style={{ display: 'grid', gridTemplateColumns: '120px 1fr auto', gap: 18, padding: 14, background: 'var(--card)', borderRadius: 14, border: '1px solid var(--line)' }}>
                    <div className="ta-item-img" style={{ width: 120, height: 100, borderRadius: 10, overflow: 'hidden', background: 'var(--paper-warm)' }}>
                      {item.img ? <img src={item.img} alt={info.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <DishPlaceholder label={info.name} ratio="120/100" />}
                    </div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                        <span className="serif" style={{ fontSize: 19, fontWeight: 600 }}>{info.name}</span>
                        {item.tags.includes('signature') && <Tag tone="accent">{t.tags.signature}</Tag>}
                        {item.tags.includes('popular') && <Tag tone="ok">{t.tags.popular}</Tag>}
                        {item.tags.includes('vegan') && <Tag>{t.tags.vegan}</Tag>}
                      </div>
                      <p style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5 }}>{info.desc}</p>
                      <div className="mono" style={{ marginTop: 8, fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>
                        {item.price.toFixed(2)} €
                      </div>
                    </div>
                    <div className="ta-item-action" style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                      {qty === 0 ? (
                        <Button onClick={() => add(item.id)} variant="outline" size="sm"><Icon.plus size={14} /> {tt.add}</Button>
                      ) : (
                        <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--accent)', borderRadius: 999, overflow: 'hidden' }}>
                          <button onClick={() => dec(item.id)} style={{ padding: '8px 12px', color: 'var(--accent)' }}><Icon.minus /></button>
                          <span className="mono" style={{ minWidth: 26, textAlign: 'center', fontWeight: 600, color: 'var(--accent)' }}>{qty}</span>
                          <button onClick={() => add(item.id)} style={{ padding: '8px 12px', color: 'var(--accent)' }}><Icon.plus /></button>
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="ta-cart-col" style={{ display: 'flex', flexDirection: 'column', background: 'var(--paper-warm)' }}>
            <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span key={bump} style={{ width: 30, height: 30, borderRadius: 999, background: 'var(--accent)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', animation: bump ? 'cartPulse .32s ease' : 'none' }}><Icon.bag size={16} /></span>
                <span className="serif" style={{ fontSize: 18, fontWeight: 600 }}>{tt.yourOrder}</span>
              </div>
              <span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{itemsInCart} {itemsInCart === 1 ? tt.items.one : tt.items.many}</span>
            </div>
            <div style={{ flex: 1, overflowY: 'auto', padding: '16px 22px', display: 'flex', flexDirection: 'column', gap: 12 }}>
              {cartLines.length === 0 && (
                <div style={{ color: 'var(--muted)', fontSize: 14, padding: '40px 10px', textAlign: 'center', lineHeight: 1.6 }}>
                  <div style={{ fontSize: 34, marginBottom: 10, opacity: 0.6 }}>🫓</div>
                  {tt.empty1}<br/>{tt.empty2}
                </div>
              )}
              {cartLines.map(l => (
                <div key={l.id} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 8, padding: 10, background: 'var(--card)', borderRadius: 10, border: '1px solid var(--line)' }}>
                  <div>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{l.name}</div>
                    <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>{l.price.toFixed(2)} € × {l.qty}</div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6 }}>
                    <div className="mono" style={{ fontSize: 13, fontWeight: 600 }}>{l.lineTotal.toFixed(2)} €</div>
                    <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--line)', borderRadius: 999, overflow: 'hidden' }}>
                      <button onClick={() => dec(l.id)} style={{ padding: '4px 8px', color: 'var(--ink-soft)' }}><Icon.minus size={12}/></button>
                      <span className="mono" style={{ fontSize: 12, minWidth: 18, textAlign: 'center' }}>{l.qty}</span>
                      <button onClick={() => add(l.id)} style={{ padding: '4px 8px', color: 'var(--ink-soft)' }}><Icon.plus size={12}/></button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding: '16px 22px', borderTop: '1px solid var(--line)' }}>
              <Field label={tt.pickupTime} style={{ marginBottom: 12 }}>
                <select value={pickupTime} onChange={e => setPickupTime(e.target.value)} style={{ ...inputStyle, padding: '10px 12px' }}>
                  {tt.pickupOptions.map(o => <option key={o.v} value={o.v}>{o.t}</option>)}
                </select>
              </Field>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--ink-soft)', marginBottom: 4 }}>
                <span>{tt.subtotal}</span><span className="mono">{subtotal.toFixed(2)} €</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--ink-soft)', marginBottom: 10 }}>
                <span>{tt.fee}</span><span className="mono">{fee.toFixed(2)} €</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 17, marginBottom: 14 }}>
                <span>{tt.total}</span><span className="mono">{total.toFixed(2)} €</span>
              </div>
              <Button variant="primary" size="lg" full disabled={cartLines.length === 0} onClick={() => setStep('checkout')}>
                {tt.continue} <Icon.arrow />
              </Button>
            </div>
          </div>
        </div>
      )}

      {step === 'checkout' && (
        <div className="ta-checkout" style={{ padding: '28px 32px 32px', display: 'grid', gridTemplateColumns: '1fr 360px', gap: 32 }}>
          <div>
            <div style={{ display: 'flex', gap: 14, marginBottom: 22 }}>
              <Button variant="ghost" size="sm" onClick={() => setStep('menu')}>{tt.backToMenu}</Button>
            </div>
            <div className="ln-form-grid">
              <Field label={tt.fullName} error={errors.name}>
                <TextInput value={checkout.name} onChange={e => setCheckout({ ...checkout, name: e.target.value })} placeholder={tt.placeholders.name} />
              </Field>
              <Field label={tt.phone} error={errors.phone} hint={tt.phoneHint}>
                <TextInput value={checkout.phone} onChange={e => setCheckout({ ...checkout, phone: e.target.value })} placeholder={tt.placeholders.phone} />
              </Field>
              <Field label={tt.email} error={errors.email} style={{ gridColumn: '1 / -1' }}>
                <TextInput value={checkout.email} onChange={e => setCheckout({ ...checkout, email: e.target.value })} placeholder={tt.placeholders.email} />
              </Field>
              <Field label={tt.kitchenNote} style={{ gridColumn: '1 / -1' }}>
                <textarea value={checkout.note} onChange={e => setCheckout({ ...checkout, note: e.target.value })} rows={3} placeholder={tt.kitchenNotePh} style={{ ...inputStyle, resize: 'vertical' }} />
              </Field>
            </div>
            <div style={{ marginTop: 24 }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 8 }}>{tt.payment}</div>
              <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                {[{ id: 'card', label: tt.paymentCard }, { id: 'counter', label: tt.paymentCounter }].map(p => {
                  const active = checkout.payment === p.id;
                  return (
                    <button key={p.id} onClick={() => setCheckout({ ...checkout, payment: p.id })}
                      style={{ padding: '12px 18px', borderRadius: 10,
                        background: active ? 'color-mix(in oklab, var(--accent) 12%, transparent)' : 'var(--card)',
                        border: active ? '1.5px solid var(--accent)' : '1px solid var(--line)',
                        color: active ? 'var(--accent-deep)' : 'var(--ink)',
                        fontWeight: 600, fontSize: 14 }}>{p.label}</button>
                  );
                })}
              </div>
            </div>
          </div>
          <div style={{ background: 'var(--paper-warm)', borderRadius: 14, padding: 20, alignSelf: 'start' }}>
            <div className="serif" style={{ fontSize: 20, fontWeight: 600, marginBottom: 12 }}>{tt.orderSummary}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13.5, marginBottom: 14 }}>
              {cartLines.map(l => (
                <div key={l.id} style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span>{l.qty}× {l.name}</span>
                  <span className="mono">{l.lineTotal.toFixed(2)} €</span>
                </div>
              ))}
            </div>
            <div style={{ borderTop: '1px dashed var(--line)', paddingTop: 10, display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>{tt.subtotal}</span><span className="mono">{subtotal.toFixed(2)} €</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>{tt.fee}</span><span className="mono">{fee.toFixed(2)} €</span></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 16, marginTop: 6 }}><span>{tt.total}</span><span className="mono">{total.toFixed(2)} €</span></div>
            </div>
            <div style={{ marginTop: 18 }}>
              <Button variant="primary" size="lg" full onClick={submitCheckout}>
                {tt.placeOrder} — {total.toFixed(2)} €
              </Button>
              <p style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 10, textAlign: 'center' }}>{tt.terms}</p>
            </div>
          </div>
        </div>
      )}

      {step === 'done' && (
        <div className="ln-modal-section-confirm" style={{ textAlign: 'center', maxWidth: 520, margin: '0 auto' }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, background: 'color-mix(in oklab, var(--ok) 15%, transparent)', color: 'var(--ok)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
            <Icon.check size={32} />
          </div>
          <h2 className="serif" style={{ margin: '0 0 10px', fontSize: 30, fontWeight: 600 }}>{tt.doneTitle}</h2>
          <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6 }}>
            {tt.doneBody(checkout.name.split(' ')[0] || '', orderRef, RESTAURANT_INFO.address, timeText)}
          </p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
            <Button variant="primary" onClick={onClose}>{tt.back}</Button>
            <Button variant="ghost" onClick={() => { setStep('menu'); setCart({}); }}>{tt.newOrder}</Button>
          </div>
        </div>
      )}
    </Modal>
  );
}

// Takeaway responsive styles
const _taStyle = document.createElement('style');
_taStyle.textContent = `
@media (max-width: 860px) {
  .ta-menu-grid {
    grid-template-columns: 1fr !important;
    min-height: 0 !important;
  }
  .ta-menu-col { border-right: none !important; }
  .ta-cart-col { border-top: 1px solid var(--line); }
  .ta-checkout {
    grid-template-columns: 1fr !important;
    gap: 22px !important;
    padding: 22px 20px !important;
  }
}
@media (max-width: 540px) {
  .ta-menu-list { padding: 16px !important; gap: 12px !important; }
  .ta-item {
    grid-template-columns: 88px 1fr !important;
    grid-template-rows: auto auto;
    gap: 12px !important;
    padding: 12px !important;
  }
  .ta-item-img {
    width: 88px !important;
    height: 88px !important;
    grid-row: span 2;
  }
  .ta-item-action {
    grid-column: 2 / 3;
    justify-content: flex-start !important;
  }
}
`;
document.head.appendChild(_taStyle);

Object.assign(window, { TakeawayModal });
