// booking-drawer.jsx — Right-side drawer with booking detail

function BookingDrawer({ booking, onClose, onAction, onEdit, onOrder, onMarkOrderServed }) {
  const data = window.HotelData;
  const room = findRoom(data.rooms, booking.roomId);
  const guest = booking.guestId ? findGuest(data.guests, booking.guestId) : booking._newGuest || null;
  const t = computeBookingTotal(booking, data.rooms, data.serviceCatalog, data.inStayMenu);
  const status = data.statuses.find(s => s.key === booking.status);
  const balance = Math.max(0, t.total - (booking.paid || 0));

  const isMaint = booking.status === 'maintenance';
  const isCancelled = booking.status === 'cancelled';
  const isActive = booking.checkedIn && !isMaint && !isCancelled;
  const orders = (booking.orders || []).slice().sort((a, b) => new Date(b.orderedAt) - new Date(a.orderedAt));
  const pendingOrders = orders.filter(o => o.status === 'pending').length;

  // Activity log (synthetic)
  const activity = [
    { h: 'Tạo đặt phòng', m: booking.createdBy + ' · ' + formatDateShort(window.HotelData.addDays(booking.checkIn, -3)) },
  ];
  if (booking.paid > 0) activity.push({ h: 'Ghi nhận thanh toán', m: `${VND(booking.paid)} · ${booking.paymentMethod === 'card' ? 'Thẻ' : booking.paymentMethod === 'cash' ? 'Tiền mặt' : booking.paymentMethod === 'transfer' ? 'Chuyển khoản' : 'Khác'}` });
  if (booking.checkedIn) activity.push({ h: 'Khách đã nhận phòng', m: 'Lễ tân Hà · ' + formatDateShort(booking.checkIn) + ' ' + booking.checkInTime });

  return (
    <>
      <div className="scrim" style={{ background: 'rgba(32,33,36,.25)' }} onClick={onClose} />
      <aside className="drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-hd">
          <div style={{ flex: 1 }}>
            <h3>
              {isMaint ? 'Bảo trì phòng' : guest?.name || 'Khách'}
              <span className={`pill s-${booking.status}`}>
                <span className="pill-dot" />
                {status?.label}
              </span>
            </h3>
            <div className="id">Mã: {booking.code} · #{booking.id}</div>
          </div>
          <div className="qr" title="QR check-in" />
          <button className="modal-x" onClick={onClose} aria-label="Đóng">
            <Icon name="x" size={20} />
          </button>
        </div>

        {!isMaint && !isCancelled && (
          <div className="drawer-actions">
            {!booking.checkedIn ? (
              <button className="btn-primary" onClick={() => onAction('checkin')}>
                <Icon name="check_circle" size={16} style={{ verticalAlign: '-3px', marginRight: 6 }} />
                Nhận phòng
              </button>
            ) : (
              <button className="btn-primary" onClick={() => onAction('checkout')} style={{ background: 'var(--status-walkin)' }}>
                <Icon name="arrow_right" size={16} style={{ verticalAlign: '-3px', marginRight: 6 }} />
                Trả phòng
              </button>
            )}
            <button className="btn-outline" onClick={onEdit}>
              <Icon name="edit" size={14} style={{ verticalAlign: '-2px', marginRight: 4 }} /> Sửa
            </button>
            <button className="btn-danger" onClick={() => onAction('cancel')}>
              <Icon name="trash" size={14} style={{ verticalAlign: '-2px', marginRight: 4 }} /> Hủy
            </button>
          </div>
        )}

        <div className="drawer-body">
          {/* Guest */}
          {guest && (
            <div className="drawer-sec">
              <h4>Khách hàng</h4>
              <div className="drawer-info-row">
                <span className="k">Tên</span>
                <span className="v strong">{guest.name}
                  {guest.returning && (
                    <span style={{ marginLeft: 8, color: 'var(--warm)', fontSize: 11, fontWeight: 600 }}>
                      <Icon name="star" size={11} style={{ verticalAlign: '-1px' }} /> Khách quen ({guest.stays} lần)
                    </span>
                  )}
                </span>
              </div>
              <div className="drawer-info-row">
                <span className="k">SĐT</span>
                <span className="v">{guest.phone}</span>
              </div>
              {guest.email && (
                <div className="drawer-info-row">
                  <span className="k">Email</span>
                  <span className="v">{guest.email}</span>
                </div>
              )}
              <div className="drawer-info-row">
                <span className="k">Giấy tờ</span>
                <span className="v">{guest.id_no} · {guest.nationality}</span>
              </div>
            </div>
          )}

          {/* Room & dates */}
          <div className="drawer-sec">
            <h4>Phòng & lịch trình</h4>
            <div className="drawer-info-row">
              <span className="k">Phòng</span>
              <span className="v strong">Phòng {room?.number} · {room?.type}</span>
            </div>
            <div className="drawer-info-row">
              <span className="k">Giường</span>
              <span className="v">{room?.bed}</span>
            </div>
            <div className="drawer-info-row">
              <span className="k">Nhận phòng</span>
              <span className="v">{formatDateVN(booking.checkIn)} · {booking.checkInTime}</span>
            </div>
            <div className="drawer-info-row">
              <span className="k">Trả phòng</span>
              <span className="v">{formatDateVN(booking.checkOut)} · {booking.checkOutTime}</span>
            </div>
            <div className="drawer-info-row">
              <span className="k">Số đêm</span>
              <span className="v">{t.nights} đêm · {booking.guests_count || 0} khách</span>
            </div>
            <div className="drawer-info-row">
              <span className="k">Nguồn</span>
              <span className="v">{booking.source}</span>
            </div>
            {booking.note && (
              <div className="drawer-info-row">
                <span className="k">Ghi chú</span>
                <span className="v" style={{ fontStyle: 'italic', color: 'var(--ink-2)' }}>"{booking.note}"</span>
              </div>
            )}
          </div>

          {/* In-stay orders (only when checked in) */}
          {!isMaint && (isActive || orders.length > 0) && (
            <div className="drawer-sec">
              <h4>
                <span>Đã gọi trong kỳ ở {orders.length > 0 && `(${orders.length})`}</span>
                {pendingOrders > 0 && (
                  <span className="pill-mini s-pending" style={{ marginLeft: 'auto' }}>
                    <span className="pill-dot" /> {pendingOrders} chờ phục vụ
                  </span>
                )}
                {isActive && (
                  <button className="h4-action primary" onClick={onOrder} style={pendingOrders > 0 ? {} : { marginLeft: 'auto' }}>
                    <Icon name="plus" size={11} stroke={2.8} /> Gọi thêm
                  </button>
                )}
              </h4>
              {orders.length === 0 ? (
                <div style={{ fontSize: 12.5, color: 'var(--ink-4)', padding: '6px 0 2px' }}>
                  Chưa có order nào trong kỳ ở này.
                </div>
              ) : (
                <div className="orders-list">
                  {orders.map(o => {
                    const item = findMenuItem(data.inStayMenu, o.itemId);
                    if (!item) return null;
                    return (
                      <div key={o.id} className="order-li">
                        <span className="o-ico">{item.icon}</span>
                        <div className="o-meta">
                          <div className="o-name">
                            <span className="qty-pill">×{o.qty}</span>
                            {item.name}
                          </div>
                          <div className="o-sub">
                            <span>{relTime(o.orderedAt)}</span>
                            <span className="dot-sep">·</span>
                            <span>{o.staff}</span>
                            <span className="dot-sep">·</span>
                            <span className={`pill-mini s-${o.status}`}>
                              <span className="pill-dot" />
                              {o.status === 'pending' ? 'Chờ phục vụ' : o.status === 'served' ? 'Đã phục vụ' : 'Đã hủy'}
                            </span>
                            {o.status === 'pending' && onMarkOrderServed && (
                              <button
                                onClick={() => onMarkOrderServed(o.id)}
                                style={{ marginLeft: 4, background: 'transparent', border: 0, color: 'var(--primary-700)', fontSize: 11, fontWeight: 600, cursor: 'pointer', padding: '2px 6px', borderRadius: 4, whiteSpace: 'nowrap' }}
                              >
                                Đánh dấu đã giao
                              </button>
                            )}
                          </div>
                          {o.note && <div className="o-note">“{o.note}”</div>}
                        </div>
                        <div className="o-total">{VND(item.price * o.qty)}</div>
                      </div>
                    );
                  })}
                </div>
              )}
            </div>
          )}

          {/* Services */}
          {booking.services && booking.services.length > 0 && (
            <div className="drawer-sec">
              <h4>Dịch vụ đã đặt trước ({booking.services.length})</h4>
              <div className="svc-list">
                {booking.services.map(s => {
                  const sv = findService(data.serviceCatalog, s.id);
                  if (!sv) return null;
                  return (
                    <div key={s.id} className="svc-li">
                      <span className="svc-ico-sm">{sv.icon}</span>
                      <div className="svc-info">
                        <div className="n">{sv.name}</div>
                        <div className="q">{s.qty} × {VND(sv.price)}{sv.unit}</div>
                      </div>
                      <div className="svc-total">{VND(sv.price * s.qty)}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Invoice */}
          {!isMaint && (
            <div className="drawer-sec">
              <h4>Hóa đơn</h4>
              <div className="pay-summary">
                <div className="pay-row">
                  <span className="lbl">Phòng × {t.nights} đêm</span>
                  <span className="val">{VND(t.roomTotal)}</span>
                </div>
                {t.servicesTotal > 0 && (
                  <div className="pay-row">
                    <span className="lbl">Dịch vụ đặt trước</span>
                    <span className="val">{VND(t.servicesTotal)}</span>
                  </div>
                )}
                {t.ordersTotal > 0 && (
                  <div className="pay-row">
                    <span className="lbl">Gọi thêm trong kỳ ở</span>
                    <span className="val">{VND(t.ordersTotal)}</span>
                  </div>
                )}
                <div className="pay-row">
                  <span className="lbl">Thuế VAT (10%)</span>
                  <span className="val">{VND(t.tax)}</span>
                </div>
                <div className="pay-row total">
                  <span className="lbl">Tổng cộng</span>
                  <span className="val">{VND(t.total)}</span>
                </div>
                <div className="pay-row" style={{ marginTop: 4 }}>
                  <span className="lbl">Đã thanh toán</span>
                  <span className="val" style={{ color: 'var(--status-walkin)' }}>{VND(booking.paid || 0)}</span>
                </div>
                <div className="pay-row">
                  <span className="lbl">Còn lại</span>
                  <span className="val" style={{ color: balance > 0 ? 'var(--status-cancel)' : 'var(--ink)' }}>
                    {VND(balance)}
                  </span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
                {balance > 0 && (
                  <button className="btn-primary" style={{ flex: 1, minWidth: 140 }}>
                    <Icon name="plus" size={14} style={{ verticalAlign: '-2px', marginRight: 4 }} stroke={2.5} />
                    Thêm thanh toán
                  </button>
                )}
                <button className="btn-outline" style={{ flex: 1, minWidth: 100 }}>
                  <Icon name="print" size={14} style={{ verticalAlign: '-2px', marginRight: 4 }} /> In
                </button>
                <button className="btn-outline" style={{ flex: 1, minWidth: 100 }}>
                  <Icon name="mail" size={14} style={{ verticalAlign: '-2px', marginRight: 4 }} /> Gửi email
                </button>
              </div>
            </div>
          )}

          {/* Activity */}
          <div className="drawer-sec" style={{ borderBottom: 'none' }}>
            <h4>Lịch sử hoạt động</h4>
            <div className="activity-log">
              {activity.map((a, i) => (
                <div key={i} className={`act-item ${i === activity.length - 1 ? 'curr' : ''}`}>
                  <div className="act-h">{a.h}</div>
                  <div className="act-m">{a.m}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </aside>
    </>
  );
}

window.BookingDrawer = BookingDrawer;
