// rooms-page.jsx — Room management page (card grid)
// Shows live status, current occupant, next reservation, quick actions

const ROOM_FILTERS = [
  { k: 'all',         l: 'Tất cả',       ico: null },
  { k: 'occupied',    l: 'Đang ở',       ico: 'check_circle' },
  { k: 'available',   l: 'Còn trống',    ico: null },
  { k: 'cleaning',    l: 'Cần dọn',      ico: 'sparkle' },
  { k: 'maintenance', l: 'Bảo trì',      ico: 'settings' },
];

function RoomsPage({ rooms, bookings, guests, today, onOpenBooking, onNewBooking, onRoomAction, onAddRoom, onEditRoom }) {
  const data = window.HotelData;
  const [filter, setFilter] = React.useState('all');

  // Compute effective status per room (considering current bookings)
  const enrichedRooms = React.useMemo(() => {
    const todayDay = startOfDay(today);
    return rooms.map(r => {
      // Find current occupant (a non-cancelled booking covering today)
      const current = bookings.find(b =>
        b.roomId === r.id &&
        b.status !== 'cancelled' &&
        b.status !== 'maintenance' &&
        startOfDay(b.checkIn) <= todayDay &&
        startOfDay(b.checkOut) > todayDay
      );
      // Find next upcoming booking
      const upcoming = bookings
        .filter(b => b.roomId === r.id && b.status !== 'cancelled' && startOfDay(b.checkIn) > todayDay)
        .sort((a, b) => a.checkIn - b.checkIn)[0];

      let effectiveStatus = r.status;
      if (current) effectiveStatus = 'occupied';
      else if (r.status === 'cleaning') effectiveStatus = 'cleaning';
      else if (r.status === 'maintenance') effectiveStatus = 'maintenance';
      else effectiveStatus = 'available';

      // Also handle if maintenance is scheduled by booking
      const maintBlock = bookings.find(b =>
        b.roomId === r.id &&
        b.status === 'maintenance' &&
        startOfDay(b.checkIn) <= todayDay &&
        startOfDay(b.checkOut) > todayDay
      );
      if (maintBlock) effectiveStatus = 'maintenance';

      return { ...r, effectiveStatus, current, upcoming, maintBlock };
    });
  }, [rooms, bookings, today]);

  // Counts for filters
  const counts = React.useMemo(() => {
    const c = { all: enrichedRooms.length, occupied: 0, available: 0, cleaning: 0, maintenance: 0 };
    enrichedRooms.forEach(r => { c[r.effectiveStatus] = (c[r.effectiveStatus] || 0) + 1; });
    return c;
  }, [enrichedRooms]);

  // Today revenue (rooms occupied)
  const todayRevenue = enrichedRooms
    .filter(r => r.current)
    .reduce((sum, r) => sum + r.price, 0);

  const filtered = enrichedRooms.filter(r => filter === 'all' || r.effectiveStatus === filter);

  return (
    <div className="rooms-page">
      {/* KPIs */}
      <div className="rm-kpis">
        <div className="rm-kpi s-total">
          <div className="k-dot" />
          <div className="k-lbl">Tổng doanh thu</div>
          <div className="k-val">{VNDshort(todayRevenue)}đ</div>
          <div className="k-trend">Đêm nay · {enrichedRooms.filter(r => r.current).length} phòng đang ở</div>
        </div>
        <div className="rm-kpi s-occupied">
          <div className="k-dot" />
          <div className="k-lbl">Đang ở</div>
          <div className="k-val">{counts.occupied}</div>
          <div className="k-trend">Lấp đầy {Math.round((counts.occupied / rooms.length) * 100)}%</div>
        </div>
        <div className="rm-kpi s-available">
          <div className="k-dot" />
          <div className="k-lbl">Sẵn sàng</div>
          <div className="k-val">{counts.available}</div>
          <div className="k-trend">Còn nhận khách</div>
        </div>
        <div className="rm-kpi s-cleaning">
          <div className="k-dot" />
          <div className="k-lbl">Cần dọn</div>
          <div className="k-val">{counts.cleaning}</div>
          <div className="k-trend">Housekeeping</div>
        </div>
        <div className="rm-kpi s-maintenance">
          <div className="k-dot" />
          <div className="k-lbl">Bảo trì</div>
          <div className="k-val">{counts.maintenance}</div>
          <div className="k-trend">Tạm khóa</div>
        </div>
      </div>

      {/* Toolbar */}
      <div className="rm-toolbar">
        <div className="rm-filters">
          {ROOM_FILTERS.map(f => (
            <button
              key={f.k}
              className={`rm-filter ${filter === f.k ? 'active' : ''}`}
              onClick={() => setFilter(f.k)}
            >
              <span>{f.l}</span>
              <span className="f-count">{counts[f.k] ?? 0}</span>
            </button>
          ))}
        </div>
        <button className="rm-add-btn" onClick={onAddRoom}>
          <Icon name="plus" size={14} stroke={2.5} />
          Thêm phòng
        </button>
      </div>

      {/* Grid */}
      <div className="rm-grid">
        {filtered.map(r => (
          <RoomCard
            key={r.id}
            room={r}
            guests={guests}
            today={today}
            onOpenBooking={onOpenBooking}
            onNewBooking={onNewBooking}
            onRoomAction={onRoomAction}
            onEditRoom={onEditRoom}
          />
        ))}
        {filter === 'all' && (
          <button className="room-card add-card" onClick={onAddRoom}>
            <span className="ac-plus"><Icon name="plus" size={22} stroke={2.2} /></span>
            <span className="ac-title">Thêm phòng mới</span>
            <span className="ac-sub">Tạo phòng với tên, tiện nghi, giá — hiển thị ngay trên lịch</span>
          </button>
        )}
        {filtered.length === 0 && filter !== 'all' && (
          <div style={{ gridColumn: '1 / -1', padding: 40, textAlign: 'center', color: 'var(--ink-4)' }}>
            Không có phòng nào ở trạng thái này.
          </div>
        )}
      </div>
    </div>
  );
}

function RoomCard({ room, guests, today, onOpenBooking, onNewBooking, onRoomAction, onEditRoom }) {
  const r = room;
  const guest = r.current ? findGuest(guests, r.current.guestId) : null;
  const status = r.effectiveStatus;

  const STATUS_META = {
    occupied:    { l: 'Đang ở',    color: 'var(--primary)' },
    available:   { l: 'Trống',     color: 'var(--status-walkin)' },
    cleaning:    { l: 'Đang dọn',  color: 'var(--status-pending)' },
    maintenance: { l: 'Bảo trì',   color: 'var(--status-maint)' },
  };
  const sm = STATUS_META[status];

  return (
    <div className="room-card" data-type={r.type.startsWith('Suite') ? 'Suite' : r.type} onClick={() => onEditRoom && onEditRoom(r)}>
      {/* Banner */}
      <div className="room-banner">
        {/* Subtle line-art background based on type */}
        <svg className="b-art" viewBox="0 0 320 100" preserveAspectRatio="none">
          {r.type.startsWith('Suite') ? (
            <>
              <path d="M0 80 L60 30 L100 50 L160 10 L220 40 L280 20 L320 50 L320 100 L0 100 Z" fill="white" opacity=".22"/>
              <circle cx="260" cy="22" r="6" fill="white" opacity=".4"/>
              <circle cx="230" cy="15" r="2" fill="white" opacity=".6"/>
              <circle cx="290" cy="10" r="1.5" fill="white" opacity=".6"/>
            </>
          ) : r.type === 'Deluxe' ? (
            <>
              <path d="M0 70 L80 25 L150 55 L220 20 L320 60 L320 100 L0 100 Z" fill="white" opacity=".22"/>
              <path d="M260 30 Q280 15 300 30" stroke="white" strokeWidth="1" fill="none" opacity=".5"/>
            </>
          ) : (
            <>
              <path d="M0 75 Q80 50 160 70 T320 60 L320 100 L0 100 Z" fill="white" opacity=".2"/>
              <path d="M40 50 Q50 35 60 50 Q70 35 80 50" stroke="white" strokeWidth="1" fill="none" opacity=".5"/>
            </>
          )}
        </svg>
        <span className="b-num">P.{r.number} · Tầng {r.floor}</span>
        <span className="b-status">
          <span className="pill-dot" style={{ background: sm.color }} />
          {sm.l}
        </span>
        <div className="b-name">{r.name || ('Phòng ' + r.number)}</div>
      </div>

      {/* Body */}
      <div className="room-body">
        <div className="room-meta">
          <span className="m-it"><Icon name="bed" size={14} /> {r.bed}</span>
          <span className="m-it"><Icon name="users" size={14} /> {r.cap}</span>
          <span className="room-price">{VNDshort(r.price)}đ<span className="per">/đêm</span></span>
        </div>

        {r.features && r.features.length > 0 && (
          <div className="room-features">
            {r.features.slice(0, 4).map((f, i) => (
              <span key={i} className="room-feature">{f}</span>
            ))}
            {r.features.length > 4 && <span className="room-feature">+{r.features.length - 4}</span>}
          </div>
        )}

        {/* Current state */}
        {status === 'occupied' && guest && (
          <div className="room-state s-occupied" onClick={(e) => { e.stopPropagation(); onOpenBooking(r.current); }}>
            <div className="rs-avatar">{initials(guest.name)}</div>
            <div className="rs-meta">
              <div className="rs-h">{guest.name}</div>
              <div className="rs-sub">Trả phòng {formatDateShort(r.current.checkOut)} · {r.current.checkOutTime}</div>
            </div>
            <div className="rs-ico"><Icon name="arrow_right" size={14} /></div>
          </div>
        )}
        {status === 'available' && (
          <div className="room-state s-available">
            <div className="rs-ico"><Icon name="check_circle" size={16} /></div>
            <div className="rs-meta">
              <div className="rs-h">Sẵn sàng đón khách</div>
              <div className="rs-sub">
                {r.upcoming
                  ? 'Có khách đặt từ ' + formatDateShort(r.upcoming.checkIn)
                  : 'Chưa có đặt phòng kế tiếp'}
              </div>
            </div>
          </div>
        )}
        {status === 'cleaning' && (
          <div className="room-state s-cleaning">
            <div className="rs-ico"><Icon name="sparkle" size={14} /></div>
            <div className="rs-meta">
              <div className="rs-h">Housekeeping đang dọn</div>
              <div className="rs-sub">Dự kiến xong trong ~30 phút</div>
            </div>
          </div>
        )}
        {status === 'maintenance' && (
          <div className="room-state s-maintenance">
            <div className="rs-ico"><Icon name="settings" size={14} /></div>
            <div className="rs-meta">
              <div className="rs-h">Đang bảo trì</div>
              <div className="rs-sub">{r.maintBlock?.note || 'Tạm khóa khỏi hệ thống'}</div>
            </div>
          </div>
        )}
      </div>

      {/* Footer actions */}
      <div className="room-foot">
        <button className="rf-btn" onClick={(e) => { e.stopPropagation(); onRoomAction(r, 'history'); }}>
          <Icon name="clock" size={12} /> Lịch sử
        </button>
        {status === 'available' && (
          <button className="rf-btn" onClick={(e) => { e.stopPropagation(); onRoomAction(r, 'block'); }}>
            <Icon name="settings" size={12} /> Khóa phòng
          </button>
        )}
        {status === 'cleaning' && (
          <button className="rf-btn" onClick={(e) => { e.stopPropagation(); onRoomAction(r, 'done_cleaning'); }}>
            <Icon name="check" size={12} stroke={2.5} /> Đã dọn xong
          </button>
        )}
        {status === 'maintenance' && (
          <button className="rf-btn" onClick={(e) => { e.stopPropagation(); onRoomAction(r, 'reopen'); }}>
            <Icon name="refresh" size={12} /> Mở lại
          </button>
        )}
        {(status === 'available') && (
          <button className="rf-btn primary" onClick={(e) => { e.stopPropagation(); onNewBooking(r.id); }}>
            <Icon name="plus" size={12} stroke={2.5} /> Đặt phòng
          </button>
        )}
        {status === 'occupied' && (
          <button className="rf-btn primary" onClick={(e) => { e.stopPropagation(); onOpenBooking(r.current); }}>
            Xem chi tiết <Icon name="arrow_right" size={12} />
          </button>
        )}
      </div>
    </div>
  );
}

window.RoomsPage = RoomsPage;
