// TableModal.jsx — Masa sipariş yönetimi
const { useState, useEffect, useRef } = React;

function TableModal({ tableId, tables, onClose, onUpdate, lang, user }) {
  const T = window.TRANS[lang];
  const table = tables.find(t => t.id === tableId);
  if (!table) return null;

  const isWaiter = user && user.role === 'waiter';
  // Empty tables now ALWAYS start with an explicit "Masayı Aç" confirm step,
  // regardless of role. From there:
  //   waiter user → 'opening' (auto open)
  //   admin user → 'waiter' (pick a name)
  const initialStep = table.occupied ? 'order' : 'confirm';
  const [step, setStep] = useState(initialStep);
  const [activeCat, setActiveCat] = useState(null);
  const [showPayment, setShowPayment] = useState(false);
  const [showReceipt, setShowReceipt] = useState(null);

  // Waiter pick is only shown to admin; waiters auto-open with their own name.
  const waiters = Store.getUsers().filter(u => u.role === 'waiter' && u.active);
  const menu = Store.getMenu().filter(m => m.active);
  const categories = Store.getCategories().filter(c => menu.some(m => m.cat === c));

  useEffect(() => {
    if (!activeCat && categories.length) setActiveCat(categories[0]);
  }, []);

  // When we enter the 'opening' step (waiter clicked "Masayı Aç"),
  // open the table on the server with their own name.
  useEffect(() => {
    if (step !== 'opening') return;
    let cancelled = false;
    (async () => {
      try {
        const updated = await Store.openTable(table.id, user.name);
        if (cancelled) return;
        onUpdate(updated);
        setStep('order');
      } catch (e) {
        if (!cancelled) onClose();
      }
    })();
    return () => { cancelled = true; };
  }, [step]);

  const orders = table.orders || [];
  const total = orders.reduce((s, o) => s + o.price * o.qty, 0);
  const catItems = menu.filter(m => m.cat === activeCat);

  const handleWaiterSelect = async (name) => {
    const updated = await Store.openTable(table.id, name);
    onUpdate(updated);
    setStep('order');
  };

  const handleAddItem = async (item) => {
    const updated = await Store.addOrderItem(table.id, { id: item.id, name: item.name, price: item.price });
    onUpdate(updated);
  };

  const handleRemove = async (itemId) => {
    const updated = await Store.removeOrderItem(table.id, itemId);
    onUpdate(updated);
  };

  const handlePayment = async (method) => {
    const t = tables.find(x => x.id === tableId);
    const receipt = {
      tableName: t.name, waiter: t.waiter,
      items: [...t.orders], total, method,
      closedAt: new Date(),
    };
    const updated = await Store.closeTable(table.id, method);
    onUpdate(updated);
    setShowPayment(false);
    setShowReceipt(receipt);
  };

  const handleCancel = async () => {
    const updated = await Store.cancelTable(table.id);
    onUpdate(updated);
    onClose();
  };

  // React to live updates that change the table state remotely.
  useEffect(() => {
    if (showReceipt || showPayment) return;
    if (step === 'order' && !table.occupied) {
      onClose();
    } else if ((step === 'waiter' || step === 'opening' || step === 'confirm') && table.occupied) {
      setStep('order');
    }
  }, [table.occupied]);

  // "Masayı Aç" pressed on the confirm screen.
  const handleOpenPress = () => {
    if (isWaiter) {
      setStep('opening');
    } else {
      setStep('waiter');
    }
  };

  // Empty table — explicit "Masayı Aç" confirm.
  if (step === 'confirm') {
    return (
      <div className="modal-overlay" onClick={onClose}>
        <div className="modal-box confirm-modal" style={{ width: 380, padding: 28 }} onClick={e => e.stopPropagation()}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 22, letterSpacing: '-0.02em' }}>{table.name}</div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--green)', marginTop: 2, letterSpacing: '0.05em' }}>BOŞ</div>
            </div>
            <button className="btn btn-ghost" style={{ fontSize: 18, padding: '6px 10px' }} onClick={onClose}>✕</button>
          </div>

          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: 'var(--green-bg)', border: '1px solid var(--green-border)',
            borderRadius: 14, padding: '32px 16px', marginBottom: 18,
          }}>
            <div style={{ fontSize: 56 }}>☕</div>
          </div>

          <div style={{ fontSize: 13, color: 'var(--text-2)', textAlign: 'center', marginBottom: 16 }}>
            {isWaiter
              ? <>Masa <strong>{user.name}</strong> adına açılacak.</>
              : <>Masayı aç ve garson seç.</>}
          </div>

          <button className="btn btn-primary"
            style={{ width: '100%', padding: '16px 0', fontSize: 16, fontWeight: 800 }}
            onClick={handleOpenPress}>
            🟢 Masayı Aç
          </button>
        </div>
      </div>
    );
  }

  if (step === 'opening') {
    return (
      <div className="modal-overlay">
        <div className="modal-box" style={{ width: 280, padding: 32, textAlign: 'center' }}>
          <div style={{ fontSize: 32 }}>⏳</div>
          <div style={{ marginTop: 8, color: 'var(--text-2)', fontSize: 14 }}>{table.name} açılıyor…</div>
        </div>
      </div>
    );
  }

  if (showReceipt) {
    return (
      <div className="modal-overlay" onClick={onClose}>
        <div className="modal-box receipt-modal" style={{ width: 340, padding: 32 }} onClick={e => e.stopPropagation()}>
          <div style={{ textAlign: 'center', marginBottom: 24 }}>
            <div style={{ fontSize: 40 }}>🧾</div>
            <div style={{ fontWeight: 700, fontSize: 20, marginTop: 8 }}>{showReceipt.tableName}</div>
            <div style={{ color: 'var(--text-2)', fontSize: 13, marginTop: 4 }}>
              {showReceipt.waiter} • {showReceipt.method === 'cash' ? T.cash : T.card}
            </div>
          </div>
          <div style={{ borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)', padding: '16px 0', marginBottom: 16 }}>
            {showReceipt.items.map(item => (
              <div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, marginBottom: 8 }}>
                <span>{item.qty}x {item.name}</span>
                <span style={{ fontWeight: 600 }}>{fmt(item.price * item.qty)}</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 18, marginBottom: 24 }}>
            <span>{T.total}</span>
            <span style={{ color: 'var(--accent)' }}>{fmt(showReceipt.total)}</span>
          </div>
          <button className="btn btn-primary" style={{ width: '100%' }} onClick={onClose}>{T.close}</button>
        </div>
      </div>
    );
  }

  if (showPayment) {
    return (
      <div className="modal-overlay" onClick={() => setShowPayment(false)}>
        <div className="modal-box payment-modal" style={{ width: 360, padding: 32 }} onClick={e => e.stopPropagation()}>
          <div style={{ fontWeight: 700, fontSize: 18, marginBottom: 8 }}>{T.confirmPayment}</div>
          <div style={{ color: 'var(--text-2)', fontSize: 14, marginBottom: 24 }}>
            {T.total}: <strong style={{ color: 'var(--accent)', fontSize: 20 }}>{fmt(total)}</strong>
          </div>
          <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
            <button className="btn btn-outline" style={{ flex: 1, padding: '16px 0', fontSize: 16 }} onClick={() => handlePayment('cash')}>
              💵 {T.cash}
            </button>
            <button className="btn btn-outline" style={{ flex: 1, padding: '16px 0', fontSize: 16 }} onClick={() => handlePayment('card')}>
              💳 {T.card}
            </button>
          </div>
          <button className="btn btn-ghost" style={{ width: '100%' }} onClick={() => setShowPayment(false)}>{T.cancel}</button>
        </div>
      </div>
    );
  }

  if (step === 'waiter') {
    return (
      <div className="modal-overlay waiter-pick-overlay" onClick={onClose}>
        <div className="modal-box waiter-pick-modal" style={{ width: 400, padding: 28 }} onClick={e => e.stopPropagation()}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18 }}>
            <div>
              <div style={{ fontWeight: 800, fontSize: 20, letterSpacing: '-0.02em' }}>{table.name}</div>
              <div style={{ color: 'var(--text-2)', fontSize: 13, marginTop: 2 }}>Masayı kim açıyor?</div>
            </div>
            <button className="btn btn-ghost" style={{ fontSize: 18, padding: '6px 10px' }} onClick={onClose}>✕</button>
          </div>
          <div className="waiter-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {waiters.length === 0 ? (
              <div style={{ gridColumn: '1 / -1', textAlign: 'center', color: 'var(--text-3)', fontSize: 13, padding: '20px 0' }}>
                Aktif garson yok. Yönetim → Kullanıcılar'dan ekle.
              </div>
            ) : waiters.map(w => (
              <button key={w.id} className="btn btn-outline" style={{ padding: '18px 12px', fontSize: 15, fontWeight: 700 }}
                onClick={() => handleWaiterSelect(w.name)}>
                👤 {w.name}
              </button>
            ))}
          </div>
          <button className="btn btn-ghost" style={{ width: '100%', marginTop: 14 }}
            onClick={() => setStep('confirm')}>← Geri</button>
        </div>
      </div>
    );
  }

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal-box modal-fullscreen" style={{ width: 860, height: '88vh', flexDirection: 'column' }} onClick={e => e.stopPropagation()}>

        <div className="tm-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px', borderBottom: '1px solid var(--border)', flexShrink: 0 }}>
          <div className="tm-header-info">
            <div style={{ fontWeight: 700, fontSize: 20 }}>{table.name}</div>
            <div style={{ color: 'var(--text-2)', fontSize: 13, marginTop: 2 }}>
              {T.waiter}: <strong>{table.waiter}</strong>
              {table.openedAt && <span style={{ marginLeft: 12, color: 'var(--text-3)' }}>⏱ {elapsed(table.openedAt)}</span>}
            </div>
          </div>
          {/* ✕ alone — destructive actions live in the order panel footer
              so an accidental tap on close doesn't free the table. */}
          <button className="btn btn-ghost" style={{ fontSize: 20, padding: '8px 14px' }} onClick={onClose} title="Kapat">✕</button>
        </div>

        <div className="tm-body" style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>

          <div className="tm-menu-side" style={{ flex: 1, display: 'flex', flexDirection: 'column', borderRight: '1px solid var(--border)' }}>
            <div className="tm-cat-tabs" style={{ display: 'flex', gap: 4, padding: '12px 16px', overflowX: 'auto', flexShrink: 0, borderBottom: '1px solid var(--border)' }}>
              {categories.map(cat => (
                <button key={cat} onClick={() => setActiveCat(cat)}
                  style={{
                    padding: '7px 14px', borderRadius: 20, border: 'none', cursor: 'pointer', whiteSpace: 'nowrap',
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 600, transition: 'all 0.15s',
                    background: activeCat === cat ? 'var(--accent)' : 'var(--border)',
                    color: activeCat === cat ? 'white' : 'var(--text-2)',
                  }}>
                  {cat}
                </button>
              ))}
            </div>
            <div className="tm-menu-grid" style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10, alignContent: 'start' }}>
              {catItems.map(item => {
                const inOrder = orders.find(o => o.id === item.id);
                const qty = inOrder ? inOrder.qty : 0;
                return (
                  <div key={item.id} onClick={() => handleAddItem(item)}
                    style={{
                      padding: '12px 10px', borderRadius: 10, border: '1.5px solid',
                      borderColor: qty > 0 ? 'var(--accent)' : 'var(--border)',
                      background: qty > 0 ? 'var(--accent-light)' : 'var(--surface)',
                      cursor: 'pointer', fontFamily: 'inherit', transition: 'all 0.15s',
                      display: 'flex', flexDirection: 'column',
                      userSelect: 'none', WebkitTapHighlightColor: 'transparent',
                    }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', marginBottom: 4, lineHeight: 1.3 }}>{item.name}</div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--accent)' }}>{fmt(item.price)}</div>
                    {qty > 0 && (
                      <div onClick={(e) => e.stopPropagation()}
                        style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          marginTop: 10, paddingTop: 10,
                          borderTop: '1px solid rgba(232,89,12,0.25)',
                          gap: 8,
                        }}>
                        <button onClick={() => handleRemove(item.id)}
                          aria-label="azalt"
                          style={{
                            width: 36, height: 36, borderRadius: 8,
                            border: '1.5px solid var(--accent)',
                            background: 'white', color: 'var(--accent)',
                            fontSize: 20, fontWeight: 700, cursor: 'pointer',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            flexShrink: 0,
                          }}>−</button>
                        <div style={{ fontWeight: 800, fontSize: 18, color: 'var(--accent)' }}>{qty}</div>
                        <button onClick={() => handleAddItem(item)}
                          aria-label="arttır"
                          style={{
                            width: 36, height: 36, borderRadius: 8, border: 'none',
                            background: 'var(--accent)', color: 'white',
                            fontSize: 20, fontWeight: 700, cursor: 'pointer',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            flexShrink: 0,
                          }}>+</button>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>

          <div className={`tm-order-panel${orders.length === 0 ? ' tm-order-panel-empty' : ''}`} style={{ width: 260, display: 'flex', flexDirection: 'column', background: '#FAFAF8' }}>
            <div className="tm-order-header" style={{ padding: '14px 16px', borderBottom: '1px solid var(--border)', fontWeight: 600, fontSize: 14, color: 'var(--text-2)' }}>
              Sipariş ({orders.length} ürün)
            </div>
            <div className="tm-order-list" style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
              {orders.length === 0 ? (
                <div style={{ textAlign: 'center', color: 'var(--text-3)', fontSize: 13, marginTop: 40 }}>{T.noOrders}</div>
              ) : orders.map(o => (
                <div key={o.id} style={{
                  display: 'flex', alignItems: 'center', gap: 8, padding: '8px 10px',
                  background: 'white', borderRadius: 8, marginBottom: 6, boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
                }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{o.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-2)' }}>{fmt(o.price)} × {o.qty}</div>
                  </div>
                  <div style={{ fontWeight: 700, fontSize: 13, color: 'var(--accent)', minWidth: 52, textAlign: 'right' }}>{fmt(o.price * o.qty)}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                    <button onClick={() => handleAddItem({ id: o.id, name: o.name, price: o.price })}
                      className="qty-btn"
                      style={{ width: 22, height: 22, borderRadius: 4, border: '1px solid var(--border)', background: 'white', cursor: 'pointer', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+</button>
                    <button onClick={() => handleRemove(o.id)}
                      className="qty-btn"
                      style={{ width: 22, height: 22, borderRadius: 4, border: '1px solid var(--border)', background: 'white', cursor: 'pointer', fontWeight: 700, fontSize: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--red)' }}>−</button>
                  </div>
                </div>
              ))}
            </div>
            <div style={{ padding: '14px 16px', borderTop: '1px solid var(--border)', background: 'white' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontWeight: 600, fontSize: 14, color: 'var(--text-2)' }}>{T.total}</span>
                <span style={{ fontWeight: 800, fontSize: 20, color: 'var(--accent)' }}>{fmt(total)}</span>
              </div>
              {orders.length > 0 ? (
                <button
                  onClick={() => setShowPayment(true)}
                  style={{
                    width: '100%', marginTop: 12, padding: '12px 0',
                    fontFamily: 'inherit', fontSize: 14, fontWeight: 700,
                    border: '1.5px solid var(--accent)', borderRadius: 8,
                    background: 'transparent', color: 'var(--accent)',
                    cursor: 'pointer', transition: 'all 0.12s',
                  }}
                  onMouseEnter={(e) => {
                    e.currentTarget.style.background = 'var(--accent)';
                    e.currentTarget.style.color = 'white';
                  }}
                  onMouseLeave={(e) => {
                    e.currentTarget.style.background = 'transparent';
                    e.currentTarget.style.color = 'var(--accent)';
                  }}>
                  💳 Hesabı Al
                </button>
              ) : (
                <button className="btn btn-danger"
                  style={{ width: '100%', marginTop: 12, fontSize: 14, padding: '14px 0' }}
                  onClick={handleCancel}>
                  ✕ {T.closeTable}
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TableModal });
