// sidebar.jsx — Left sidebar for Sao Mai Hotel
// Logo, +New, nav, mini calendar, room filters, quick stats

const NAV_ITEMS = [
  { key: 'calendar', label: 'Lịch đặt phòng', icon: 'calendar', badge: null },
  { key: 'bookings', label: 'Danh sách đặt phòng', icon: 'list', badge: 13 },
  { key: 'invoices', label: 'Hóa đơn', icon: 'invoice', badge: 8 },
  { key: 'services', label: 'Dịch vụ', icon: 'sparkle', badge: null },
  { key: 'rooms', label: 'Phòng', icon: 'bed', badge: null },
  { key: 'reports', label: 'Báo cáo', icon: 'chart', badge: null },
];

function MiniCalendar({ value, onPick, bookings, today }) {
  const [view, setView] = React.useState(() => {
    const d = new Date(value || today);
    return new Date(d.getFullYear(), d.getMonth(), 1);
  });

  const monthName = `${MONTH_VN[view.getMonth()]} ${view.getFullYear()}`;
  const firstDow = view.getDay();
  const daysInMonth = new Date(view.getFullYear(), view.getMonth() + 1, 0).getDate();
  const prevMonthDays = new Date(view.getFullYear(), view.getMonth(), 0).getDate();

  // Build 6 weeks of 7 = 42 cells
  const cells = [];
  for (let i = 0; i < firstDow; i++) {
    cells.push({
      d: new Date(view.getFullYear(), view.getMonth() - 1, prevMonthDays - firstDow + 1 + i),
      muted: true,
    });
  }
  for (let i = 1; i <= daysInMonth; i++) {
    cells.push({ d: new Date(view.getFullYear(), view.getMonth(), i), muted: false });
  }
  while (cells.length < 42) {
    const last = cells[cells.length - 1].d;
    cells.push({ d: new Date(last.getFullYear(), last.getMonth(), last.getDate() + 1), muted: true });
  }

  // Booking presence per date
  const hasBooking = (d) => bookings.some(b => {
    const a = startOfDay(b.checkIn), c = startOfDay(b.checkOut);
    const x = startOfDay(d);
    return x >= a && x < c && b.status !== 'cancelled';
  });

  return (
    <div className="mc">
      <div className="mc-head">
        <div className="mc-title">{monthName}</div>
        <div className="mc-nav">
          <button onClick={() => setView(new Date(view.getFullYear(), view.getMonth() - 1, 1))} aria-label="Tháng trước">
            <Icon name="chevron_left" size={16} />
          </button>
          <button onClick={() => setView(new Date(view.getFullYear(), view.getMonth() + 1, 1))} aria-label="Tháng sau">
            <Icon name="chevron_right" size={16} />
          </button>
        </div>
      </div>
      <div className="mc-grid">
        {DOW_VN.map((d, i) => <div key={i} className="mc-dow">{d}</div>)}
        {cells.map((c, i) => {
          const isToday = sameDay(c.d, today);
          const isSelected = sameDay(c.d, value);
          return (
            <button
              key={i}
              className={`mc-day ${c.muted ? 'muted' : ''} ${isToday ? 'today' : ''} ${isSelected ? 'selected' : ''}`}
              onClick={() => onPick(c.d)}
            >
              {c.d.getDate()}
              {hasBooking(c.d) && <span className="dot" />}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Sidebar({
  collapsed, onToggle,
  active, onNav,
  onNewBooking,
  miniDate, setMiniDate,
  filters, setFilters,
  rooms, bookings, today,
  stats,
}) {
  return (
    <aside className="sidebar">
      <div className="sb-brand">
        <div className="sb-logo">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 18l5-9 4 6 3-4 6 7" />
            <path d="M2 22h20" />
            <path d="M15 6c1.5-1 2.5-1 3.5 0M14 3c2-1.2 3.5-1 5 0" />
          </svg>
        </div>
        {!collapsed && (
          <div>
            <div className="sb-name">Windy Hill</div>
            <div className="sb-sub">
              Homestay · Đà Lạt · <a href="booking.html" style={{ color: 'var(--primary)', textDecoration: 'none' }}>xem trang web →</a>
            </div>
          </div>
        )}
        <button className="sb-collapse" onClick={onToggle} aria-label="Thu gọn">
          <Icon name="sidebar" size={18} />
        </button>
      </div>

      <button className="sb-new" onClick={onNewBooking}>
        <span className="sb-new-ico"><Icon name="plus" size={14} stroke={2.5} /></span>
        {!collapsed && <span className="sb-new-lbl">Đặt phòng mới</span>}
      </button>

      <div className="sb-scroll">
        <ul className="sb-nav">
          {NAV_ITEMS.map(it => (
            <li key={it.key}>
              <button
                className={active === it.key ? 'active' : ''}
                onClick={() => onNav(it.key)}
                title={collapsed ? it.label : undefined}
              >
                <span className="ico"><Icon name={it.icon} size={18} stroke={active === it.key ? 2 : 1.7} /></span>
                <span className="lbl">{it.label}</span>
                {it.badge != null && <span className="badge">{it.badge}</span>}
              </button>
            </li>
          ))}
        </ul>

        {!collapsed && (
          <>
            <MiniCalendar value={miniDate} onPick={setMiniDate} bookings={bookings} today={today} />

            <div className="sb-section">Bộ lọc trạng thái</div>
            <div className="sb-filter">
              {window.HotelData.statuses.map(s => {
                const count = bookings.filter(b => b.status === s.key).length;
                const checked = filters.statuses.includes(s.key);
                return (
                  <label
                    key={s.key}
                    className="sb-chk"
                    style={{ '--swatch-c': s.color }}
                  >
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => {
                        const next = checked
                          ? filters.statuses.filter(x => x !== s.key)
                          : [...filters.statuses, s.key];
                        setFilters({ ...filters, statuses: next });
                      }}
                    />
                    <span className="swatch" />
                    <span>{s.label}</span>
                    <span className="count">{count}</span>
                  </label>
                );
              })}
            </div>

            <div className="sb-section">Loại phòng</div>
            <div className="sb-filter">
              {['Standard', 'Deluxe', 'Suite'].map(t => {
                const count = rooms.filter(r => r.type.startsWith(t)).length;
                const checked = filters.types.includes(t);
                return (
                  <label key={t} className="sb-chk" style={{ '--swatch-c': '#5f6368' }}>
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => {
                        const next = checked
                          ? filters.types.filter(x => x !== t)
                          : [...filters.types, t];
                        setFilters({ ...filters, types: next });
                      }}
                    />
                    <span className="swatch" />
                    <span>{t}</span>
                    <span className="count">{count}</span>
                  </label>
                );
              })}
            </div>

            <div className="sb-section">Hôm nay</div>
            <div className="sb-stats">
              <div className="sb-stat">
                <div className="lbl">Phòng trống</div>
                <div className="val">{stats.available}</div>
              </div>
              <div className="sb-stat">
                <div className="lbl">Nhận phòng</div>
                <div className="val">{stats.checkIns}</div>
              </div>
              <div className="sb-stat">
                <div className="lbl">Trả phòng</div>
                <div className="val">{stats.checkOuts}</div>
              </div>
              <div className="sb-stat">
                <div className="lbl">Lấp đầy</div>
                <div className="val">{stats.occupancy}%</div>
              </div>
              <div className="sb-stat revenue">
                <div className="lbl">Doanh thu hôm nay</div>
                <div className="val">{VND(stats.revenue)}</div>
              </div>
            </div>
          </>
        )}
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
