// Dine-in (QR table service): menu -> send to kitchen -> confirmation
const { useState: useStateDI, useMemo: useMemoDI, useEffect: useEffectDI } = React;

function tableLabelOf(table) {
  if (!table) return '';
  if (table.name && table.number) return `${table.number} · ${table.name}`;
  return table.name || table.number || '—';
}

function DineInModal({ open, onClose, tableId }) {
  const { t, lang } = useT();
  const store = useLnStore();
  const mode = store.serviceModes.dineIn;
  const dt = t.dineIn;
  const table = useMemoDI(() => store.tables.find(x => x.id === tableId), [store.tables, tableId]);
  const label = tableLabelOf(table);

  const [activeCat, setActiveCat] = useStateDI(MENU_CATEGORIES[0].id);
  const [cart, setCart] = useStateDI({});
  const [bump, setBump] = useStateDI(0);
  const [expandedId, setExpandedId] = useStateDI(null);
  const [step, setStep] = useStateDI('menu'); // menu | done
  const [orderRef, setOrderRef] = useStateDI(null);

  useEffectDI(() => {
    if (!open) {
      setTimeout(() => { setStep('menu'); setCart({}); setOrderRef(null); }, 250);
    }
  }, [open]);

  // All hooks must be called unconditionally (React rules of hooks).
  // This useMemo MUST stay above the early returns below.
  const cartLines = useMemoDI(() => Object.entries(cart).map(([id, qty]) => {
    const item = MENU_ITEMS.find(i => i.id === id);
    const info = getDishInfo(item, lang);
    return { ...item, name: info.name, qty, lineTotal: item.price * qty };
  }), [cart, lang]);

  if (!open) return null;

  // Service disabled → fallback (phone or closed)
  if (mode !== 'online') {
    return <ServiceFallbackModal open={open} onClose={onClose} service="dineIn" />;
  }

  // QR points to a table that no longer exists
  if (!table) {
    return (
      <Modal open={open} onClose={onClose} width={500}>
        <div className="ln-modal-section-tight" style={{ textAlign: 'center' }}>
          <div style={{ width: 64, height: 64, borderRadius: 20, background: 'color-mix(in oklab, var(--err) 14%, transparent)', color: 'var(--err)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 18 }}>
            <Icon.qr size={30} />
          </div>
          <h2 className="serif" style={{ margin: '0 0 10px', fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em' }}>{dt.tableNotFoundTitle}</h2>
          <p style={{ margin: '0 auto 22px', color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6, maxWidth: 380 }}>{dt.tableNotFoundBody}</p>
          <Button variant="primary" onClick={onClose}>{dt.backToSite}</Button>
        </div>
      </Modal>
    );
  }

  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 subtotal = cartLines.reduce((s, l) => s + l.lineTotal, 0);
  const total = subtotal; // no service fee at the table
  const itemsInCart = cartLines.reduce((s, l) => s + l.qty, 0);
  const filtered = MENU_ITEMS.filter(i => i.cat === activeCat && i.available !== false);

  const sendOrder = () => {
    if (cartLines.length === 0) return;
    const ref = 'LN-' + Math.floor(Math.random() * 9000 + 1000);
    lnAddOrder({
      ref,
      service: 'dine-in',
      tableId: table.id,
      tableLabel: label,
      items: cartLines.map(l => ({ id: l.id, name: l.name, qty: l.qty, price: l.price })),
      subtotal,
      fee: 0,
      total,
      pickupTime: null,
      customer: null,
      payment: null,
    });
    setOrderRef(ref);
    setStep('done');
  };

  return (
    <Modal open={open} onClose={onClose} width={1080} title={step === 'done' ? null : dt.title(label)}>
      {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'
                    }}>
                    {getCatName(c, lang)}
                  </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 = getDishInfo(item, lang);
                const expanded = expandedId === item.id;
                return (
                  <div key={item.id} className={`ta-item${expanded ? ' is-expanded' : ''}`} 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 className="ta-item-text" style={{ minWidth: 0 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                        <span className="serif" style={{ fontSize: 19, fontWeight: 600, wordBreak: 'break-word' }}>{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 className="ta-item-desc" style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.5, wordBreak: 'break-word' }}>{info.desc}</p>
                      <div className="ta-item-meta" style={{ marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap' }}>
                        <span className="mono" style={{ fontSize: 13, color: 'var(--ink)', fontWeight: 500 }}>{item.price.toFixed(2)} €</span>
                        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                          <button
                            type="button"
                            aria-label={expanded ? 'Hide details' : 'Show details'}
                            aria-expanded={expanded}
                            onClick={() => setExpandedId(expanded ? null : item.id)}
                            className="ta-item-toggle"
                            style={{ display: 'none', width: 28, height: 28, borderRadius: 999, alignItems: 'center', justifyContent: 'center', fontSize: 14, color: 'var(--accent)', border: '1px solid color-mix(in oklab, var(--accent) 30%, var(--line))', background: 'transparent', fontWeight: 700, lineHeight: 1 }}
                          >
                            {expanded ? '−' : 'ⓘ'}
                          </button>
                          <div className="ta-item-action-mobile" style={{ display: 'none' }}>
                            {qty === 0 ? (
                              <Button onClick={() => add(item.id)} variant="primary" size="sm"><Icon.plus size={14} /> {t.takeaway.add}</Button>
                            ) : (
                              <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--accent)', borderRadius: 999, overflow: 'hidden' }}>
                                <button onClick={() => dec(item.id)} style={{ padding: '6px 10px', color: 'var(--accent)' }}><Icon.minus size={14} /></button>
                                <span className="mono" style={{ minWidth: 22, textAlign: 'center', fontWeight: 600, color: 'var(--accent)', fontSize: 13 }}>{qty}</span>
                                <button onClick={() => add(item.id)} style={{ padding: '6px 10px', color: 'var(--accent)' }}><Icon.plus size={14} /></button>
                              </div>
                            )}
                          </div>
                        </div>
                      </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} /> {t.takeaway.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 }}>{dt.yourOrder}</span>
              </div>
              <span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{itemsInCart} {itemsInCart === 1 ? t.takeaway.items.one : t.takeaway.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>
                  {dt.empty1}<br />{dt.empty2}
                </div>
              )}
              {cartLines.map(l => (
                <div key={l.id} style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) auto', gap: 8, padding: 10, background: 'var(--card)', borderRadius: 10, border: '1px solid var(--line)' }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, wordBreak: 'break-word' }}>{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 className="ta-cart-foot" style={{ padding: '16px 22px', borderTop: '1px solid var(--line)', background: 'var(--paper-warm)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 17, marginBottom: 14 }}>
                <span>{t.takeaway.total}</span><span className="mono">{total.toFixed(2)} €</span>
              </div>
              <Button variant="primary" size="lg" full disabled={cartLines.length === 0} onClick={sendOrder}>
                {dt.sendToKitchen} <Icon.arrow />
              </Button>
            </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 }}>{dt.doneTitle}</h2>
          <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6 }}>
            {dt.doneBody(label, orderRef)}
          </p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
            <Button variant="ghost" onClick={() => { setStep('menu'); }}>{dt.newOrder}</Button>
            <Button variant="primary" onClick={onClose}>{dt.backToSite}</Button>
          </div>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { DineInModal });
