// booking-app.jsx — Customer-facing booking site for Windy Hill Homestay
// Views: home → detail → checkout → confirm

// ─── Helpers ────────────────────────────────────────────
const dateInputISO = (d) => {
  if (!d) return '';
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const dd = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${dd}`;
};
const parseDateInput = (s) => {
  if (!s) return null;
  const [y, m, d] = s.split('-').map(Number);
  return new Date(y, m - 1, d);
};

const isRoomAvailable = (room, ci, co, bookings) => {
  if (room.status === 'maintenance') return false;
  if (!ci || !co) return true;
  const ciD = startOfDay(ci), coD = startOfDay(co);
  return !bookings.some(b => {
    if (b.roomId !== room.id) return false;
    if (b.status === 'cancelled') return false;
    const bi = startOfDay(b.checkIn), bo = startOfDay(b.checkOut);
    return ciD < bo && coD > bi;  // intervals overlap
  });
};

// Find the next available start date for a room (within 60 days)
const nextAvailableDate = (room, fromDate, nights, bookings) => {
  if (!fromDate || !nights) return null;
  for (let i = 1; i <= 60; i++) {
    const candidateIn = window.HotelData.addDays(fromDate, i);
    const candidateOut = window.HotelData.addDays(candidateIn, nights);
    if (isRoomAvailable(room, candidateIn, candidateOut, bookings)) {
      return candidateIn;
    }
  }
  return null;
};

// Map room type/theme to placeholder SVG art
const ROOM_ART = {
  'suoi':  <><path d="M50 350 Q150 280 250 340 T450 320 T650 350" stroke="white" strokeWidth="3" fill="none" opacity=".8"/><path d="M50 400 Q200 340 350 390 T650 410" stroke="white" strokeWidth="2.5" fill="none" opacity=".6"/><path d="M50 450 Q180 410 320 440 T650 450" stroke="white" strokeWidth="2" fill="none" opacity=".4"/></>,
  'la':    <><path d="M200 100 Q260 80 340 120 Q400 200 360 320 Q300 360 220 320 Q160 220 200 100 Z" fill="white" opacity=".55"/><path d="M280 140 L280 300" stroke="rgba(60,80,40,.4)" strokeWidth="2"/></>,
  'da':    <><circle cx="280" cy="280" r="120" fill="white" opacity=".5"/><ellipse cx="380" cy="320" rx="60" ry="40" fill="white" opacity=".4"/></>,
  'co':    <><path d="M150 380 L180 200 L200 380 M220 380 L250 220 L270 380 M290 380 L320 180 L340 380 M360 380 L390 240 L410 380 M430 380 L460 210 L480 380" stroke="white" strokeWidth="2.5" fill="none" opacity=".7"/></>,
  'may':   <><ellipse cx="220" cy="180" rx="100" ry="40" fill="white" opacity=".7"/><ellipse cx="350" cy="220" rx="120" ry="50" fill="white" opacity=".6"/><ellipse cx="220" cy="260" rx="80" ry="30" fill="white" opacity=".4"/></>,
  'gio':   <><path d="M80 200 Q150 180 250 200 Q350 220 450 200" stroke="white" strokeWidth="3" fill="none" opacity=".7"/><path d="M120 260 Q180 240 280 260 Q380 280 480 260" stroke="white" strokeWidth="2.5" fill="none" opacity=".55"/><path d="M150 320 Q200 300 290 320 Q380 340 470 320" stroke="white" strokeWidth="2" fill="none" opacity=".4"/></>,
  'suong': <><circle cx="150" cy="200" r="40" fill="white" opacity=".4"/><circle cx="280" cy="230" r="55" fill="white" opacity=".35"/><circle cx="400" cy="200" r="45" fill="white" opacity=".4"/><circle cx="200" cy="320" r="40" fill="white" opacity=".3"/><circle cx="370" cy="340" r="50" fill="white" opacity=".35"/></>,
  'nang':  <><circle cx="350" cy="180" r="60" fill="rgba(255,225,150,.7)"/><g stroke="rgba(255,225,150,.5)" strokeWidth="2"><line x1="350" y1="80" x2="350" y2="110"/><line x1="350" y1="250" x2="350" y2="280"/><line x1="250" y1="180" x2="280" y2="180"/><line x1="420" y1="180" x2="450" y2="180"/></g></>,
  'trang': <><circle cx="380" cy="160" r="55" fill="white" opacity=".85"/><circle cx="395" cy="150" r="42" fill="rgba(120,140,110,.5)" opacity=".5"/></>,
  'mountain': <><path d="M0 480 L180 220 L260 320 L340 180 L450 280 L560 200 L650 380 L650 500 L0 500 Z" fill="white" opacity=".4"/><path d="M340 180 L370 210 L320 230 Z" fill="white" opacity=".6"/></>,
  'thong': <><g fill="white" opacity=".55"><path d="M200 380 L230 280 L250 310 L260 220 L280 250 L290 160 L310 230 L325 200 L340 290 L360 270 L380 380 Z"/><path d="M400 380 L425 290 L440 320 L450 240 L470 270 L480 180 L500 250 L515 220 L530 300 L550 280 L570 380 Z"/></g></>,
  'sao':   <><g fill="white" opacity=".85"><path d="M180 200 L195 235 L230 240 L203 263 L210 298 L180 281 L150 298 L157 263 L130 240 L165 235 Z"/></g><g fill="white" opacity=".5"><circle cx="380" cy="180" r="3"/><circle cx="420" cy="230" r="2.5"/><circle cx="350" cy="240" r="2"/><circle cx="480" cy="200" r="3.5"/><circle cx="450" cy="320" r="2.5"/><circle cx="290" cy="290" r="2"/><circle cx="500" cy="280" r="2"/></g></>,
};

function artForRoom(room) {
  const name = (room.name || '').toLowerCase();
  if (name.includes('suối')) return ROOM_ART.suoi;
  if (name.includes('lá')) return ROOM_ART.la;
  if (name.includes('đá')) return ROOM_ART.da;
  if (name.includes('cỏ')) return ROOM_ART.co;
  if (name.includes('mây')) return ROOM_ART.may;
  if (name.includes('gió')) return ROOM_ART.gio;
  if (name.includes('sương')) return ROOM_ART.suong;
  if (name.includes('nắng')) return ROOM_ART.nang;
  if (name.includes('trăng')) return ROOM_ART.trang;
  if (name.includes('đỉnh núi')) return ROOM_ART.mountain;
  if (name.includes('thông')) return ROOM_ART.thong;
  if (name.includes('sao')) return ROOM_ART.sao;
  return ROOM_ART.may;  // default
}

function PlaceholderArt({ room, kind = 'card', showName = true }) {
  const cls = room.type.startsWith('Suite') ? 'suite' : room.type === 'Deluxe' ? 'deluxe' : 'standard';
  return (
    <div className={`placeholder-art ${cls}`}>
      <svg viewBox="0 0 650 500" preserveAspectRatio="xMidYMid slice">
        {artForRoom(room)}
      </svg>
      {showName && <div className="ph-name">{room.name || ('Phòng ' + room.number)}</div>}
    </div>
  );
}

// Amenity icons
const AMENITY_ICONS = {
  'View núi': '⛰️', 'View vườn': '🌿', 'View thung lũng': '🏞️', 'View rừng thông': '🌲',
  'Hướng vườn': '🌳', 'View toàn cảnh': '🌅', 'View hồ': '🌊', 'View rừng': '🌲',
  'Ban công': '🪟', 'Ban công lớn': '🪟', 'Sân riêng': '🌱', 'Sân thượng': '🏠',
  'Sân thượng ngắm sao': '✨',
  'Bồn tắm': '🛁', 'Bồn tắm ngoài trời': '🛁', 'Jacuzzi': '♨️', 'Vòi sen mưa': '🚿',
  'Bếp nhỏ': '🍳', 'Bếp riêng': '🍳',
  'Lò sưởi điện': '🔥', 'Lò sưởi củi': '🪵', 'Lò sưởi': '🔥',
  'Tivi 4K': '📺', 'Máy lạnh': '❄️', 'Máy pha cà phê': '☕',
  'Wi-Fi nhanh': '📶', 'Bàn làm việc': '💼',
};
const amenityIcon = (a) => AMENITY_ICONS[a] || '✨';

// ─── Nav ─────────────────────────────────────────────────
function Nav({ goHome, onBookNow }) {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <div className="container nav-inner">
        <a href="#" onClick={(e) => { e.preventDefault(); goHome(); }} className="nav-brand">
          <span className="nb-logo">
            <svg width="22" height="22" 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>
          </span>
          <span>
            <div className="nb-name">Windy Hill</div>
            <div className="nb-sub">Homestay · Đà Lạt</div>
          </span>
        </a>
        <div className="nav-links">
          <a href="#rooms">Phòng</a>
          <a href="#about">Về chúng tôi</a>
          <a href="#contact">Liên hệ</a>
        </div>
        <div className="nav-spacer" />
        <a href="index.html" className="nav-admin" title="Quản trị viên">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18M3 9h18"/>
          </svg>
          Admin
        </a>
        <button className="nav-cta" onClick={onBookNow}>Đặt phòng</button>
      </div>
    </nav>
  );
}

// ─── Hero ────────────────────────────────────────────────
function Hero({ search, setSearch, onSearch }) {
  return (
    <section className="hero">
      <div className="container hero-grid">
        <div>
          <span className="hero-eyebrow">
            <span className="he-dot">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 21s7-7 7-12a7 7 0 0 0-14 0c0 5 7 12 7 12z"/><circle cx="12" cy="9" r="2.5"/>
              </svg>
            </span>
            Đà Lạt · Tháng Năm 2026 · 16–22°C
          </span>
          <h1>
            Nghỉ dưỡng giữa <em>rừng thông</em> Đà Lạt,<br/>
            mỗi đêm là một kỷ niệm.
          </h1>
          <p>
            Windy Hill là homestay 12 phòng nằm bên sườn đồi, đón gió rừng thông buổi sáng và ngắm sao buổi tối.
            Đặt phòng trực tiếp để nhận giá tốt nhất, không qua trung gian.
          </p>
          <div className="hero-stats">
            <div className="hero-stat"><div className="num">12</div><div className="lbl">Phòng</div></div>
            <div className="hero-stat"><div className="num">4.9★</div><div className="lbl">238 đánh giá</div></div>
            <div className="hero-stat"><div className="num">2hrs</div><div className="lbl">Đến trung tâm</div></div>
          </div>
        </div>
        <div className="hero-image">
          <PlaceholderArt
            room={{ name: 'Đà Lạt', type: 'Suite' }}
            kind="hero"
            showName={false}
          />
          <image-slot id="hero-image" placeholder="Kéo ảnh hero (rừng thông, sương sớm, view đồi…) vào đây"></image-slot>
          <div className="badge">
            <span className="star">★</span>
            4.9 · Superhost từ 2023
          </div>
        </div>
      </div>

      <div className="container">
        <SearchBar search={search} setSearch={setSearch} onSearch={onSearch} />
      </div>
    </section>
  );
}

function SearchBar({ search, setSearch, onSearch }) {
  const todayISO = dateInputISO(new Date());
  return (
    <div className="search-bar">
      <div className="sb-cell">
        <div className="sb-lbl">Nhận phòng</div>
        <input
          type="date"
          min={todayISO}
          value={dateInputISO(search.checkIn)}
          onChange={(e) => setSearch(s => ({ ...s, checkIn: parseDateInput(e.target.value) }))}
        />
      </div>
      <div className="sb-cell">
        <div className="sb-lbl">Trả phòng</div>
        <input
          type="date"
          min={dateInputISO(search.checkIn) || todayISO}
          value={dateInputISO(search.checkOut)}
          onChange={(e) => setSearch(s => ({ ...s, checkOut: parseDateInput(e.target.value) }))}
        />
      </div>
      <div className="sb-cell">
        <div className="sb-lbl">Số khách</div>
        <select
          value={search.guests}
          onChange={(e) => setSearch(s => ({ ...s, guests: +e.target.value }))}
        >
          {[1, 2, 3, 4, 5, 6].map(n => <option key={n} value={n}>{n} khách</option>)}
        </select>
      </div>
      <button className="sb-search-btn" onClick={onSearch}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="11" cy="11" r="7"/><path d="M20 20l-3.5-3.5"/>
        </svg>
        Tìm phòng
      </button>
    </div>
  );
}

// ─── Rooms grid ──────────────────────────────────────────
function RoomsGrid({ rooms, bookings, search, onSelect }) {
  const [favs, setFavs] = React.useState(new Set());
  const toggleFav = (id) => {
    setFavs(s => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  };

  const nights = search.checkIn && search.checkOut
    ? Math.max(1, daysBetween(search.checkIn, search.checkOut))
    : 1;

  // Compute availability for each room once
  const datesSelected = !!(search.checkIn && search.checkOut);
  const roomsWithAvail = rooms.map(r => ({
    r,
    available: isRoomAvailable(r, search.checkIn, search.checkOut, bookings),
    fitsGuests: r.cap >= search.guests,
  }));
  const availableCount = roomsWithAvail.filter(x => x.available && x.fitsGuests).length;

  return (
    <section className="section" id="rooms">
      <div className="container">
        <div className="section-hd">
          <div>
            <div className="sh-eyebrow">Phòng & Suite</div>
            <h2>Chọn không gian <em>của bạn</em>.</h2>
          </div>
          <div className="sh-sub">
            12 phòng với tên gọi và tinh thần riêng — từ Phòng Suối nhỏ xinh đến Suite Sao Trời ngắm trọn dải ngân hà.
          </div>
        </div>

        {/* Availability summary */}
        {datesSelected && (
          <div className="avail-bar">
            <div className="avail-stat">
              <span className="avail-dot" />
              <b>{availableCount}/{rooms.length}</b>
              <span>phòng còn trống</span>
            </div>
            <div className="avail-dates">
              {formatDateShort(search.checkIn)} <span style={{ color: 'var(--ink-4)' }}>→</span> {formatDateShort(search.checkOut)}
              <span className="avail-nights"> · {nights} đêm</span>
            </div>
            <div className="avail-guests">{search.guests} khách</div>
          </div>
        )}

        <div className="rooms-grid">
          {roomsWithAvail.map(({ r, available, fitsGuests }) => {
            const fav = favs.has(r.id);
            const slotId = 'room-img-' + r.id;
            const bookable = available && fitsGuests;
            const nextAvail = !available && datesSelected
              ? nextAvailableDate(r, search.checkIn, nights, bookings)
              : null;
            return (
              <article
                key={r.id}
                className={`room-card ${!bookable ? 'is-soldout' : ''}`}
                onClick={() => bookable && onSelect(r)}
              >
                <div className="room-image">
                  <PlaceholderArt room={r} />
                  <image-slot id={slotId} placeholder={`Ảnh phòng ${r.name || r.number}`}></image-slot>
                  <button
                    className={`rc-fav ${fav ? 'active' : ''}`}
                    onClick={(e) => { e.stopPropagation(); toggleFav(r.id); }}
                    aria-label="Yêu thích"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill={fav ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 21s-7-5-9-10a5 5 0 0 1 9-3 5 5 0 0 1 9 3c-2 5-9 10-9 10z"/>
                    </svg>
                  </button>
                  {datesSelected && (
                    <span className={`avail-badge ${bookable ? 'free' : !available ? 'sold' : 'cap'}`}>
                      <span className="ab-dot" />
                      {bookable ? 'Còn trống' : !available ? 'Hết phòng' : `Tối đa ${r.cap} khách`}
                    </span>
                  )}
                  {!bookable && datesSelected && (
                    <div className="rc-soldout">
                      <div>{!available ? '🚫 Hết phòng cho ngày này' : `👥 Phòng tối đa ${r.cap} khách`}</div>
                      {nextAvail && (
                        <div className="rc-next">
                          Còn trống từ <b>{formatDateShort(nextAvail)}</b>
                        </div>
                      )}
                    </div>
                  )}
                  <div className="rc-badge">P.{r.number}</div>
                </div>
                <div className="room-body">
                  <div className="room-head">
                    <div>
                      <h3 className="rh-name">{r.name || ('Phòng ' + r.number)}</h3>
                      <div className="rh-type">{r.type} · Tầng {r.floor}</div>
                    </div>
                    <div className="rh-rating">
                      <span className="star">★</span>
                      <span>{(4.6 + (parseInt(r.number) % 4) * 0.1).toFixed(1)}</span>
                    </div>
                  </div>

                  <div className="room-meta">
                    <span className="m-it">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M3 8v12M3 14h18M21 20v-6a3 3 0 0 0-3-3H8v3"/><circle cx="6.5" cy="11.5" r="2"/>
                      </svg>
                      {r.bed}
                    </span>
                    <span className="m-it">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>
                      </svg>
                      {r.cap} khách
                    </span>
                  </div>

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

                  <div className="room-foot">
                    <div>
                      <div className="room-price">
                        {VND(r.price)}
                        <span className="per">/đêm</span>
                      </div>
                      {nights > 1 && bookable && (
                        <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>
                          {VND(r.price * nights)} cho {nights} đêm
                        </div>
                      )}
                    </div>
                    <button
                      className="room-book-btn"
                      onClick={(e) => { e.stopPropagation(); if (bookable) onSelect(r); }}
                      disabled={!bookable}
                    >
                      {bookable ? 'Đặt phòng' : !available ? 'Đổi ngày' : 'Quá tải'}
                      {bookable && (
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                          <path d="M5 12h14M13 6l6 6-6 6"/>
                        </svg>
                      )}
                    </button>
                  </div>
                </div>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ─── Room detail ─────────────────────────────────────────
function RoomDetail({ room, search, setSearch, onContinue, onBack }) {
  const nights = search.checkIn && search.checkOut
    ? Math.max(1, daysBetween(search.checkIn, search.checkOut))
    : 2;
  const roomTotal = room.price * nights;
  const cleaning = 100000;
  const serviceFee = Math.round(roomTotal * 0.05);
  const total = roomTotal + cleaning + serviceFee;
  const canContinue = search.checkIn && search.checkOut && nights > 0;
  const rating = (4.6 + (parseInt(room.number) % 4) * 0.1).toFixed(1);

  return (
    <section className="section" style={{ paddingTop: 40 }}>
      <div className="container">
        <button className="detail-back" onClick={onBack}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
          Tất cả phòng
        </button>

        <div className="detail-gallery">
          <div>
            <PlaceholderArt room={room} showName={false} />
            <image-slot id={`gal-${room.id}-1`} placeholder={`Ảnh chính ${room.name}`}></image-slot>
          </div>
          {[2, 3, 4, 5].map(i => (
            <div key={i}>
              <PlaceholderArt room={room} showName={false} />
              <image-slot id={`gal-${room.id}-${i}`} placeholder={`Ảnh ${i}`}></image-slot>
            </div>
          ))}
        </div>

        <div className="detail-grid">
          <div className="detail-main">
            <div className="detail-hd">
              <div className="d-type">{room.type} · Tầng {room.floor} · Phòng {room.number}</div>
              <h1>{room.name || ('Phòng ' + room.number)}</h1>
              <div className="d-meta">
                <span className="m-it">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M3 8v12M3 14h18M21 20v-6a3 3 0 0 0-3-3H8v3"/><circle cx="6.5" cy="11.5" r="2"/>
                  </svg>
                  {room.bed}
                </span>
                <span className="m-it">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>
                  </svg>
                  Tối đa {room.cap} khách
                </span>
                <span className="d-rating">
                  <span className="star">★</span> {rating} · 47 đánh giá
                </span>
              </div>
            </div>

            <div className="detail-body">
              <p>
                {room.name} là không gian {room.type === 'Suite' || room.type.startsWith('Suite') ? 'sang trọng nhất' : room.type === 'Deluxe' ? 'rộng rãi' : 'ấm cúng'} của Windy Hill —
                {room.features?.find(f => f.startsWith('View')) ? ` đón ánh sáng tự nhiên qua cửa sổ lớn hướng ${room.features.find(f => f.startsWith('View')).replace('View ', '')}, ` : ' '}
                {room.features?.includes('Lò sưởi củi') || room.features?.includes('Lò sưởi điện') ? 'có lò sưởi để ấm áp những đêm Đà Lạt se lạnh, ' : ''}
                cùng đầy đủ tiện nghi cho kỳ nghỉ thư thái.
                Mỗi sáng, bạn sẽ thức dậy bên tiếng chim và mùi thông sau mưa.
              </p>

              <h3>Tiện nghi phòng</h3>
              <div className="amenities-grid">
                {(room.features || []).map((f, i) => (
                  <div key={i} className="am-item">
                    <span className="am-ico" style={{ fontSize: 16 }}>{amenityIcon(f)}</span>
                    <span>{f}</span>
                  </div>
                ))}
                <div className="am-item">
                  <span className="am-ico" style={{ fontSize: 16 }}>☕</span>
                  <span>Bữa sáng homemade</span>
                </div>
                <div className="am-item">
                  <span className="am-ico" style={{ fontSize: 16 }}>📶</span>
                  <span>Wi-Fi tốc độ cao</span>
                </div>
                <div className="am-item">
                  <span className="am-ico" style={{ fontSize: 16 }}>🅿️</span>
                  <span>Bãi đỗ xe miễn phí</span>
                </div>
              </div>

              <h3>Chính sách</h3>
              <ul style={{ color: 'var(--ink-2)', fontSize: 14.5, lineHeight: 1.8, paddingLeft: 22 }}>
                <li>Nhận phòng từ 14:00 · Trả phòng trước 12:00</li>
                <li>Hủy miễn phí trong vòng 48 giờ trước check-in</li>
                <li>Không hút thuốc trong phòng · Có khu hút thuốc riêng</li>
                <li>Cho phép thú cưng nhỏ (báo trước · phụ thu 150.000đ/đêm)</li>
              </ul>
            </div>
          </div>

          {/* Sticky booking card */}
          <aside className="book-card">
            <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 16 }}>
              <div className="bc-price">
                <span className="num">{VND(room.price)}</span>
                <span className="per">/đêm</span>
              </div>
              <span className="bc-rating">
                <span className="star">★</span> {rating}
              </span>
            </div>

            <div className="bc-form">
              <div className="bc-row">
                <div className="bc-cell">
                  <div className="bc-lbl">Nhận phòng</div>
                  <input
                    type="date"
                    min={dateInputISO(new Date())}
                    value={dateInputISO(search.checkIn)}
                    onChange={(e) => setSearch(s => ({ ...s, checkIn: parseDateInput(e.target.value) }))}
                  />
                </div>
                <div className="bc-cell">
                  <div className="bc-lbl">Trả phòng</div>
                  <input
                    type="date"
                    min={dateInputISO(search.checkIn) || dateInputISO(new Date())}
                    value={dateInputISO(search.checkOut)}
                    onChange={(e) => setSearch(s => ({ ...s, checkOut: parseDateInput(e.target.value) }))}
                  />
                </div>
              </div>
              <div className="bc-row">
                <div className="bc-cell" style={{ borderTop: '1px solid var(--line)' }}>
                  <div className="bc-lbl">Số khách</div>
                  <select
                    value={search.guests}
                    onChange={(e) => setSearch(s => ({ ...s, guests: +e.target.value }))}
                  >
                    {[1, 2, 3, 4, 5, 6].slice(0, room.cap).map(n => (
                      <option key={n} value={n}>{n} khách</option>
                    ))}
                  </select>
                </div>
              </div>
            </div>

            <button className="bc-cta" onClick={onContinue} disabled={!canContinue}>
              Đặt phòng
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 6l6 6-6 6"/>
              </svg>
            </button>
            <div className="bc-note">Chưa trừ tiền — chỉ giữ chỗ</div>

            <div className="bc-summary">
              <div className="bc-srow">
                <span>{VND(room.price)} × {nights} đêm</span>
                <span>{VND(roomTotal)}</span>
              </div>
              <div className="bc-srow">
                <span>Phí dọn phòng</span>
                <span>{VND(cleaning)}</span>
              </div>
              <div className="bc-srow">
                <span>Phí dịch vụ (5%)</span>
                <span>{VND(serviceFee)}</span>
              </div>
              <div className="bc-srow total">
                <span>Tổng cộng</span>
                <span className="v">{VND(total)}</span>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

// ─── Checkout ─────────────────────────────────────────────
function Checkout({ room, search, guestInfo, setGuestInfo, payment, setPayment, onBack, onConfirm }) {
  const nights = Math.max(1, daysBetween(search.checkIn, search.checkOut));
  const roomTotal = room.price * nights;
  const cleaning = 100000;
  const serviceFee = Math.round(roomTotal * 0.05);
  const total = roomTotal + cleaning + serviceFee;

  const canConfirm = guestInfo.name && guestInfo.phone && guestInfo.email && payment.method;

  return (
    <section className="section" style={{ paddingTop: 40 }}>
      <div className="container">
        <button className="detail-back" onClick={onBack}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
          Quay lại
        </button>

        <div className="checkout">
          <div className="co-main">
            <h2>Xác nhận đặt phòng</h2>
            <div className="co-sub">Sắp xong rồi! Điền thông tin để chúng tôi giữ chỗ.</div>

            <div className="co-steps">
              <div className="co-step done">
                <span className="co-num">1</span>
                <span>Chọn phòng</span>
              </div>
              <div className="co-line" />
              <div className="co-step active">
                <span className="co-num">2</span>
                <span>Thông tin & Thanh toán</span>
              </div>
              <div className="co-line" />
              <div className="co-step">
                <span className="co-num">3</span>
                <span>Xác nhận</span>
              </div>
            </div>

            <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 22, margin: '0 0 14px', fontWeight: 500 }}>Thông tin khách</h3>

            <div className="field-row">
              <div className="field">
                <label>Họ và tên *</label>
                <input
                  type="text"
                  placeholder="VD: Nguyễn Thị Minh Anh"
                  value={guestInfo.name}
                  onChange={(e) => setGuestInfo(g => ({ ...g, name: e.target.value }))}
                />
              </div>
              <div className="field">
                <label>Số điện thoại *</label>
                <input
                  type="tel"
                  placeholder="VD: 0912 345 678"
                  value={guestInfo.phone}
                  onChange={(e) => setGuestInfo(g => ({ ...g, phone: e.target.value }))}
                />
              </div>
            </div>
            <div className="field">
              <label>Email *</label>
              <input
                type="email"
                placeholder="email@example.com · để gửi xác nhận"
                value={guestInfo.email}
                onChange={(e) => setGuestInfo(g => ({ ...g, email: e.target.value }))}
              />
            </div>
            <div className="field">
              <label>CCCD / Hộ chiếu</label>
              <input
                type="text"
                placeholder="Tùy chọn — sẽ check khi nhận phòng"
                value={guestInfo.idNo}
                onChange={(e) => setGuestInfo(g => ({ ...g, idNo: e.target.value }))}
              />
            </div>
            <div className="field">
              <label>Yêu cầu đặc biệt</label>
              <textarea
                placeholder="VD: phòng tầng cao, đưa đón sân bay, dị ứng…"
                rows="3"
                value={guestInfo.note}
                onChange={(e) => setGuestInfo(g => ({ ...g, note: e.target.value }))}
              ></textarea>
            </div>

            <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 22, margin: '34px 0 14px', fontWeight: 500 }}>Phương thức thanh toán</h3>
            <div className="pay-methods">
              {[
                { k: 'card',     l: 'Thẻ ngân hàng', emoji: '💳' },
                { k: 'transfer', l: 'Chuyển khoản',  emoji: '🏦' },
                { k: 'momo',     l: 'Momo · ZaloPay', emoji: '📱' },
                { k: 'pay_later', l: 'Trả tại chỗ',  emoji: '💵' },
              ].map(m => (
                <button
                  key={m.k}
                  className={`pay-method ${payment.method === m.k ? 'active' : ''}`}
                  onClick={() => setPayment(p => ({ ...p, method: m.k }))}
                >
                  <span style={{ fontSize: 22 }}>{m.emoji}</span>
                  <span>{m.l}</span>
                </button>
              ))}
            </div>

            <div className="co-foot">
              <button className="btn-ghost" onClick={onBack}>Quay lại</button>
              <button
                className="bc-cta"
                style={{ width: 'auto', padding: '13px 32px' }}
                onClick={() => canConfirm && onConfirm()}
                disabled={!canConfirm}
              >
                Hoàn tất đặt phòng · {VND(total)}
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M13 6l6 6-6 6"/>
                </svg>
              </button>
            </div>
          </div>

          {/* Summary */}
          <aside className="co-summary">
            <div className="co-sum-room">
              <div className="co-sum-img">
                <PlaceholderArt room={room} showName={false} />
                <image-slot id={`co-img-${room.id}`} placeholder="Ảnh phòng"></image-slot>
              </div>
              <div className="co-sum-info">
                <div className="name">{room.name || ('Phòng ' + room.number)}</div>
                <div className="type">{room.type}</div>
                <div className="dates">
                  {formatDateShort(search.checkIn)} → {formatDateShort(search.checkOut)}<br/>
                  {nights} đêm · {search.guests} khách
                </div>
              </div>
            </div>
            <div className="bc-summary" style={{ borderTop: 0, paddingTop: 0 }}>
              <div className="bc-srow">
                <span>{VND(room.price)} × {nights} đêm</span>
                <span>{VND(roomTotal)}</span>
              </div>
              <div className="bc-srow">
                <span>Phí dọn phòng</span>
                <span>{VND(cleaning)}</span>
              </div>
              <div className="bc-srow">
                <span>Phí dịch vụ (5%)</span>
                <span>{VND(serviceFee)}</span>
              </div>
              <div className="bc-srow total">
                <span>Tổng cộng</span>
                <span className="v">{VND(total)}</span>
              </div>
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
              Bạn sẽ được trừ tiền sau khi xác nhận. Hủy miễn phí trong 48 giờ trước check-in.
            </div>
          </aside>
        </div>
      </div>
    </section>
  );
}

// ─── Confirmation ─────────────────────────────────────────
function Confirmation({ booking, room, search, total, guestInfo, onHome }) {
  const nights = Math.max(1, daysBetween(search.checkIn, search.checkOut));
  return (
    <section className="confirm container">
      <div className="confirm-tick">
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 13l4 4 10-12"/>
        </svg>
      </div>
      <h1>Cảm ơn <em>{guestInfo.name.split(' ').pop()}</em>! Phòng đã được giữ chỗ.</h1>
      <p>
        Chúng tôi đã gửi email xác nhận tới <b>{guestInfo.email}</b>.<br/>
        Nhân viên sẽ liên hệ qua số <b>{guestInfo.phone}</b> trong 24h để xác nhận lại.
      </p>

      <div className="confirm-code">{booking.code}</div>

      <div className="confirm-summary">
        <div className="cs-row"><span className="l">Phòng</span><span className="r">{room.name || ('Phòng ' + room.number)} · {room.type}</span></div>
        <div className="cs-row"><span className="l">Nhận phòng</span><span className="r">{formatDateVN(search.checkIn)} · 14:00</span></div>
        <div className="cs-row"><span className="l">Trả phòng</span><span className="r">{formatDateVN(search.checkOut)} · 12:00</span></div>
        <div className="cs-row"><span className="l">{nights} đêm · {search.guests} khách</span><span className="r">{VND(room.price)}/đêm</span></div>
        <div className="cs-row" style={{ fontSize: 16, fontWeight: 600 }}><span className="l" style={{ color: 'var(--ink)' }}>Tổng cộng</span><span className="r" style={{ color: 'var(--accent)' }}>{VND(total)}</span></div>
      </div>

      <button className="bc-cta" style={{ display: 'inline-flex', width: 'auto', padding: '13px 32px' }} onClick={onHome}>
        Về trang chủ
      </button>

      <p style={{ marginTop: 32, fontSize: 13, color: 'var(--ink-3)' }}>
        Hẹn gặp bạn ở Windy Hill 🌲
      </p>
    </section>
  );
}

// ─── About + Footer ──────────────────────────────────────
function About() {
  return (
    <section className="section" id="about" style={{ background: 'var(--bg-soft)', marginTop: 80 }}>
      <div className="container">
        <div className="section-hd" style={{ marginBottom: 28 }}>
          <div>
            <div className="sh-eyebrow">Về Windy Hill</div>
            <h2>Một góc Đà Lạt <em>yên ả</em>.</h2>
          </div>
          <div className="sh-sub">
            Chỉ 12 phòng, đội ngũ ít hơn 10 người. Chúng tôi tin vào sự đơn giản, chân thật và những bữa sáng tự nấu.
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28, marginTop: 30 }}>
          {[
            { ico: '🌲', t: 'Trong rừng thông', d: '5 phút đi bộ tới đường mòn rừng thông Tuyền Lâm. Sáng dậy với mùi nhựa thông và tiếng chim.' },
            { ico: '☕', t: 'Bữa sáng nhà nấu', d: 'Phở, bún, trứng ốp, bánh mì tự nướng — bữa sáng đổi món mỗi ngày, làm bằng nguyên liệu địa phương.' },
            { ico: '🚗', t: '20 phút từ trung tâm', d: 'Đủ gần để đi chợ Đà Lạt buổi tối, đủ xa để nghe tiếng thông reo cả ngày.' },
          ].map((b, i) => (
            <div key={i} style={{ background: 'var(--surface)', padding: 28, borderRadius: 'var(--r-lg)', border: '1px solid var(--line)' }}>
              <div style={{ fontSize: 32, marginBottom: 12 }}>{b.ico}</div>
              <h3 style={{ fontFamily: 'var(--font-serif)', fontSize: 20, margin: '0 0 8px', fontWeight: 500 }}>{b.t}</h3>
              <p style={{ margin: 0, color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6 }}>{b.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot" id="contact">
      <div className="container">
        <div className="foot-grid">
          <div className="foot-brand">
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 24, fontWeight: 600, color: 'var(--ink)', marginBottom: 6 }}>Windy Hill</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '.1em', marginBottom: 14 }}>Homestay · Đà Lạt</div>
            <p>12 phòng, một góc rừng thông, vô số khoảnh khắc đáng nhớ. Đặt trực tiếp để được giá tốt nhất.</p>
          </div>
          <div>
            <h4>Khám phá</h4>
            <ul>
              <li><a href="#rooms">Tất cả phòng</a></li>
              <li><a href="#about">Về chúng tôi</a></li>
              <li><a href="#">Hoạt động & trải nghiệm</a></li>
              <li><a href="#">Ưu đãi</a></li>
            </ul>
          </div>
          <div>
            <h4>Liên hệ</h4>
            <ul>
              <li>📍 Phường 4, Đà Lạt</li>
              <li>📞 0263 888 8888</li>
              <li>✉️ hello@windyhill.vn</li>
              <li>💬 Zalo: @windyhill</li>
            </ul>
          </div>
          <div>
            <h4>Theo dõi</h4>
            <ul>
              <li><a href="#">Instagram</a></li>
              <li><a href="#">Facebook</a></li>
              <li><a href="#">TikTok</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bot">
          <div>© 2026 Windy Hill Homestay · Số ĐKKD: 0312345678</div>
          <div>Made with 🌲 in Đà Lạt</div>
        </div>
      </div>
    </footer>
  );
}

// ─── Main App ───────────────────────────────────────────
function BookingApp() {
  const data = window.HotelData;
  const [view, setView] = React.useState('home');  // 'home' | 'detail' | 'checkout' | 'confirm'
  const [selectedRoom, setSelectedRoom] = React.useState(null);
  const [search, setSearch] = React.useState(() => {
    // Default: today + 1 → today + 3. This overlaps existing demo bookings
    // so customer immediately sees the "Còn trống / Hết phòng" UI.
    const ci = window.HotelData.addDays(window.HotelData.today, 1);
    const co = window.HotelData.addDays(window.HotelData.today, 3);
    return { checkIn: ci, checkOut: co, guests: 2 };
  });
  const [guestInfo, setGuestInfo] = React.useState({
    name: '', phone: '', email: '', idNo: '', note: '',
  });
  const [payment, setPayment] = React.useState({ method: 'card' });
  const [confirmedBooking, setConfirmedBooking] = React.useState(null);
  const [toast, setToast] = React.useState(null);

  // Scroll to top on view change
  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [view]);

  const handleSelect = (room) => {
    setSelectedRoom(room);
    setView('detail');
  };
  const handleSearchSubmit = () => {
    setToast('Đã tìm phòng cho ' + (search.checkIn ? formatDateShort(search.checkIn) : '?') + ' → ' + (search.checkOut ? formatDateShort(search.checkOut) : '?'));
    setTimeout(() => setToast(null), 2500);
    // Scroll to rooms section
    document.getElementById('rooms')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };
  const handleConfirm = () => {
    const code = 'WH' + Math.floor(2500 + Math.random() * 7499);
    const nights = Math.max(1, daysBetween(search.checkIn, search.checkOut));
    const roomTotal = selectedRoom.price * nights;
    const cleaning = 100000;
    const serviceFee = Math.round(roomTotal * 0.05);
    const total = roomTotal + cleaning + serviceFee;
    setConfirmedBooking({ code, total });
    setView('confirm');
  };

  return (
    <>
      <Nav goHome={() => setView('home')} onBookNow={() => {
        if (view === 'home') document.getElementById('rooms')?.scrollIntoView({ behavior: 'smooth' });
        else setView('home');
      }} />

      {view === 'home' && (
        <>
          <Hero search={search} setSearch={setSearch} onSearch={handleSearchSubmit} />
          <RoomsGrid rooms={data.rooms} bookings={data.bookings} search={search} onSelect={handleSelect} />
          <About />
        </>
      )}

      {view === 'detail' && selectedRoom && (
        <RoomDetail
          room={selectedRoom}
          search={search}
          setSearch={setSearch}
          onContinue={() => setView('checkout')}
          onBack={() => setView('home')}
        />
      )}

      {view === 'checkout' && selectedRoom && (
        <Checkout
          room={selectedRoom}
          search={search}
          guestInfo={guestInfo}
          setGuestInfo={setGuestInfo}
          payment={payment}
          setPayment={setPayment}
          onBack={() => setView('detail')}
          onConfirm={handleConfirm}
        />
      )}

      {view === 'confirm' && selectedRoom && confirmedBooking && (
        <Confirmation
          booking={confirmedBooking}
          room={selectedRoom}
          search={search}
          total={confirmedBooking.total}
          guestInfo={guestInfo}
          onHome={() => { setView('home'); setConfirmedBooking(null); setGuestInfo({ name:'', phone:'', email:'', idNo:'', note:'' }); }}
        />
      )}

      <Footer />

      {toast && <div className="toast">{toast}</div>}
    </>
  );
}

window.BookingApp = BookingApp;
