// 39 Uchi — Apartment detail: gallery, spaces, sticky booking widget
const DetNS = window.Ds39UchiDesignSystem_266f47;

const RATE = 1100000;
const ROOM_ID = "1217154875373241975";

const pad2 = (n) => String(n).padStart(2, "0");
const ddmmyyyy = (d) => `${pad2(d.getDate())}.${pad2(d.getMonth() + 1)}.${d.getFullYear()}`;
const isoDate = (d) => `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
const startOfDay = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
const addMonths = (d, n) => new Date(d.getFullYear(), d.getMonth() + n, 1);
const nightsBetween = (a, b) => Math.round((startOfDay(b) - startOfDay(a)) / 86400000);
const vnNum = (n) => n.toLocaleString("vi-VN");

const PHOTOS = [
  { src: "photos/living-01.webp", cap: "Phòng khách" },
  { src: "photos/kitchen.webp",   cap: "Bếp" },
  { src: "photos/bathroom.webp",  cap: "Phòng tắm" },
  { src: "photos/hikari.webp",    cap: "Hikari · tầng trên" },
  { src: "photos/kage.webp",      cap: "Kage · tầng dưới" },
  { src: "photos/living-02.webp", cap: "Phòng khách" },
  { src: "photos/hero.webp",      cap: "Không gian chung" },
];

function Lightbox({ photos, start, onClose }) {
  const vw = useViewport();
  const m = vw < 760;
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const el = document.getElementById("lb-" + (start || 0));
    if (el) el.scrollIntoView();
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = prev; };
  }, [onClose, start]);
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 50, background: "rgba(14,14,14,0.97)", overflowY: "auto" }}>
      <div style={{ position: "sticky", top: 0, zIndex: 1, display: "flex", alignItems: "center", justifyContent: "space-between", padding: m ? "12px 16px" : "14px 24px", background: "color-mix(in srgb, var(--noir-900) 86%, transparent)", backdropFilter: "blur(12px)", borderBottom: "1px solid var(--border)" }}>
        <button onClick={onClose} aria-label="Đóng" style={{ background: "none", border: "none", color: "var(--text)", fontFamily: "var(--font-sans)", fontSize: 24, lineHeight: 1, cursor: "pointer", padding: "2px 8px" }}>×</button>
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 13, letterSpacing: "0.06em", color: "var(--text-muted)" }}>39 Uchi · {photos.length} ảnh</span>
        <span style={{ width: 32 }}></span>
      </div>
      <div style={{ maxWidth: 880, margin: "0 auto", padding: m ? "20px 14px 64px" : "28px 24px 72px", display: "flex", flexDirection: "column", gap: m ? 12 : 18 }}>
        {photos.map((ph, i) => (
          <figure key={i} id={"lb-" + i} style={{ margin: 0, scrollMarginTop: 72 }}>
            <img src={ph.src} alt={ph.cap} loading="lazy" style={{ width: "100%", display: "block", borderRadius: "var(--r-md)", border: "1px solid var(--border)" }} />
            <figcaption style={{ fontFamily: "var(--font-text)", fontSize: 13, color: "var(--text-faint)", margin: "8px 0 0" }}>{ph.cap}</figcaption>
          </figure>
        ))}
      </div>
    </div>
  );
}

function GalleryTile({ photo, onClick, corners }) {
  const [hover, setHover] = React.useState(false);
  const r = "var(--r-lg)";
  const radius = {
    tl: corners.includes("tl") ? r : 0, tr: corners.includes("tr") ? r : 0,
    bl: corners.includes("bl") ? r : 0, br: corners.includes("br") ? r : 0,
  };
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: "relative", display: "block", width: "100%", height: "100%", padding: 0, border: 0, cursor: "pointer", overflow: "hidden",
        background: "var(--noir-850)", minWidth: 0,
        borderTopLeftRadius: radius.tl, borderTopRightRadius: radius.tr,
        borderBottomLeftRadius: radius.bl, borderBottomRightRadius: radius.br,
        gridColumn: corners.includes("big") ? "1" : "auto", gridRow: corners.includes("big") ? "1 / 3" : "auto" }}>
      <img src={photo.src} alt={photo.cap} loading="lazy"
        style={{ width: "100%", height: "100%", objectFit: "cover", display: "block",
          transition: "transform var(--dur-4) var(--ease-quiet)", transform: hover ? "scale(1.04)" : "scale(1)" }} />
      <span style={{ position: "absolute", inset: 0, background: hover ? "rgba(14,14,14,0.10)" : "rgba(14,14,14,0)", transition: "background var(--dur-2) var(--ease-std)" }}></span>
    </button>
  );
}

function AllPhotosButton({ onClick }) {
  const [h, setH] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ position: "absolute", right: 14, bottom: 14, display: "inline-flex", alignItems: "center", gap: 8,
        padding: "9px 16px", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 600, letterSpacing: "0.01em",
        color: "var(--text)", background: h ? "color-mix(in srgb, var(--noir-900) 92%, transparent)" : "color-mix(in srgb, var(--noir-900) 78%, transparent)",
        border: "1px solid var(--border-strong)", borderRadius: "var(--r-md)", backdropFilter: "blur(8px)", cursor: "pointer",
        transition: "background var(--dur-2) var(--ease-std)" }}>
      Hiển thị tất cả ảnh
    </button>
  );
}

function Gallery() {
  const [open, setOpen] = React.useState(false);
  const [start, setStart] = React.useState(0);
  const vw = useViewport();
  const m = vw < 760, t = vw < 1024;
  const show = (i) => { setStart(i); setOpen(true); };
  const tiles = [
    { corners: ["big", "tl", "bl"] },
    { corners: [] },
    { corners: ["tr"] },
    { corners: [] },
    { corners: ["br"] },
  ];
  return (
    <div style={{ position: "relative" }}>
      {m ? (
        <div style={{ height: vw < 480 ? 240 : 300 }}>
          <GalleryTile photo={PHOTOS[0]} corners={["tl", "tr", "bl", "br"]} onClick={() => show(0)} />
        </div>
      ) : (
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr 1fr", gridTemplateRows: "1fr 1fr", gap: 8, height: t ? 360 : 460 }}>
          {tiles.map((tile, i) => (
            <GalleryTile key={i} photo={PHOTOS[i]} corners={tile.corners} onClick={() => show(i)} />
          ))}
        </div>
      )}
      <AllPhotosButton onClick={() => show(0)} />
      {open && <Lightbox photos={PHOTOS} start={start} onClose={() => setOpen(false)} />}
    </div>
  );
}

function Spaces() {
  const vw = useViewport();
  const m = vw < 760;
  const rooms = [
    { kanji: "光", roman: "Hikari", level: "Tầng trên", desc: "Cửa sổ lớn, nhiều sáng." },
    { kanji: "影", roman: "Kage", level: "Tầng dưới", desc: "Kín hơn, yên hơn." },
  ];
  return (
    <div>
      <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 14 }}>Hai phòng ngủ</div>
      <div style={{ display: "grid", gridTemplateColumns: m ? "1fr" : "1fr 1fr", gap: 16 }}>
        {rooms.map((r) => (
          <div key={r.roman} style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 18 }}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
              <span style={{ fontFamily: "var(--font-sans)", fontWeight: 300, fontSize: 26, color: "var(--accent)", lineHeight: 1 }}>{r.kanji}</span>
              <h4 style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 17, margin: 0 }}>{r.roman}</h4>
              <span style={{ fontFamily: "var(--font-text)", fontSize: 12.5, color: "var(--text-faint)", marginLeft: "auto" }}>{r.level}</span>
            </div>
            <p style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "var(--text-muted)", margin: "8px 0 0" }}>{r.desc}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

function Amenities() {
  const { Tag } = DetNS;
  const groups = [
    ["Không gian", ["Căn hộ 2 phòng ngủ", "Nguyên căn", "35 m²", "1 phòng tắm"]],
    ["Tiện nghi", ["Bếp nhỏ", "Máy giặt", "Nước nóng", "Wifi 350 Mbps"]],
    ["Chi tiết", ["Bàn làm việc", "Cà phê phin", "Máy sấy", "Tủ sách"]],
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 26 }}>
      {groups.map(([t, items]) => (
        <div key={t}>
          <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 12 }}>{t}</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {items.map((i) => <Tag key={i}>{i}</Tag>)}
          </div>
        </div>
      ))}
    </div>
  );
}

const REVIEW = {
  overall: 4.72,
  count: 74,
  cats: [
    ["Giao tiếp", 4.95],
    ["Vị trí", 4.92],
    ["Mức độ chính xác", 4.78],
    ["Đáng giá tiền", 4.76],
    ["Sạch sẽ", 4.73],
    ["Nhận phòng", 4.73],
  ],
};

const QUOTES = [
  { name: "Thuý", date: "Tháng 6, 2026", text: "Nhà được dọn dẹp rất sạch sẽ và đẹp, không gian thoáng, host rất thân thiện và nhiệt tình, cho check-in nhận phòng sớm nếu cần. Gia đình mình rất thoải mái khi ở đây, nếu có dịp sẽ quay lại thuê tiếp." },
  { name: "Max", date: "Tháng 7, 2025", text: "Chủ nhà trả lời khá nhanh, vị trí ngay trung tâm gần nhiều chỗ ăn vặt, đi chợ khoảng 5 phút, nhà mới và dễ tìm. Mình rất hài lòng, tiếc chỉ ở Đà Lạt được vài ngày, tương lai chắc chắn quay lại." },
  { name: "Nhi", date: "Tháng 7, 2025", text: "Địa điểm ngay trung tâm, siêu gần Chợ Đà Lạt, đi bộ vài bước chân là tới. Phòng sạch sẽ, dễ tìm và check-in, sắp xếp giống như trong hình. Chủ nhà phản hồi nhanh, vui vẻ và nhiệt tình." },
  { name: "Phương Anh", date: "Tháng 12, 2025", text: "Phòng rất xinh và chỗ ở rất trung tâm, đi lại đều rất tiện. Cảm ơn anh chị chủ nhà rất nhiều vì đã hỗ trợ gia đình em." },
];

function QuoteCard({ name, date, text }) {
  return (
    <div style={{ border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 20, background: "var(--surface)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <div style={{ width: 40, height: 40, borderRadius: "50%", border: "1px solid var(--border-strong)", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 16, color: "var(--text)", flexShrink: 0 }}>{name.trim().charAt(0).toUpperCase()}</div>
        <div>
          <div style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 15, color: "var(--text)" }}>{name}</div>
          <div style={{ fontFamily: "var(--font-text)", fontSize: 12.5, color: "var(--text-faint)" }}>{date} · <span style={{ color: "var(--accent)", fontVariantNumeric: "tabular-nums" }}>5,0</span></div>
        </div>
      </div>
      <p style={{ fontFamily: "var(--font-text)", fontSize: 14.5, lineHeight: 1.65, color: "var(--text-muted)", margin: 0 }}>{text}</p>
    </div>
  );
}

function Reviews() {
  const vw = useViewport();
  const cols = vw < 560 ? 1 : vw < 1024 ? 2 : 3;
  const fmt = (v) => v.toFixed(2).replace(".", ",");
  return (
    <div>
      <div style={{ fontFamily: "var(--font-sans)", fontSize: 11, fontWeight: 600, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 14 }}>Cảm nhận của khách</div>
      <div style={{ display: "flex", alignItems: "baseline", flexWrap: "wrap", gap: "0 10px", marginBottom: 22 }}>
        <span style={{ fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontWeight: 600, fontSize: 44, lineHeight: 1, color: "var(--accent)" }}>{fmt(REVIEW.overall)}</span>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 18, color: "var(--text-muted)" }}>/ 5</span>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "var(--text-faint)", marginLeft: 4 }}>· {REVIEW.count} đánh giá trên Airbnb</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(" + cols + ", 1fr)", gap: "14px 32px" }}>
        {REVIEW.cats.map(([label, v]) => (
          <div key={label}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10, marginBottom: 6 }}>
              <span style={{ fontFamily: "var(--font-text)", fontSize: 13.5, color: "var(--text-muted)" }}>{label}</span>
              <span style={{ fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontSize: 13.5, color: "var(--text)" }}>{fmt(v)}</span>
            </div>
            <div style={{ height: 3, background: "var(--noir-700)", borderRadius: 2, overflow: "hidden" }}>
              <div style={{ width: (v / 5 * 100) + "%", height: "100%", background: "var(--text)" }}></div>
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: vw < 760 ? "1fr" : "1fr 1fr", gap: 16, marginTop: 26 }}>
        {QUOTES.map((q, i) => <QuoteCard key={i} name={q.name} date={q.date} text={q.text} />)}
      </div>
      <a href={"https://www.airbnb.com.vn/rooms/" + ROOM_ID + "/reviews"} target="_blank" rel="noopener"
        style={{ display: "inline-block", marginTop: 24, fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--accent)", cursor: "pointer" }}>
        Xem tất cả {REVIEW.count} đánh giá trên Airbnb →
      </a>
    </div>
  );
}

/* ---- Range calendar (noir) ---- */
function Calendar({ month, setMonth, checkIn, checkOut, onPick }) {
  const vw = useViewport();
  const cw = Math.max(260, Math.min(308, vw - 48));
  const today = startOfDay(new Date());
  const y = month.getFullYear(), m = month.getMonth();
  const offset = (new Date(y, m, 1).getDay() + 6) % 7; // Mon-first
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));
  const atFirstMonth = y === today.getFullYear() && m === today.getMonth();

  const navBtn = (dir, disabled) => (
    <button onClick={() => !disabled && setMonth(addMonths(month, dir))} disabled={disabled}
      style={{ background: "none", border: "1px solid var(--border)", borderRadius: "var(--r-sm)", color: disabled ? "var(--text-faint)" : "var(--text)", width: 30, height: 30, cursor: disabled ? "not-allowed" : "pointer", fontSize: 15, opacity: disabled ? 0.4 : 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
      {dir < 0 ? "‹" : "›"}
    </button>
  );

  return (
    <div style={{ background: "var(--noir-800)", border: "1px solid var(--noir-600)", borderRadius: "var(--r-md)", boxShadow: "var(--shadow-md)", padding: 16, width: cw, maxWidth: "calc(100vw - 32px)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        {navBtn(-1, atFirstMonth)}
        <span style={{ fontFamily: "var(--font-sans)", fontSize: 14, fontWeight: 600, color: "var(--text)" }}>Tháng {m + 1} {y}</span>
        {navBtn(1, false)}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 2 }}>
        {["T2", "T3", "T4", "T5", "T6", "T7", "CN"].map((w) => (
          <div key={w} style={{ textAlign: "center", fontFamily: "var(--font-sans)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.04em", color: "var(--text-faint)", paddingBottom: 6 }}>{w}</div>
        ))}
        {cells.map((d, i) => {
          if (!d) return <div key={"e" + i}></div>;
          const isPast = d < today;
          const isToday = +d === +today;
          const isStart = checkIn && +d === +startOfDay(checkIn);
          const isEnd = checkOut && +d === +startOfDay(checkOut);
          const inRange = checkIn && checkOut && d > checkIn && d < checkOut;
          const endpoint = isStart || isEnd;
          let bg = "transparent", color = "var(--text)", border = "1px solid transparent";
          if (isPast) { color = "var(--text-faint)"; }
          if (inRange) { bg = "rgba(201,164,90,0.15)"; }
          if (isToday && !endpoint) { border = "1px solid var(--accent)"; }
          if (endpoint) { bg = "var(--accent)"; color = "#0E0E0E"; }
          return (
            <button key={+d} disabled={isPast} onClick={() => onPick(d)}
              style={{ height: 36, border, borderRadius: "var(--r-sm)", background: bg, color, opacity: isPast ? 0.35 : 1,
                fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontSize: 13.5, fontWeight: endpoint ? 600 : 400,
                cursor: isPast ? "not-allowed" : "pointer", transition: "background var(--dur-1) var(--ease-std)" }}>
              {d.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ---- Guest stepper row ---- */
function GuestRow({ label, sub, value, onDec, onInc, decDisabled, incDisabled }) {
  const stepBtn = (sign, fn, disabled) => (
    <button onClick={() => !disabled && fn()} disabled={disabled}
      style={{ width: 30, height: 30, borderRadius: "50%", border: "1px solid var(--border-strong)", background: "transparent",
        color: disabled ? "var(--text-faint)" : "var(--text)", fontSize: 16, lineHeight: 1, cursor: disabled ? "not-allowed" : "pointer",
        opacity: disabled ? 0.4 : 1, display: "flex", alignItems: "center", justifyContent: "center" }}>{sign}</button>
  );
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 0" }}>
      <div>
        <div style={{ fontFamily: "var(--font-sans)", fontSize: 14.5, fontWeight: 500, color: "var(--text)" }}>{label}</div>
        {sub && <div style={{ fontFamily: "var(--font-text)", fontSize: 12.5, color: "var(--text-faint)" }}>{sub}</div>}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        {stepBtn("−", onDec, decDisabled)}
        <span style={{ fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontSize: 15, minWidth: 16, textAlign: "center", color: "var(--text)" }}>{value}</span>
        {stepBtn("+", onInc, incDisabled)}
      </div>
    </div>
  );
}

function BookingPanel() {
  const { Button } = DetNS;
  const vw = useViewport();
  const stack = vw < 1024;
  const [checkIn, setCheckIn] = React.useState(null);
  const [checkOut, setCheckOut] = React.useState(null);
  const [month, setMonth] = React.useState(() => { const t = new Date(); return new Date(t.getFullYear(), t.getMonth(), 1); });
  const [openCal, setOpenCal] = React.useState(false);
  const [openGuests, setOpenGuests] = React.useState(false);
  const [adults, setAdults] = React.useState(2);
  const [children, setChildren] = React.useState(0);
  const [infants, setInfants] = React.useState(0);

  const nights = checkIn && checkOut ? nightsBetween(checkIn, checkOut) : 0;
  const totalGuests = adults + children;
  const atCap = totalGuests >= 4;
  const subtotal = nights * RATE;
  const canBook = checkIn && checkOut;

  const onPick = (d) => {
    if (!checkIn || (checkIn && checkOut)) { setCheckIn(d); setCheckOut(null); return; }
    if (d <= checkIn) { setCheckIn(d); setCheckOut(null); return; }
    setCheckOut(d); setOpenCal(false);
  };

  const openCalendar = (mode) => {
    setOpenGuests(false);
    if (mode === "in") { setCheckIn(null); setCheckOut(null); }
    setOpenCal(true);
  };

  const book = () => {
    if (!canBook) return;
    const params = new URLSearchParams({
      check_in: isoDate(checkIn), check_out: isoDate(checkOut),
      adults: String(adults), children: String(children), infants: String(infants), pets: "0",
    });
    window.open(`https://www.airbnb.com.vn/rooms/${ROOM_ID}?${params.toString()}`, "_blank", "noopener");
  };

  const guestText = `${totalGuests} khách` + (infants > 0 ? ` · ${infants} em bé` : "");

  const field = (label, value, placeholder, onClick) => (
    <button onClick={onClick}
      style={{ textAlign: "left", background: "var(--bg)", border: "1px solid var(--border-strong)", borderRadius: "var(--r-md)", padding: "9px 13px", cursor: "pointer", width: "100%" }}>
      <div style={{ fontFamily: "var(--font-sans)", fontSize: 10, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--text-muted)" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontSize: 14.5, color: value ? "var(--text)" : "var(--text-faint)", marginTop: 3 }}>{value || placeholder}</div>
    </button>
  );

  return (
    <div style={{ position: stack ? "static" : "sticky", top: 96, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", padding: 24 }}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 7, flexWrap: "wrap" }}>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "var(--text-muted)" }}>từ</span>
        <span style={{ fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums", fontWeight: 600, fontSize: 26, color: "var(--accent)" }}>1.100.000</span>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "var(--text-muted)" }}>₫ / đêm</span>
      </div>

      <div style={{ position: "relative", marginTop: 20 }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {field("Nhận phòng", checkIn && ddmmyyyy(checkIn), "Chọn ngày", () => openCalendar("in"))}
          {field("Trả phòng", checkOut && ddmmyyyy(checkOut), "Chọn ngày", () => openCalendar("out"))}
        </div>
        {openCal && (
          <React.Fragment>
            <div onClick={() => setOpenCal(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }}></div>
            <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, zIndex: 31 }}>
              <Calendar month={month} setMonth={setMonth} checkIn={checkIn} checkOut={checkOut} onPick={onPick} />
            </div>
          </React.Fragment>
        )}
      </div>

      <div style={{ position: "relative", marginTop: 10 }}>
        {field("Khách", guestText, "Chọn khách", () => { setOpenCal(false); setOpenGuests((v) => !v); })}
        {openGuests && (
          <React.Fragment>
            <div onClick={() => setOpenGuests(false)} style={{ position: "fixed", inset: 0, zIndex: 30 }}></div>
            <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, right: 0, zIndex: 31, background: "var(--noir-800)", border: "1px solid var(--noir-600)", borderRadius: "var(--r-md)", boxShadow: "var(--shadow-md)", padding: "8px 18px" }}>
              <GuestRow label="Người lớn" value={adults} onDec={() => setAdults((a) => Math.max(1, a - 1))} onInc={() => setAdults((a) => a + 1)} decDisabled={adults <= 1} incDisabled={atCap} />
              <div style={{ height: 1, background: "var(--noir-600)" }}></div>
              <GuestRow label="Trẻ em" sub="2–12 tuổi" value={children} onDec={() => setChildren((c) => Math.max(0, c - 1))} onInc={() => setChildren((c) => c + 1)} decDisabled={children <= 0} incDisabled={atCap} />
              <div style={{ height: 1, background: "var(--noir-600)" }}></div>
              <GuestRow label="Em bé" sub="Dưới 2 tuổi · không tính vào 4 khách" value={infants} onDec={() => setInfants((i) => Math.max(0, i - 1))} onInc={() => setInfants((i) => i + 1)} decDisabled={infants <= 0} incDisabled={false} />
              <div style={{ fontFamily: "var(--font-text)", fontSize: 12, color: "var(--text-faint)", padding: "10px 0 6px" }}>Tối đa 4 khách (người lớn + trẻ em).</div>
            </div>
          </React.Fragment>
        )}
      </div>

      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 18, minHeight: 20 }}>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 14, color: "var(--text-muted)" }}>
          {nights > 0 ? `${nights} đêm` : "Chọn ngày để xem tạm tính"}
        </span>
      </div>

      {nights > 0 && (
        <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8, paddingTop: 16, borderTop: "1px solid var(--border)", fontFamily: "var(--font-text)", fontVariantNumeric: "tabular-nums" }}>
          <span style={{ fontSize: 15, color: "var(--text)" }}>Tạm tính</span>
          <span style={{ fontSize: 17, fontWeight: 600, color: "var(--text)" }}>{vnNum(subtotal)} ₫</span>
        </div>
      )}

      <div style={{ marginTop: 18 }}>
        <Button variant="primary" full size="lg" disabled={!canBook} onClick={book}>Đặt phòng</Button>
      </div>
      <p style={{ fontFamily: "var(--font-text)", fontSize: 12.5, color: "var(--text-faint)", textAlign: "center", margin: "12px 0 0" }}>
        Giá ước tính. Hoàn tất đặt phòng trên Airbnb.
      </p>
    </div>
  );
}

function Detail({ onNav }) {
  const { Eyebrow } = DetNS;
  const vw = useViewport();
  const m = vw < 760, t = vw < 1024;
  const px = m ? 20 : t ? 32 : 48;
  return (
    <div style={{ padding: `${m ? 24 : 40}px ${px}px ${m ? 48 : 72}px` }}>
      <button onClick={() => onNav("home")} style={{ background: "none", border: "none", color: "var(--text-muted)", fontFamily: "var(--font-sans)", fontSize: 14, cursor: "pointer", padding: 0, marginBottom: 22 }}>← Trang chủ</button>
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 8, marginBottom: 20 }}>
        <div>
          <Eyebrow>Căn hộ 2 tầng · Trung tâm Đà Lạt</Eyebrow>
          <h1 style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: m ? 32 : 44, letterSpacing: "-0.025em", margin: "12px 0 0" }}>39 Uchi</h1>
        </div>
        <span style={{ fontFamily: "var(--font-text)", fontSize: 13.5, color: "var(--text-muted)" }}>Nguyên căn · tối đa 4 khách · 1 phòng tắm</span>
      </div>
      <Gallery />
      {(() => {
        const info = (
          <div>
            <p style={{ fontFamily: "var(--font-text)", fontSize: 17, lineHeight: 1.7, color: "var(--text)", maxWidth: "52ch", margin: 0 }}>
              Một căn hộ hai tầng, cho thuê nguyên căn. Cửa kính lớn, ánh sáng tự nhiên cả ngày. Bếp đủ nấu, bàn làm việc cạnh cửa sổ. Nhận phòng linh hoạt từ 14:00, trả phòng 12:00.
            </p>
            <div style={{ height: 1, background: "var(--border)", margin: "32px 0" }}></div>
            <Spaces />
            <div style={{ height: 1, background: "var(--border)", margin: "32px 0" }}></div>
            <Amenities />
            <div style={{ height: 1, background: "var(--border)", margin: "32px 0" }}></div>
            <Reviews />
          </div>
        );
        if (t) {
          return (
            <div style={{ display: "flex", flexDirection: "column", gap: 36, marginTop: 32 }}>
              <BookingPanel />
              {info}
            </div>
          );
        }
        return (
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 0.9fr", gap: 56, marginTop: 48 }}>
            {info}
            <BookingPanel />
          </div>
        );
      })()}
    </div>
  );
}

Object.assign(window, { Detail });
