// order-modal.jsx — In-stay room service / F&B / amenities ordering
// Opens from the Booking Detail drawer's "Gọi thêm" button

const ORDER_CATEGORIES = [
  { k: 'food',    l: 'Ẩm thực',          emoji: '🍴' },
  { k: 'drink',   l: 'Đồ uống',          emoji: '🍷' },
  { k: 'amenity', l: 'Tiện nghi & dịch vụ', emoji: '✨' },
];

function relTime(d) {
  if (!d) return '';
  const date = d instanceof Date ? d : new Date(d);
  const diff = Math.floor((Date.now() - date.getTime()) / 1000);
  if (diff < 60) return 'vừa xong';
  if (diff < 3600) return `${Math.floor(diff / 60)} phút trước`;
  if (diff < 86400) return `${Math.floor(diff / 3600)} giờ trước`;
  return `${Math.floor(diff / 86400)} ngày trước`;
}

function OrderModal({ booking, onClose, onSubmit }) {
  const data = window.HotelData;
  const room = findRoom(data.rooms, booking.roomId);
  const guest = booking.guestId ? findGuest(data.guests, booking.guestId) : booking._newGuest;

  const [cat, setCat] = React.useState('food');
  const [q, setQ] = React.useState('');
  const [cart, setCart] = React.useState({});  // {itemId: qty}
  const [note, setNote] = React.useState('');

  const filteredItems = React.useMemo(() => {
    return data.inStayMenu.filter(m => {
      if (m.cat !== cat) return false;
      if (!q.trim()) return true;
      const s = q.trim().toLowerCase();
      return m.name.toLowerCase().includes(s) || (m.desc || '').toLowerCase().includes(s);
    });
  }, [cat, q, data.inStayMenu]);

  const catCount = (k) => data.inStayMenu.filter(m => m.cat === k).length;

  const setQty = (id, qty) => {
    setCart(c => {
      const next = { ...c };
      if (qty <= 0) delete next[id];
      else next[id] = qty;
      return next;
    });
  };

  const cartTotal = Object.entries(cart).reduce((sum, [id, qty]) => {
    const item = findMenuItem(data.inStayMenu, id);
    return sum + (item ? item.price * qty : 0);
  }, 0);
  const cartCount = Object.values(cart).reduce((s, q) => s + q, 0);

  const handleSend = () => {
    const newOrders = Object.entries(cart).map(([itemId, qty]) => ({
      id: 'o-' + Date.now() + '-' + itemId,
      itemId,
      qty,
      status: 'pending',
      staff: 'Lễ tân Hà',
      note: note || '',
      orderedAt: new Date(),
    }));
    onSubmit(newOrders);
  };

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal order-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-hd">
          <div>
            <h2>Gọi thêm dịch vụ</h2>
            <div className="sub">
              Phòng {room?.number} · {guest?.name || 'Khách'} ·{' '}
              <span style={{ color: 'var(--status-walkin)' }}>● đang lưu trú</span>
            </div>
          </div>
          <button className="modal-x" onClick={onClose} aria-label="Đóng">
            <Icon name="x" size={20} />
          </button>
        </div>

        <div className="order-body">
          {/* Left: menu */}
          <div className="order-left">
            <div className="order-cats">
              {ORDER_CATEGORIES.map(c => (
                <button
                  key={c.k}
                  className={`order-cat ${cat === c.k ? 'active' : ''}`}
                  onClick={() => setCat(c.k)}
                >
                  <span className="cat-emoji">{c.emoji}</span>
                  <span>{c.l}</span>
                  <span className="cat-count">{catCount(c.k)}</span>
                </button>
              ))}
            </div>
            <div className="order-search">
              <div className="tb-search" style={{ width: '100%' }}>
                <Icon name="search" size={16} className="ico" />
                <input
                  type="text"
                  placeholder="Tìm món, đồ uống, tiện nghi…"
                  value={q}
                  onChange={(e) => setQ(e.target.value)}
                  autoFocus
                />
              </div>
            </div>
            <div className="order-grid">
              {filteredItems.map(item => {
                const qty = cart[item.id] || 0;
                const inCart = qty > 0;
                return (
                  <div
                    key={item.id}
                    className={`menu-card ${inCart ? 'in-cart' : ''}`}
                    onClick={() => setQty(item.id, qty + 1)}
                  >
                    {inCart && <span className="m-badge">×{qty}</span>}
                    <div className="m-emoji">{item.icon}</div>
                    <div className="m-name">{item.name}</div>
                    <div className="m-desc">{item.desc}</div>
                    <div className="m-foot">
                      <div className={`m-price ${item.price === 0 ? 'free' : ''}`}>
                        {item.price === 0 ? 'Miễn phí' : VND(item.price) + (item.unit || '')}
                      </div>
                      <button
                        className="m-add"
                        onClick={(e) => { e.stopPropagation(); setQty(item.id, qty + 1); }}
                        aria-label="Thêm"
                      >
                        <Icon name="plus" size={14} stroke={2.8} />
                      </button>
                    </div>
                  </div>
                );
              })}
              {filteredItems.length === 0 && (
                <div style={{ gridColumn: '1 / -1', padding: 40, textAlign: 'center', color: 'var(--ink-4)' }}>
                  Không tìm thấy "{q}"
                </div>
              )}
            </div>
          </div>

          {/* Right: cart */}
          <div className="order-cart">
            <div className="cart-hd">
              <div>
                <div className="cart-room">Phiếu order · Phòng {room?.number}</div>
                <h3>Giỏ hàng</h3>
              </div>
              {cartCount > 0 && <span className="cart-count">{cartCount} món</span>}
            </div>

            {cartCount === 0 ? (
              <div className="cart-empty">
                <div className="e-emoji">🛎️</div>
                <div>Chưa có món nào.<br/>Bấm hoặc kéo món từ menu để thêm.</div>
              </div>
            ) : (
              <div className="cart-list">
                {Object.entries(cart).map(([id, qty]) => {
                  const item = findMenuItem(data.inStayMenu, id);
                  if (!item) return null;
                  return (
                    <div key={id} className="cart-item">
                      <div className="ci-emoji">{item.icon}</div>
                      <div className="ci-meta">
                        <div className="ci-name">{item.name}</div>
                        <div className="ci-price">{VND(item.price)} × {qty}</div>
                        <div className="stepper" style={{ marginTop: 4 }}>
                          <button onClick={() => setQty(id, qty - 1)}>
                            <Icon name="minus" size={14} />
                          </button>
                          <span className="qty">{qty}</span>
                          <button onClick={() => setQty(id, qty + 1)}>
                            <Icon name="plus" size={14} />
                          </button>
                        </div>
                      </div>
                      <div className="ci-controls">
                        <div className="ci-total">{VND(item.price * qty)}</div>
                        <button
                          onClick={() => setQty(id, 0)}
                          style={{ background: 'transparent', border: 0, color: 'var(--ink-4)', padding: 2, cursor: 'pointer' }}
                          aria-label="Xóa"
                        >
                          <Icon name="trash" size={13} />
                        </button>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}

            <div className="cart-note">
              <textarea
                placeholder="Ghi chú cho bếp / housekeeping…"
                value={note}
                onChange={(e) => setNote(e.target.value)}
              />
            </div>

            <div className="cart-ft">
              <div className="row">
                <span>Tạm tính</span>
                <span>{VND(cartTotal)}</span>
              </div>
              <div className="row">
                <span>Thuế VAT 10%</span>
                <span>{VND(Math.round(cartTotal * 0.1))}</span>
              </div>
              <div className="row total">
                <span className="l">Tổng</span>
                <span className="v">{VND(cartTotal + Math.round(cartTotal * 0.1))}</span>
              </div>
              <button
                className="send-btn"
                onClick={handleSend}
                disabled={cartCount === 0}
              >
                <Icon name="check_circle" size={16} stroke={2.2} />
                Gửi tới Phòng {room?.number} ({cartCount})
              </button>
              <div className="send-note">
                Sẽ tự cộng vào hóa đơn · Thông báo bếp / housekeeping
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.OrderModal = OrderModal;
window.relTime = relTime;
