// Hotel booking flow backed by the BedBank Partner API through the Duyuf Worker.

const hotelApi = async (endpoint, payload) => {
  const response = await fetch(
    `${window.DUYUF_API_URL}/v1/hotels/${endpoint}`,
    {
      method: payload === undefined ? "GET" : "POST",
      headers: { "content-type": "application/json" },
      body: payload === undefined ? undefined : JSON.stringify(payload),
    },
  );
  const body = await response.json().catch(() => ({}));
  if (!response.ok || body.ok === false || body.success === false)
    throw new Error(body.message || body.error || "hotel_api_error");
  return body;
};

const hotelDate = (offset) => {
  const value = new Date();
  value.setDate(value.getDate() + offset);
  return value.toISOString().slice(0, 10);
};

const hotelArabicTerms = {
  Makkah: "مكة المكرمة",
  Mecca: "مكة المكرمة",
  Madinah: "المدينة المنورة",
  Medina: "المدينة المنورة",
  Jeddah: "جدة",
  Riyadh: "الرياض",
  Abha: "أبها",
  Dammam: "الدمام",
  Khobar: "الخبر",
  "Saudi Arabia": "المملكة العربية السعودية",
  "Room Only": "إقامة فقط",
  "ROOM ONLY": "إقامة فقط",
  "Bed and Breakfast": "إقامة مع الإفطار",
  Breakfast: "إفطار",
  "Half Board": "نصف إقامة",
  "Full Board": "إقامة كاملة",
  "All Inclusive": "شامل جميع الوجبات",
  Superior: "سوبيريور",
  Deluxe: "ديلوكس",
  Standard: "قياسية",
  Executive: "تنفيذية",
  "King Room": "غرفة بسرير كبير",
  "Twin Room": "غرفة بسريرين",
  "Double Room": "غرفة مزدوجة",
  "Single Room": "غرفة مفردة",
  Suite: "جناح",
  "Free WiFi": "واي فاي مجاني",
  WiFi: "واي فاي",
  Parking: "مواقف سيارات",
  Restaurant: "مطعم",
  "Breakfast included": "الإفطار مشمول",
  "Airport shuttle": "نقل من وإلى المطار",
  "Swimming pool": "مسبح",
  "Family rooms": "غرف عائلية",
  "Room service": "خدمة الغرف",
  "Fitness center": "مركز لياقة بدنية",
};
function hotelLocalized(value, rtl) {
  if (!value || !rtl) return value || "";
  let text = String(value);
  Object.entries(hotelArabicTerms)
    .sort((a, b) => b[0].length - a[0].length)
    .forEach(([from, to]) => {
      text = text.replace(
        new RegExp(from.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi"),
        to,
      );
    });
  return text;
}
function hotelCurrency(code, rtl) {
  return rtl
    ? String(code || "SAR").toUpperCase() === "SAR"
      ? "ر.س"
      : code
    : code || "SAR";
}
function hotelBoard(value, rtl) {
  return hotelLocalized(value, rtl);
}
function hotelImageUrl(image) {
  if (!image) return "";
  if (typeof image === "string") return image;
  return image.url || image.imageUrl || image.largeUrl || image.thumbnailUrl || "";
}
function hotelImages(value) {
  if (!value) return [];
  const media = [
    value.imageUrl,
    value.image,
    value.thumbnailUrl,
    ...(Array.isArray(value.images) ? value.images : []),
    ...(Array.isArray(value.photos) ? value.photos : []),
    ...(Array.isArray(value.imageUrls) ? value.imageUrls : []),
    ...(Array.isArray(value.media) ? value.media : []),
  ];
  return [...new Set(media.map(hotelImageUrl).filter(Boolean))];
}
function hotelImage(value) {
  return hotelImages(value)[0] || "";
}
function hotelFormatDate(value, rtl) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return new Intl.DateTimeFormat(rtl ? "ar-SA-u-ca-gregory" : "en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
    timeZone: "Asia/Riyadh",
  }).format(date);
}
function hotelName(value, rtl) {
  return hotelLocalized(value?.name || value?.hotelName || value?.propertyName || "", rtl);
}
function hotelNightCount(query) {
  const start = new Date(`${query?.checkInDate || ""}T12:00:00`);
  const end = new Date(`${query?.checkOutDate || ""}T12:00:00`);
  const nights = Math.round((end - start) / 86400000);
  return Number.isFinite(nights) && nights > 0 ? nights : 1;
}
function hotelGuestCount(query) {
  return (query?.rooms || []).reduce(
    (total, room) =>
      total + Number(room.adults || 0) + (room.childrenAges || []).length,
    0,
  );
}
function hotelBestRoom(hotel) {
  return (hotel?.rooms || [])
    .filter((room) =>
      Number.isFinite(Number(room.totalPrice ?? room.price)),
    )
    .sort(
      (a, b) =>
        Number(a.totalPrice ?? a.price) - Number(b.totalPrice ?? b.price),
    )[0];
}
function hotelAmenityIcon(value) {
  const text = String(value || "").toLowerCase();
  if (/wifi|internet|lan/.test(text)) return "⌁";
  if (/breakfast|restaurant|food|dining|coffee|kitchen/.test(text)) return "♨";
  if (/pool|swim/.test(text)) return "≈";
  if (/parking|car park/.test(text)) return "P";
  if (/fitness|gym|massage|spa/.test(text)) return "✦";
  if (/airport|shuttle|taxi|transport/.test(text)) return "↗";
  if (/family|child/.test(text)) return "♙";
  if (/accessible|wheelchair|disabled/.test(text)) return "♿";
  if (/air conditioning/.test(text)) return "❄";
  if (/laundry|cleaning/.test(text)) return "◇";
  return "✓";
}

const HOTEL_SPOKEN_LANGUAGES = {
  arabic: { ar: "العربية", en: "Arabic" },
  english: { ar: "الإنجليزية", en: "English" },
  french: { ar: "الفرنسية", en: "French" },
  german: { ar: "الألمانية", en: "German" },
  hindi: { ar: "الهندية", en: "Hindi" },
  urdu: { ar: "الأردية", en: "Urdu" },
  turkish: { ar: "التركية", en: "Turkish" },
  spanish: { ar: "الإسبانية", en: "Spanish" },
  italian: { ar: "الإيطالية", en: "Italian" },
  russian: { ar: "الروسية", en: "Russian" },
};

function hotelLanguageKey(value) {
  const text = String(value || "").trim().toLowerCase();
  const aliases = {
    "العربية": "arabic", "اللغة العربية": "arabic",
    "الإنجليزية": "english", "اللغة الإنجليزية": "english",
    "الفرنسية": "french", "اللغة الفرنسية": "french",
    "الألمانية": "german", "اللغة الألمانية": "german",
    "الهندية": "hindi", "اللغة الهندية": "hindi",
    "الأردية": "urdu", "اللغة الأردية": "urdu",
    "التركية": "turkish", "اللغة التركية": "turkish",
    "الإسبانية": "spanish", "الإيطالية": "italian", "الروسية": "russian",
  };
  if (aliases[text]) return aliases[text];
  return Object.keys(HOTEL_SPOKEN_LANGUAGES).find(
    (key) => text === key || text === `${key} language` || text === `language: ${key}`,
  ) || null;
}

function hotelFacilityItems(items) {
  return (Array.isArray(items) ? items : []).filter((item) => !hotelLanguageKey(item));
}

function hotelSpokenLanguages(items, rtl) {
  return [...new Set((Array.isArray(items) ? items : []).map(hotelLanguageKey).filter(Boolean))]
    .map((key) => HOTEL_SPOKEN_LANGUAGES[key][rtl ? "ar" : "en"]);
}

function HotelStepBar({ theme, lang, active }) {
  const rtl = isRTL(lang);
  const labels = rtl
    ? ["البحث", "اختيار الفندق", "اختيار الغرفة", "بيانات الضيوف"]
    : ["Search", "Hotel", "Room", "Guests"];
  return (
    <div
      className="hotel-stepbar"
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(4,1fr)",
        maxWidth: 860,
        margin: "0 auto 24px",
        gap: 7,
      }}
    >
      {labels.map((label, i) => (
        <div
          key={label}
          style={{
            padding: "9px 5px",
            textAlign: "center",
            borderRadius: 10,
            background: i <= active ? theme.camelMist : theme.surface,
            color: i <= active ? theme.primary : theme.textMuted,
            font: "600 11px Alexandria",
            border: `1px solid ${i === active ? theme.primary : theme.hairline}`,
          }}
        >
          {i + 1}. {label}
        </div>
      ))}
    </div>
  );
}

function HotelSearchForm({ theme, lang, compact = false, initial, onSearch }) {
  const T = theme,
    rtl = isRTL(lang);
  const seed = initial
    ? {
        ...initial,
        adults:
          (initial.adults ??
            (initial.rooms || []).reduce(
              (n, r) => n + Number(r.adults || 0),
              0,
            )) ||
          2,
        childrenAges:
          initial.childrenAges ??
          (initial.rooms || []).flatMap((r) => r.childrenAges || []),
        roomCount:
          initial.roomCount ?? Math.max(1, (initial.rooms || []).length),
        pets: Boolean(initial.pets),
      }
    : {
        destination: "Makkah",
        countryCode: "SA",
        checkInDate: hotelDate(14),
        checkOutDate: hotelDate(16),
        nationality: "SA",
        residency: "SA",
        adults: 2,
        childrenAges: [],
        roomCount: 1,
        pets: false,
      };
  const [cities, setCities] = React.useState([]),
    [hotels, setHotels] = React.useState([]),
    [busy, setBusy] = React.useState(false),
    [error, setError] = React.useState("");
  const [form, setForm] = React.useState(seed),
    [destinationText, setDestinationText] = React.useState(
      initial
        ? seed.hotelName || hotelLocalized(seed.destination || "Makkah", rtl)
        : "",
    ),
    [destinationOpen, setDestinationOpen] = React.useState(false),
    [datesOpen, setDatesOpen] = React.useState(false),
    [guestsOpen, setGuestsOpen] = React.useState(false);
  const destinationBox = React.useRef(null),
    destinationOverlayInput = React.useRef(null),
    datesBox = React.useRef(null),
    guestsBox = React.useRef(null);
  React.useEffect(() => {
    if (!destinationOpen || typeof window === "undefined") return;
    const mobile = window.matchMedia("(max-width: 600px)").matches;
    if (!mobile) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const focusTimer = window.setTimeout(
      () => destinationOverlayInput.current?.focus(),
      80,
    );
    return () => {
      window.clearTimeout(focusTimer);
      document.body.style.overflow = previousOverflow;
    };
  }, [destinationOpen]);
  React.useEffect(() => {
    let active = true;
    hotelApi("cities", { countryCode: form.countryCode })
      .then(async (b) => {
        const list = b.cities || [];
        if (!active) return;
        setCities(list);
        const chosen =
          list.find(
            (c) =>
              String(c.cityName).toLowerCase() ===
              String(form.destination || "Makkah").toLowerCase(),
          ) || list.find((c) => /makkah|mecca/i.test(c.cityName));
        if (chosen) {
          const result = await hotelApi("hotels", {
            countryCode: form.countryCode,
            cityId: chosen.cityId,
          }).catch(() => ({ hotels: [] }));
          if (active) setHotels((result.hotels || []).slice(0, 300));
        }
      })
      .catch(() =>
        setCities([
          { cityId: 78591, cityName: "Makkah" },
          { cityId: 23028, cityName: "Madinah" },
          { cityId: 9777, cityName: "Jeddah" },
        ]),
      );
    return () => {
      active = false;
    };
  }, [form.countryCode]);
  React.useEffect(() => {
    const close = (e) => {
      if (destinationBox.current && !destinationBox.current.contains(e.target))
        setDestinationOpen(false);
      if (guestsBox.current && !guestsBox.current.contains(e.target))
        setGuestsOpen(false);
      if (datesBox.current && !datesBox.current.contains(e.target))
        setDatesOpen(false);
    };
    document.addEventListener("pointerdown", close);
    return () => document.removeEventListener("pointerdown", close);
  }, []);
  const set = (key, value) => setForm((v) => ({ ...v, [key]: value }));
  const selectCity = async (city) => {
    setDestinationText(hotelLocalized(city.cityName, rtl));
    setForm((v) => ({
      ...v,
      destination: city.cityName,
      cityId: city.cityId,
      hotelId: null,
      hotelName: null,
    }));
    setDestinationOpen(false);
    const result = await hotelApi("hotels", {
      countryCode: form.countryCode,
      cityId: city.cityId,
    }).catch(() => ({ hotels: [] }));
    setHotels((result.hotels || []).slice(0, 300));
  };
  const selectHotel = (hotel) => {
    setDestinationText(hotel.name);
    setForm((v) => ({
      ...v,
      destination: hotel.city || v.destination || "Makkah",
      hotelId: Number(hotel.id),
      hotelName: hotel.name,
    }));
    setDestinationOpen(false);
  };
  const adjust = (key, delta, min, max) =>
    setForm((v) => ({
      ...v,
      [key]: Math.max(min, Math.min(max, Number(v[key] || 0) + delta)),
    }));
  const setChildren = (count) =>
    setForm((v) => {
      const ages = [...(v.childrenAges || [])];
      while (ages.length < count) ages.push(7);
      return { ...v, childrenAges: ages.slice(0, count) };
    });
  const setChildAge = (index, age) =>
    setForm((v) => ({
      ...v,
      childrenAges: (v.childrenAges || []).map((x, i) =>
        i === index ? Number(age) : x,
      ),
    }));
  const makeRooms = () => {
    const count = Math.max(1, Number(form.roomCount)),
      adultTotal = Math.max(count, Number(form.adults)),
      rooms = Array.from({ length: count }, () => ({
        adults: 0,
        childrenAges: [],
      }));
    for (let i = 0; i < adultTotal; i++) rooms[i % count].adults++;
    (form.childrenAges || []).forEach((age, i) =>
      rooms[i % count].childrenAges.push(age),
    );
    return rooms;
  };
  const submit = async (e) => {
    e.preventDefault();
    setError("");
    if (form.checkOutDate <= form.checkInDate)
      return setError(
        rtl
          ? "تاريخ المغادرة يجب أن يكون بعد الوصول."
          : "Check-out must be after check-in.",
      );
    setBusy(true);
    try {
      const query = {
        ...form,
        destination: form.destination || "Makkah",
        rooms: makeRooms(),
      };
      await onSearch(query, form.hotelId ? [Number(form.hotelId)] : undefined);
    } catch (err) {
      setError(
        rtl
          ? "تعذر جلب الفنادق الآن. جرّب تاريخًا آخر أو وجهة أخرى."
          : "Hotels could not be loaded. Try different dates or another destination.",
      );
    } finally {
      setBusy(false);
    }
  };
  const fieldStyle = {
    width: "100%",
    minHeight: 50,
    padding: "11px 12px",
    border: `1px solid ${T.hairlineStrong}`,
    borderRadius: 11,
    background: T.bg,
    color: T.text,
    font: "600 13px Alexandria",
  };
  const q = destinationText.trim().toLowerCase(),
    apiQ = q
      .replace(/مكة المكرمة|مكة/g, "makkah")
      .replace(/المدينة المنورة|المدينة/g, "madinah")
      .replace(/جدة/g, "jeddah"),
    popularCityNames = [
      "Makkah",
      "Madinah",
      "Jeddah",
      "Riyadh",
      "Dammam",
      "Al Khobar",
    ],
    popularCities = popularCityNames
      .map((name) =>
        cities.find((c) =>
          String(c.cityName || "")
            .toLowerCase()
            .includes(name.toLowerCase()),
        ),
      )
      .filter(Boolean),
    cityMatches = cities
      .filter((c) => !apiQ || c.cityName.toLowerCase().includes(apiQ))
      .slice(0, apiQ ? 6 : 0),
    hotelMatches = hotels
      .filter(
        (h) =>
          apiQ && `${h.name} ${h.address || ""}`.toLowerCase().includes(apiQ),
      )
      .slice(0, 8),
    visibleCities = apiQ
      ? cityMatches
      : popularCities.length
        ? popularCities
        : cities.slice(0, 6);
  const destinationInput = (overlay = false) => (
    <div className={overlay ? "hotel-destination-overlay-input" : ""} style={{ position: "relative" }}>
      <span
        style={{
          position: "absolute",
          insetInlineStart: 13,
          top: 15,
          fontSize: 18,
        }}
      >
        ⌖
      </span>
      <input
        ref={overlay ? destinationOverlayInput : null}
        value={destinationText}
        onFocus={() => setDestinationOpen(true)}
        onChange={(e) => {
          setDestinationText(e.target.value);
          setDestinationOpen(true);
          setForm((v) => ({ ...v, hotelId: null, hotelName: null }));
        }}
        placeholder={rtl ? "ابحث عن مدينة أو فندق أو مكان إقامة" : "Search for a city, hotel or property"}
        autoComplete="off"
        aria-label={rtl ? "ابحث عن وجهة أو فندق" : "Search destination or hotel"}
        style={{ ...fieldStyle, paddingInlineStart: 39 }}
      />
    </div>
  );
  const counter = (label, key, min, max) => (
    <div
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 18,
        padding: "10px 0",
      }}
    >
      <span style={{ color: T.text, font: "600 13px Alexandria" }}>
        {label}
      </span>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <button
          type="button"
          aria-label={`decrease ${key}`}
          onClick={() => adjust(key, -1, min, max)}
          style={{
            width: 34,
            height: 34,
            border: `1px solid ${T.primary}`,
            borderRadius: 8,
            background: T.surface,
            color: T.primary,
            fontSize: 22,
          }}
        >
          −
        </button>
        <strong style={{ minWidth: 20, textAlign: "center", color: T.text }}>
          {form[key]}
        </strong>
        <button
          type="button"
          aria-label={`increase ${key}`}
          onClick={() => adjust(key, 1, min, max)}
          style={{
            width: 34,
            height: 34,
            border: `1px solid ${T.primary}`,
            borderRadius: 8,
            background: T.surface,
            color: T.primary,
            fontSize: 20,
          }}
        >
          +
        </button>
      </div>
    </div>
  );
  return (
    <form
      onSubmit={submit}
      className="hotel-search-form"
      style={{
        position: "relative",
        zIndex: 20,
        background: T.surface,
        border: `1px solid ${T.hairline}`,
        borderRadius: 18,
        padding: compact ? 14 : 20,
        boxShadow: compact ? "none" : T.cardShadow,
      }}
    >
      <div
        className="hotel-booking-search-grid"
        style={{
          display: "grid",
          gridTemplateColumns: compact
            ? "1.35fr 1.35fr 1fr"
            : "1.45fr 1.4fr 1.05fr",
          gap: 7,
        }}
      >
        <div ref={destinationBox} style={{ position: "relative" }}>
          <label
            style={{
              display: "block",
              color: T.textMuted,
              font: "600 11px Alexandria",
            }}
          >
            {rtl ? "الوجهة أو مكان الإقامة" : "Destination or property"}
            {destinationInput(false)}
          </label>
          {destinationOpen && (
            <div
              className="hotel-autocomplete hotel-destination-picker"
              style={{
                position: "absolute",
                zIndex: 40,
                insetInline: 0,
                top: "calc(100% + 7px)",
                maxHeight: 390,
                overflowY: "auto",
                background: T.surface,
                border: `1px solid ${T.hairlineStrong}`,
                borderRadius: 13,
                boxShadow: "0 18px 45px rgba(32,27,23,.18)",
              }}
            >
              <div className="hotel-autocomplete-mobile-head">
                <button
                  type="button"
                  className="hotel-autocomplete-back"
                  onClick={() => setDestinationOpen(false)}
                  aria-label={rtl ? "رجوع" : "Back"}
                >
                  {rtl ? "←" : "→"}
                </button>
                <strong>{rtl ? "اختر وجهتك" : "Choose your destination"}</strong>
              </div>
              <div className="hotel-autocomplete-mobile-search">
                {destinationInput(true)}
              </div>
              {!apiQ && (
                <div className="hotel-suggestion-heading">
                  <strong>{rtl ? "المدن الأكثر بحثًا" : "Popular destinations"}</strong>
                  <span>{rtl ? "وجهات يفضلها المسافرون" : "Traveller favourites"}</span>
                </div>
              )}
              {!!apiQ && !!hotelMatches.length && (
                <div className="hotel-suggestion-group-label">
                  {rtl ? "الفنادق وأماكن الإقامة" : "Hotels and properties"}
                </div>
              )}
              {hotelMatches.map((h) => (
                <button
                  type="button"
                  key={`h-${h.id}`}
                  onClick={() => selectHotel(h)}
                  className="hotel-suggestion-row"
                  style={{
                    display: "grid",
                    gridTemplateColumns: "30px 1fr",
                    gap: 10,
                    width: "100%",
                    padding: "12px 14px",
                    textAlign: "start",
                    border: 0,
                    borderBottom: `1px solid ${T.hairline}`,
                    background: "transparent",
                    color: T.text,
                    font: "600 12px Alexandria",
                  }}
                >
                  <span style={{ fontSize: 20 }}>▣</span>
                  <span>
                    {h.name}
                    <small
                      style={{
                        display: "block",
                        marginTop: 3,
                        color: T.textMuted,
                        font: "500 9px Alexandria",
                      }}
                    >
                      {hotelLocalized(h.address || h.city, rtl)}
                    </small>
                  </span>
                </button>
              ))}
              {!!apiQ && !!visibleCities.length && (
                <div className="hotel-suggestion-group-label">
                  {rtl ? "المدن والوجهات" : "Cities and destinations"}
                </div>
              )}
              {visibleCities.map((c) => (
                <button
                  type="button"
                  key={`c-${c.cityId}`}
                  onClick={() => selectCity(c)}
                  className="hotel-suggestion-row"
                  style={{
                    display: "grid",
                    gridTemplateColumns: "30px 1fr",
                    gap: 10,
                    width: "100%",
                    padding: "12px 14px",
                    textAlign: "start",
                    border: 0,
                    borderBottom: `1px solid ${T.hairline}`,
                    background: "transparent",
                    color: T.text,
                    font: "600 12px Alexandria",
                  }}
                >
                  <span style={{ fontSize: 20 }}>⌖</span>
                  <span>
                    {hotelLocalized(c.cityName, rtl)}
                    <small
                      style={{
                        display: "block",
                        marginTop: 3,
                        color: T.textMuted,
                        font: "500 9px Alexandria",
                      }}
                    >
                      {rtl
                        ? "مدينة في المملكة العربية السعودية"
                        : "City in Saudi Arabia"}
                    </small>
                  </span>
                </button>
              ))}
              {!hotelMatches.length && !visibleCities.length && (
                <div
                  style={{
                    padding: 18,
                    color: T.textMuted,
                    font: "500 12px Alexandria",
                  }}
                >
                  {rtl
                    ? "لم نجد نتيجة مطابقة."
                    : "No matching destination found."}
                </div>
              )}
            </div>
          )}
        </div>
        <fieldset ref={datesBox} style={{ border: 0, padding: 0, margin: 0, minWidth: 0, position: "relative" }}>
          <legend style={{ color: T.textMuted, font: "600 11px Alexandria", padding: 0 }}>
            {rtl ? "فترة الإقامة" : "Stay dates"}
          </legend>
          <button type="button" className="hotel-date-trigger" onClick={() => setDatesOpen(v => !v)} style={{...fieldStyle,textAlign:"start",cursor:"pointer"}}>
            <Icon name="calendar" size={17} color={T.primary}/>{" "}{form.checkInDate} — {form.checkOutDate}
          </button>
          {datesOpen && <div className="hotel-date-popover hotel-motion-popover" style={{position:"absolute",zIndex:45,insetInline:0,top:"calc(100% + 7px)",padding:18,background:T.surface,border:`1px solid ${T.hairlineStrong}`,borderRadius:14,boxShadow:"0 20px 50px rgba(32,27,23,.2)"}}>
            <DateRangeCalendar theme={T} lang={lang} start={form.checkInDate} end={form.checkOutDate} onChange={(checkInDate,checkOutDate)=>setForm(v=>({...v,checkInDate,checkOutDate}))} onDone={()=>setDatesOpen(false)}/>
          </div>}
        </fieldset>
        <div ref={guestsBox} style={{ position: "relative" }}>
          <label
            style={{
              display: "block",
              color: T.textMuted,
              font: "600 11px Alexandria",
            }}
          >
            {rtl ? "الضيوف والغرف" : "Guests and rooms"}
            <button
              type="button"
              onClick={() => setGuestsOpen((v) => !v)}
              style={{ ...fieldStyle, textAlign: "start", cursor: "pointer" }}
            >
              {rtl
                ? `${form.adults} بالغ · ${(form.childrenAges || []).length} أطفال · ${form.roomCount} غرف`
                : `${form.adults} adults · ${(form.childrenAges || []).length} children · ${form.roomCount} rooms`}
            </button>
          </label>
          {guestsOpen && (
            <div
              className="hotel-guests-popover"
              style={{
                position: "absolute",
                zIndex: 40,
                insetInlineEnd: 0,
                top: "calc(100% + 7px)",
                width: 330,
                maxWidth: "calc(100vw - 44px)",
                padding: "10px 18px 16px",
                background: T.surface,
                border: `1px solid ${T.hairlineStrong}`,
                borderRadius: 13,
                boxShadow: "0 18px 45px rgba(32,27,23,.18)",
              }}
            >
              {counter(rtl ? "البالغون" : "Adults", "adults", 1, 30)}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 18,
                  padding: "10px 0",
                }}
              >
                <span style={{ color: T.text, font: "600 13px Alexandria" }}>
                  {rtl ? "الأطفال" : "Children"}
                  <small
                    style={{
                      display: "block",
                      color: T.textMuted,
                      font: "500 9px Alexandria",
                    }}
                  >
                    {rtl ? "من 0 إلى 17 سنة" : "Ages 0–17"}
                  </small>
                </span>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <button
                    type="button"
                    onClick={() =>
                      setChildren(
                        Math.max(0, (form.childrenAges || []).length - 1),
                      )
                    }
                    style={{
                      width: 34,
                      height: 34,
                      border: `1px solid ${T.primary}`,
                      borderRadius: 8,
                      background: T.surface,
                      color: T.primary,
                      fontSize: 22,
                    }}
                  >
                    −
                  </button>
                  <strong style={{ minWidth: 20, textAlign: "center" }}>
                    {(form.childrenAges || []).length}
                  </strong>
                  <button
                    type="button"
                    onClick={() =>
                      setChildren(
                        Math.min(10, (form.childrenAges || []).length + 1),
                      )
                    }
                    style={{
                      width: 34,
                      height: 34,
                      border: `1px solid ${T.primary}`,
                      borderRadius: 8,
                      background: T.surface,
                      color: T.primary,
                      fontSize: 20,
                    }}
                  >
                    +
                  </button>
                </div>
              </div>
              {(form.childrenAges || []).length > 0 && (
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "repeat(2,minmax(0,1fr))",
                    gap: 8,
                    padding: "5px 0 10px",
                  }}
                >
                  {form.childrenAges.map((age, i) => (
                    <label
                      key={i}
                      style={{ color: T.textMuted, font: "500 9px Alexandria" }}
                    >
                      {rtl ? `عمر الطفل ${i + 1}` : `Child ${i + 1} age`}
                      <select
                        value={age}
                        onChange={(e) => setChildAge(i, e.target.value)}
                        style={{
                          ...fieldStyle,
                          minHeight: 40,
                          padding: 7,
                          marginTop: 4,
                        }}
                      >
                        {Array.from({ length: 18 }, (_, ageValue) => (
                          <option key={ageValue} value={ageValue}>
                            {ageValue} {rtl ? "سنة" : "years"}
                          </option>
                        ))}
                      </select>
                    </label>
                  ))}
                </div>
              )}
              {counter(rtl ? "الغرف" : "Rooms", "roomCount", 1, 10)}
              <label
                style={{
                  display: "flex",
                  alignItems: "flex-start",
                  gap: 9,
                  padding: "10px 0",
                  borderTop: `1px solid ${T.hairline}`,
                  color: T.text,
                  font: "500 11px/1.6 Alexandria",
                }}
              >
                <input
                  type="checkbox"
                  checked={Boolean(form.pets)}
                  onChange={(e) => set("pets", e.target.checked)}
                />
                <span>
                  {rtl ? "أسافر مع حيوان أليف" : "I’m travelling with pets"}
                  <small
                    style={{
                      display: "block",
                      color: T.textMuted,
                      font: "500 9px Alexandria",
                    }}
                  >
                    {rtl
                      ? "سنوضح الفنادق التي تسمح بذلك عند توفر المعلومة."
                      : "Pet-friendly availability depends on property policy."}
                  </small>
                </span>
              </label>
              <button
                type="button"
                onClick={() => setGuestsOpen(false)}
                style={{
                  width: "100%",
                  height: 42,
                  border: 0,
                  borderRadius: 9,
                  background: T.primary,
                  color: "#fff",
                  font: "700 12px Alexandria",
                }}
              >
                {rtl ? "تم" : "Done"}
              </button>
            </div>
          )}
        </div>
      </div>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 12,
          marginTop: 12,
          flexWrap: "wrap",
        }}
      >
        <span style={{ color: T.textMuted, font: "500 11px Alexandria" }}>
          {rtl
            ? "الأسعار والتوفر يتم تأكيدهما مباشرة قبل الحجز."
            : "Prices and availability are rechecked immediately before booking."}
        </span>
        <button
          disabled={busy}
          type="submit"
          style={{
            minHeight: 48,
            padding: "0 26px",
            border: 0,
            borderRadius: 11,
            background: T.primary,
            color: "#fff",
            font: "700 13px Alexandria",
            cursor: "pointer",
            opacity: busy ? 0.65 : 1,
          }}
        >
          {busy
            ? rtl
              ? "جارٍ البحث…"
              : "Searching…"
            : rtl
              ? "بحث عن فنادق"
              : "Search hotels"}
        </button>
      </div>
      {error && (
        <p
          role="alert"
          style={{
            margin: "10px 0 0",
            color: "#b42318",
            font: "600 12px Alexandria",
          }}
        >
          {error}
        </p>
      )}
    </form>
  );
}

function WebHotelsSearchPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    ctx = useWeb();
  const [catalog, setCatalog] = React.useState([]),
    [catalogBusy, setCatalogBusy] = React.useState(true),
    [catalogError, setCatalogError] = React.useState(""),
    [catalogQuery, setCatalogQuery] = React.useState(""),
    [visible, setVisible] = React.useState(6),
    [destinations, setDestinations] = React.useState([]);
  const [catalogImages, setCatalogImages] = React.useState({});
  const catalogSwipeStart = React.useRef({});
  const defaultQuery = ctx.hotel?.query || {
    destination: "Makkah",
    countryCode: "SA",
    checkInDate: hotelDate(14),
    checkOutDate: hotelDate(16),
    nationality: "SA",
    residency: "SA",
    rooms: [{ adults: 2, childrenAges: [] }],
  };
  const search = async (query, hotelIds) => {
    const body = await hotelApi("search", {
      destination: query.destination,
      countryCode: query.countryCode,
      checkInDate: query.checkInDate,
      checkOutDate: query.checkOutDate,
      nationality: query.nationality,
      residency: query.residency,
      rooms: query.rooms,
      hotelIds,
    });
    const hotels = body.hotels || [];
    if (hotelIds?.length && !hotels.length)
      throw new Error("hotel_not_available");
    ctx.setHotel({
      ...ctx.hotel,
      query,
      results: hotels,
      currency: body.currency || "SAR",
      sessionId: body.sessionId,
    });
    ctx.setPage("hotel-results");
  };
  React.useEffect(() => {
    let active = true;
    (async () => {
      try {
        const cityBody = await hotelApi("cities", { countryCode: "SA" });
        const allCities = cityBody.cities || [];
        const preferred = [
          /makkah|mecca/i,
          /madinah|medina/i,
          /jeddah/i,
          /riyadh/i,
          /abha/i,
          /dammam|khobar/i,
        ]
          .map((pattern) => allCities.find((city) => pattern.test(city.cityName)))
          .filter(Boolean);
        const discovered = await Promise.all(
          preferred.map(async (city) => {
            try {
              const body = await hotelApi("search", {
                ...defaultQuery,
                destination: city.cityName,
              });
              const hotels = (body.hotels || []).filter((hotel) => hotelImage(hotel));
              return hotels.length ? { ...city, hotels, image: hotelImage(hotels[0]) } : null;
            } catch (_) {
              return null;
            }
          }),
        );
        const ready = discovered.filter(Boolean);
        const hotels = ready
          .flatMap((city) => city.hotels.map((hotel) => ({ ...hotel, landingCity: city.cityName })))
          .filter((hotel, index, list) =>
            list.findIndex((candidate) =>
              String(candidate.hotelCode || candidate.id) === String(hotel.hotelCode || hotel.id),
            ) === index,
          );
        if (!active) return;
        setDestinations(ready);
        setCatalog(hotels);
        if (!hotels.length)
          setCatalogError(
            rtl
              ? "لا توجد حاليًا فنادق بصور وأسعار متاحة لهذه الفترة. غيّر التواريخ للبحث المباشر."
              : "No hotels with imagery and live rates are available for these dates. Try different dates.",
          );
      } catch (_) {
        if (active)
          setCatalogError(
            rtl
              ? "تعذر تحميل كتالوج الفنادق."
              : "Could not load the hotel catalog.",
          );
      } finally {
        if (active) setCatalogBusy(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);
  const chooseDestination = async (city) => {
    setCatalogError("");
    try {
      await search({ ...defaultQuery, destination: city.cityName });
    } catch (_) {
      setCatalogError(
        rtl ? "تعذر جلب فنادق هذه الوجهة الآن." : "Hotels for this destination could not be loaded.",
      );
    }
  };
  const defaultDestination = String(defaultQuery.destination || "Makkah").toLowerCase();
  const filtered = catalog.filter((h) => {
    const matchesText = `${h.name || h.hotelName || ""} ${h.address || ""}`
      .toLowerCase()
      .includes(catalogQuery.toLowerCase());
    const matchesDestination = String(h.landingCity || "").toLowerCase() === defaultDestination;
    return catalogQuery ? matchesText : matchesDestination;
  });
  const check = async (h) => {
    setCatalogError("");
    if ((h.rooms || []).length) {
      ctx.setHotel({
        ...ctx.hotel,
        query: { ...defaultQuery, destination: h.landingCity || defaultQuery.destination },
        results: [h],
        currency: h.currency || "SAR",
      });
      ctx.setPage("hotel-results");
      return;
    }
    try {
      await search(defaultQuery, [Number(h.id || h.hotelCode)]);
    } catch (_) {
      setCatalogError(
        rtl
          ? "لا يوجد سعر متاح لهذا الفندق في التواريخ الحالية. غيّر التواريخ من نموذج البحث."
          : "No rate is available for this hotel on the current dates. Change the dates above.",
      );
    }
  };
  return (
    <main style={{ minHeight: 700, background: T.bg }}>
      <WebPageHeader
        theme={T}
        lang={lang}
        eyebrow={rtl ? "إقامة موثوقة" : "Trusted stays"}
        title={rtl ? "احجز إقامتك القادمة" : "Find your next stay"}
        sub={
          rtl
            ? "ابحث بالوجهة وفترة الإقامة والضيوف، ثم قارن الخيارات المتاحة بصور وأسعار مباشرة."
            : "Search by destination, stay dates and guests, then compare live options with verified property photos and rates."
        }
      />
      <section
        style={{
          maxWidth: 1180,
          margin: "-28px auto 0",
          position: "relative",
          padding: "0 16px 70px",
        }}
      >
        <HotelSearchForm
          theme={T}
          lang={lang}
          initial={ctx.hotel?.query}
          onSearch={search}
        />
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(3,1fr)",
            gap: 14,
            marginTop: 22,
          }}
        >
          {(rtl
            ? [
                "أسعار مباشرة من المزوّد",
                "سياسة إلغاء واضحة",
                "تأكيد التوفر قبل الدفع",
              ]
            : [
                "Live rates",
                "Clear cancellation terms",
                "Availability rechecked",
              ]
          ).map((x) => (
            <div
              key={x}
              style={{
                padding: 18,
                borderRadius: 14,
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                color: T.text,
                font: "700 13px Alexandria",
              }}
            >
              <span
                style={{
                  display: "inline-grid",
                  placeItems: "center",
                  width: 28,
                  height: 28,
                  borderRadius: 99,
                  background: T.camelMist,
                  color: T.primary,
                  marginInlineEnd: 8,
                }}
              >
                ✓
              </span>
              {x}
            </div>
          ))}
        </div>
        {destinations.length > 0 && (
          <>
            <section style={{ marginTop: 42 }}>
              <h2 style={{ margin: "0 0 5px", color: T.text, font: "700 clamp(23px,4vw,32px) Alexandria" }}>
                {rtl ? "وجهات رائجة" : "Trending destinations"}
              </h2>
              <p style={{ margin: "0 0 15px", color: T.textMuted, font: "500 12px Alexandria" }}>
                {rtl ? "وجهات يكثر البحث عنها داخل المملكة" : "Popular places travellers are searching for"}
              </p>
              <div className="hotel-destination-strip" style={{ display: "flex", gap: 14, overflowX: "auto", paddingBottom: 8, scrollSnapType: "x mandatory" }}>
                {destinations.slice(0, 4).map((city) => (
                  <button key={`trend-${city.cityId}`} type="button" onClick={() => chooseDestination(city)} style={{ position: "relative", flex: "0 0 min(360px,82vw)", height: 220, padding: 0, overflow: "hidden", border: 0, borderRadius: 17, cursor: "pointer", scrollSnapAlign: "start", background: T.surface }}>
                    <img src={city.image} alt={hotelLocalized(city.cityName, rtl)} loading="lazy" onError={(event) => { event.currentTarget.closest("button").style.display = "none"; }} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    <span style={{ position: "absolute", inset: 0, background: "linear-gradient(0deg,rgba(20,16,12,.78),transparent 65%)" }} />
                    <strong style={{ position: "absolute", insetInlineStart: 18, bottom: 17, color: "#fff", font: "700 24px Alexandria" }}>{hotelLocalized(city.cityName, rtl)}</strong>
                  </button>
                ))}
              </div>
            </section>
            <section style={{ marginTop: 38 }}>
              <h2 style={{ margin: "0 0 5px", color: T.text, font: "700 clamp(23px,4vw,32px) Alexandria" }}>
                {rtl ? "اكتشف السعودية" : "Explore Saudi Arabia"}
              </h2>
              <p style={{ margin: "0 0 15px", color: T.textMuted, font: "500 12px Alexandria" }}>
                {rtl ? "وجهات سعودية متاحة للحجز" : "Saudi destinations available to book"}
              </p>
              <div className="hotel-city-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 14 }}>
                {destinations.map((city) => (
                  <button key={`city-${city.cityId}`} type="button" onClick={() => chooseDestination(city)} style={{ padding: 0, overflow: "hidden", textAlign: "start", border: `1px solid ${T.hairline}`, borderRadius: 15, background: T.surface, cursor: "pointer" }}>
                    <img src={city.image} alt="" loading="lazy" onError={(event) => { event.currentTarget.closest("button").style.display = "none"; }} style={{ display: "block", width: "100%", height: 150, objectFit: "cover" }} />
                    <span style={{ display: "block", padding: 14 }}>
                      <strong style={{ display: "block", color: T.text, font: "700 16px Alexandria" }}>{hotelLocalized(city.cityName, rtl)}</strong>
                      <small style={{ color: T.textMuted, font: "500 10px Alexandria" }}>{rtl ? `${city.hotels.length} خيارات متاحة الآن` : `${city.hotels.length} options available now`}</small>
                    </span>
                  </button>
                ))}
              </div>
            </section>
          </>
        )}
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "end",
            gap: 16,
            flexWrap: "wrap",
            marginTop: 42,
          }}
        >
          <div>
            <span style={{ color: T.primary, font: "600 11px Alexandria" }}>
              {rtl ? "إقامات مقترحة" : "RECOMMENDED STAYS"}
            </span>
            <h2
              style={{
                margin: "5px 0",
                color: T.text,
                font: "700 clamp(24px,5vw,34px) Alexandria",
              }}
            >
              {rtl
                ? `فنادق مقترحة في ${hotelLocalized(defaultQuery.destination || "Makkah", rtl)}`
                : "Hotels with imagery and live rates"}
            </h2>
          </div>
          <input
            value={catalogQuery}
            onChange={(e) => {
              setCatalogQuery(e.target.value);
              setVisible(6);
            }}
            placeholder={
              rtl ? "ابحث باسم الفندق أو العنوان…" : "Search name or address…"
            }
            style={{
              width: "min(100%,360px)",
              height: 48,
              boxSizing: "border-box",
              padding: "0 14px",
              border: `1px solid ${T.hairlineStrong}`,
              borderRadius: 12,
              background: T.surface,
              color: T.text,
              font: "500 13px Alexandria",
            }}
          />
        </div>
        {catalogError && (
          <p
            role="alert"
            style={{
              padding: 12,
              borderRadius: 10,
              background: "#fff1f0",
              color: "#b42318",
              font: "600 12px Alexandria",
            }}
          >
            {catalogError}
          </p>
        )}
        {catalogBusy ? (
          <div style={{ padding: 50, textAlign: "center", color: T.textMuted }}>
            {rtl ? "جارٍ تحميل كتالوج الفنادق…" : "Loading hotel catalog…"}
          </div>
        ) : (
          <div
            className="hotel-catalog-grid"
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3,minmax(0,1fr))",
              gap: 16,
              marginTop: 18,
            }}
          >
            {filtered.filter((h) => hotelImage(h)).slice(0, visible).map((h) => {
              const gallery = hotelImages(h);
              const imageKey = String(h.id || h.hotelCode);
              const imageIndex = Math.min(catalogImages[imageKey] || 0, Math.max(0, gallery.length - 1));
              const moveImage = (delta) => setCatalogImages((current) => ({
                ...current,
                [imageKey]: (imageIndex + delta + gallery.length) % gallery.length,
              }));
              return (
              <article
                key={h.id || h.hotelCode}
                style={{
                  overflow: "hidden",
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 17,
                  boxShadow: T.cardShadow,
                }}
              >
                <div
                  className="hotel-card-gallery"
                  onTouchStart={(event) => { catalogSwipeStart.current[imageKey] = event.touches[0].clientX; }}
                  onTouchEnd={(event) => {
                    const delta = event.changedTouches[0].clientX - (catalogSwipeStart.current[imageKey] || 0);
                    if (gallery.length > 1 && Math.abs(delta) > 40) moveImage(delta < 0 ? 1 : -1);
                  }}
                  style={{
                    height: 190,
                    position: "relative",
                    background: T.surfaceAlt,
                  }}
                >
                  <img
                    src={gallery[imageIndex]}
                    alt={hotelName(h, rtl)}
                    loading="lazy"
                    onError={(event) => { event.currentTarget.closest("article").style.display = "none"; }}
                    style={{ width: "100%", height: "100%", objectFit: "cover" }}
                  />
                  {gallery.length > 1 && <>
                    <button type="button" className="hotel-gallery-prev" aria-label={rtl ? "الصورة السابقة" : "Previous image"} onClick={() => moveImage(-1)}>‹</button>
                    <button type="button" className="hotel-gallery-next" aria-label={rtl ? "الصورة التالية" : "Next image"} onClick={() => moveImage(1)}>›</button>
                    <span className="hotel-gallery-dots" aria-hidden="true">
                      {gallery.slice(0, 8).map((_, index) => <i key={index} className={imageIndex === index ? "is-active" : ""} />)}
                    </span>
                  </>}
                  <span
                    style={{
                      position: "absolute",
                      insetInlineStart: 12,
                      bottom: 12,
                      padding: "6px 9px",
                      borderRadius: 99,
                      background: "rgba(255,255,255,.9)",
                      color: T.text,
                      font: "700 10px Alexandria",
                    }}
                  >
                    {hotelLocalized(h.landingCity || h.city || "Saudi Arabia", rtl)}
                  </span>
                </div>
                <div style={{ padding: 16 }}>
                  <small
                    style={{
                      display: "inline-block",
                      padding: "4px 7px",
                      borderRadius: 99,
                      background: T.camelMist,
                      color: T.primary,
                      font: "700 9px Alexandria",
                    }}
                  >
                    {rtl ? "سعر مباشر" : "Live rate"}
                  </small>
                  <h3
                    style={{
                      minHeight: 45,
                      margin: "7px 0 5px",
                      color: T.text,
                      font: "700 16px/1.45 Alexandria",
                    }}
                  >
                    {hotelName(h, rtl)}
                  </h3>
                  <p
                    style={{
                      minHeight: 42,
                      margin: "6px 0",
                      color: T.textMuted,
                      font: "500 11px/1.7 Alexandria",
                    }}
                  >
                    {hotelLocalized(h.address || h.city, rtl)}
                  </p>
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      gap: 10,
                      marginTop: 14,
                    }}
                  >
                    <span
                      style={{
                        color: T.textMuted,
                        font: "600 10px Alexandria",
                      }}
                    >
                      {rtl ? "السعر والتوفر مباشر" : "Live price and availability"}
                    </span>
                    <button
                      onClick={() => check(h)}
                      style={{
                        minHeight: 42,
                        padding: "0 14px",
                        border: 0,
                        borderRadius: 10,
                        background: T.primary,
                        color: "#fff",
                        font: "700 11px Alexandria",
                      }}
                    >
                      {rtl ? "عرض الغرف" : "See rooms"}
                    </button>
                  </div>
                </div>
              </article>
              );
            })}
          </div>
        )}
        {visible < filtered.filter((h) => hotelImage(h)).length && (
          <button
            onClick={() => setVisible((v) => Math.min(v + 24, 300))}
            style={{
              display: "block",
              margin: "24px auto 0",
              minHeight: 48,
              padding: "0 28px",
              border: `1px solid ${T.primary}`,
              borderRadius: 11,
              background: T.surface,
              color: T.primary,
              font: "700 13px Alexandria",
            }}
          >
            {rtl ? "عرض المزيد من الفنادق" : "Show more hotels"}
          </button>
        )}
      </section>
    </main>
  );
}

function WebHotelResultsPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    ctx = useWeb(),
    data = ctx.hotel || {},
    [sort, setSort] = React.useState("recommended"),
    [refundable, setRefundable] = React.useState(false),
    [stars, setStars] = React.useState(0),
    [mealPlan, setMealPlan] = React.useState("all"),
    [priceCap, setPriceCap] = React.useState(0),
    [sheet, setSheet] = React.useState(null),
    [displayCurrency, setDisplayCurrency] = React.useState(data.currency || "SAR"),
    [activeImages, setActiveImages] = React.useState({}),
    [loading, setLoading] = React.useState(false);
  const swipeStart = React.useRef({});
  const nightCount = hotelNightCount(data.query),
    guestCount = hotelGuestCount(data.query),
    roomCount = Math.max(1, (data.query?.rooms || []).length);
  const currencyRate = displayCurrency === "USD" ? 1 / 3.75 : displayCurrency === "AED" ? 1 / 1.021 : 1;
  const money = (value) => (Number(value || 0) * currencyRate).toLocaleString(undefined, { maximumFractionDigits: 2 });
  const currencyLabel = displayCurrency === "SAR" ? (rtl ? "ر.س" : "SAR") : displayCurrency;
  React.useEffect(() => {
    document.body.style.overflow = sheet ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [sheet]);
  const search = async (query, hotelIds) => {
    setLoading(true);
    try {
      const body = await hotelApi("search", {
        destination: query.destination,
        countryCode: query.countryCode,
        checkInDate: query.checkInDate,
        checkOutDate: query.checkOutDate,
        nationality: query.nationality,
        residency: query.residency,
        rooms: query.rooms,
        hotelIds,
      });
      ctx.setHotel({
        ...data,
        query,
        results: body.hotels || [],
        currency: body.currency || "SAR",
      });
    } finally {
      setLoading(false);
    }
  };
  let hotels = (data.results || []).filter((h) => {
    const best = hotelBestRoom(h),
      price = Number(best?.totalPrice ?? best?.price ?? 0),
      boards = (h.rooms || []).map((room) => String(room.boardType || "").toLowerCase());
    const mealMatch =
      mealPlan === "all" ||
      (mealPlan === "breakfast" && boards.some((board) => /breakfast|half board|full board|all inclusive/.test(board))) ||
      (mealPlan === "room" && boards.some((board) => /room only/.test(board)));
    return (
      hotelImages(h).length > 0 &&
      (!stars || Number(h.starRating) >= stars) &&
      (!refundable || (h.rooms || []).some((r) => r.isRefundable)) &&
      (!priceCap || (price > 0 && price <= priceCap)) &&
      mealMatch
    );
  });
  hotels = [...hotels].sort((a, b) =>
    sort === "price"
      ? Number(hotelBestRoom(a)?.totalPrice ?? hotelBestRoom(a)?.price ?? Infinity) -
        Number(hotelBestRoom(b)?.totalPrice ?? hotelBestRoom(b)?.price ?? Infinity)
      : sort === "price-high"
        ? Number(hotelBestRoom(b)?.totalPrice ?? hotelBestRoom(b)?.price ?? 0) -
          Number(hotelBestRoom(a)?.totalPrice ?? hotelBestRoom(a)?.price ?? 0)
      : sort === "stars"
        ? Number(b.starRating) - Number(a.starRating)
        : sort === "smart"
          ? (Number(b.reviewScore || b.rating || b.starRating || 0) * 100 - Number(hotelBestRoom(b)?.totalPrice || 0) / 20) -
            (Number(a.reviewScore || a.rating || a.starRating || 0) * 100 - Number(hotelBestRoom(a)?.totalPrice || 0) / 20)
        : 0,
  );
  const open = async (h) => {
    setLoading(true);
    try {
      const q = data.query,
        body = await hotelApi("details", {
          token: h.token,
          hotelCode: h.hotelCode,
          countryCode: q.countryCode,
          destination: q.destination,
          checkInDate: q.checkInDate,
          checkOutDate: q.checkOutDate,
          nationality: q.nationality,
          residency: q.residency,
          rooms: q.rooms,
        });
      ctx.setHotel({
        ...data,
        selectedHotel: { ...h, ...body },
        currency: body.currency || data.currency,
      });
      ctx.setPage("hotel-details");
    } catch (_) {
      alert(
        rtl ? "تعذر تحميل تفاصيل الفندق." : "Could not load hotel details.",
      );
    } finally {
      setLoading(false);
    }
  };
  return (
    <main style={{ minHeight: 720, background: T.bg, paddingBottom: 70 }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "24px 16px" }}>
        <div className="hotel-results-topbar">
          <button type="button" className="hotel-round-action" onClick={() => ctx.setPage("hotels")} aria-label={rtl ? "رجوع" : "Back"}>{rtl ? "→" : "←"}</button>
          <button type="button" className="hotel-search-summary" onClick={() => setSheet("search") }>
            <strong>{hotelLocalized(data.query?.destination, rtl)}</strong>
            <span>{hotelFormatDate(data.query?.checkInDate, rtl)} — {hotelFormatDate(data.query?.checkOutDate, rtl)} · {guestCount} {rtl ? "ضيف" : "guests"}</span>
          </button>
          <button type="button" className="hotel-currency-action" onClick={() => setSheet("currency")}>{displayCurrency}</button>
        </div>
        <div className="hotel-mobile-filter-row">
          <button type="button" onClick={() => setSheet("filters")}>{rtl ? "تصفية البحث" : "Filters"} ⚙</button>
          <button type="button" onClick={() => setSheet("sort")}>{rtl ? "الأكثر شعبية" : "Popular"} ↕</button>
        </div>
        <div
          className="hotel-results-layout"
          style={{
            display: "grid",
            gridTemplateColumns: "250px minmax(0,1fr)",
            gap: 22,
            marginTop: 22,
          }}
        >
          <aside
            className="hotel-filters"
            style={{
              background: T.surface,
              border: `1px solid ${T.hairline}`,
              borderRadius: 15,
              padding: 18,
              height: "fit-content",
            }}
          >
            <h3
              style={{
                margin: "0 0 16px",
                color: T.text,
                font: "700 15px Alexandria",
              }}
            >
              {rtl ? "تصفية النتائج" : "Filter results"}
            </h3>
            <label
              style={{
                display: "flex",
                gap: 9,
                color: T.text,
                font: "600 12px Alexandria",
                padding: "8px 0",
              }}
            >
              <input
                type="checkbox"
                checked={refundable}
                onChange={(e) => setRefundable(e.target.checked)}
              />
              {rtl ? "إلغاء مجاني/قابل للاسترداد" : "Refundable rates"}
            </label>
            <div
              style={{
                marginTop: 14,
                color: T.textMuted,
                font: "600 11px Alexandria",
              }}
            >
              {rtl ? "تصنيف الفندق" : "Star rating"}
            </div>
            {[5, 4, 3, 0].map((n) => (
              <button
                key={n}
                onClick={() => setStars(n)}
                style={{
                  display: "block",
                  width: "100%",
                  textAlign: "start",
                  padding: "9px 10px",
                  marginTop: 6,
                  border: `1px solid ${stars === n ? T.primary : T.hairline}`,
                  borderRadius: 9,
                  background: stars === n ? T.camelMist : "transparent",
                  color: T.text,
                  font: "600 12px Alexandria",
                }}
              >
                {n
                  ? `${"★".repeat(n)} ${rtl ? "فأعلى" : "& up"}`
                  : rtl
                    ? "الكل"
                    : "All"}
              </button>
            ))}
            <div style={{ marginTop: 18, color: T.textMuted, font: "600 11px Alexandria" }}>
              {rtl ? "الوجبات" : "Meals"}
            </div>
            <select
              value={mealPlan}
              onChange={(e) => setMealPlan(e.target.value)}
              style={{ width: "100%", marginTop: 7, padding: "10px", border: `1px solid ${T.hairline}`, borderRadius: 9, background: T.surface, color: T.text, font: "600 11px Alexandria" }}
            >
              <option value="all">{rtl ? "كل الخيارات" : "All options"}</option>
              <option value="breakfast">{rtl ? "يشمل الإفطار" : "Breakfast included"}</option>
              <option value="room">{rtl ? "إقامة فقط" : "Room only"}</option>
            </select>
            <div style={{ marginTop: 18, color: T.textMuted, font: "600 11px Alexandria" }}>
              {rtl ? "الحد الأعلى للسعر الإجمالي" : "Maximum total price"}
            </div>
            <select
              value={priceCap}
              onChange={(e) => setPriceCap(Number(e.target.value))}
              style={{ width: "100%", marginTop: 7, padding: "10px", border: `1px solid ${T.hairline}`, borderRadius: 9, background: T.surface, color: T.text, font: "600 11px Alexandria" }}
            >
              <option value="0">{rtl ? "بدون حد" : "No limit"}</option>
              {[500, 1000, 2000, 5000].map((price) => (
                <option key={price} value={price}>{rtl ? `حتى ${price.toLocaleString()} ر.س` : `Up to SAR ${price.toLocaleString()}`}</option>
              ))}
            </select>
          </aside>
          <section>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                gap: 12,
                marginBottom: 13,
              }}
            >
              <div>
                <h1
                  style={{
                    margin: 0,
                    color: T.text,
                    font: "700 25px Alexandria",
                  }}
                >
                  {hotelLocalized(data.query?.destination, rtl)} —{" "}
                  {hotels.length} {rtl ? "فندق متاح" : "properties available"}
                </h1>
                <small
                  style={{ color: T.textMuted, font: "500 11px Alexandria" }}
                >
                  {rtl
                    ? `${hotelFormatDate(data.query?.checkInDate, true)} — ${hotelFormatDate(data.query?.checkOutDate, true)} · ${nightCount} ${nightCount === 1 ? "ليلة" : "ليالٍ"} · ${guestCount} ضيف · ${roomCount} غرفة`
                    : `${hotelFormatDate(data.query?.checkInDate, false)} — ${hotelFormatDate(data.query?.checkOutDate, false)} · ${nightCount} nights · ${guestCount} guests · ${roomCount} rooms`}
                </small>
              </div>
              <select
                value={sort}
                onChange={(e) => setSort(e.target.value)}
                style={{
                  padding: "10px 12px",
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 10,
                  background: T.surface,
                  color: T.text,
                  font: "600 12px Alexandria",
                }}
              >
                <option value="recommended">
                  {rtl ? "موصى به" : "Recommended"}
                </option>
                <option value="price">
                  {rtl ? "الأقل سعراً" : "Lowest price"}
                </option>
                <option value="price-high">{rtl ? "الأعلى سعراً" : "Highest price"}</option>
                <option value="stars">
                  {rtl ? "الأعلى تصنيفاً" : "Highest stars"}
                </option>
                <option value="smart">{rtl ? "الأنسب لرحلتي" : "Best match"}</option>
              </select>
            </div>
            {loading && (
              <p style={{ color: T.primary }}>
                {rtl ? "جارٍ التحديث…" : "Updating…"}
              </p>
            )}
            <div style={{ display: "grid", gap: 14 }}>
              {hotels.map((h, i) => {
                const best = hotelBestRoom(h),
                  total = Number(best?.totalPrice ?? best?.price ?? 0),
                  perNight = total / nightCount,
                  gallery = hotelImages(h),
                  imageKey = String(h.hotelCode || i),
                  imageIndex = Math.min(activeImages[imageKey] || 0, Math.max(0, gallery.length - 1)),
                  reviewScore = Number(h.reviewScore || h.rating || 0),
                  reviewCount = Number(h.reviewCount || h.reviewsCount || 0);
                return (
                  <article
                    className="hotel-result-card"
                    key={h.hotelCode || i}
                    style={{
                      display: "grid",
                      gridTemplateColumns: "220px minmax(0,1fr) 190px",
                      background: T.surface,
                      border: `1px solid ${T.hairline}`,
                      borderRadius: 16,
                      overflow: "hidden",
                    }}
                  >
                    <div
                      className="hotel-card-gallery"
                      style={{ minHeight: 190, background: T.camelMist }}
                      onTouchStart={(e) => { swipeStart.current[imageKey] = e.touches[0].clientX; }}
                      onTouchEnd={(e) => {
                        const delta = e.changedTouches[0].clientX - (swipeStart.current[imageKey] || 0);
                        if (gallery.length > 1 && Math.abs(delta) > 40) {
                          const next = (imageIndex + (delta < 0 ? 1 : -1) + gallery.length) % gallery.length;
                          setActiveImages((v) => ({ ...v, [imageKey]: next }));
                        }
                      }}
                    >
                      {gallery[imageIndex] ? (
                        <img
                          src={gallery[imageIndex]}
                          alt={hotelName(h, rtl)}
                          style={{
                            width: "100%",
                            height: "100%",
                            objectFit: "cover",
                          }}
                        />
                      ) : (
                        <div
                          style={{
                            height: "100%",
                            display: "grid",
                            placeItems: "center",
                            color: T.primary,
                            font: "700 13px Alexandria",
                          }}
                        >
                          {rtl ? "صورة الفندق" : "Hotel image"}
                        </div>
                      )}
                      {gallery.length > 1 && <>
                        <button type="button" aria-label={rtl ? "الصورة السابقة" : "Previous image"} className="hotel-gallery-prev" onClick={(e) => { e.stopPropagation(); setActiveImages((v) => ({ ...v, [imageKey]: (imageIndex - 1 + gallery.length) % gallery.length })); }}>‹</button>
                        <button type="button" aria-label={rtl ? "الصورة التالية" : "Next image"} className="hotel-gallery-next" onClick={(e) => { e.stopPropagation(); setActiveImages((v) => ({ ...v, [imageKey]: (imageIndex + 1) % gallery.length })); }}>›</button>
                        <span className="hotel-gallery-dots">{gallery.map((_, n) => <i key={n} className={n === imageIndex ? "is-active" : ""} />)}</span>
                      </>}
                    </div>
                    <div style={{ padding: 18 }}>
                      <div style={{ color: T.camel, fontSize: 14 }}>
                        {"★".repeat(
                          Math.max(0, Math.min(5, Number(h.starRating) || 0)),
                        )}
                      </div>
                      <h2
                        style={{
                          margin: "5px 0",
                          color: T.text,
                          font: "700 18px Alexandria",
                        }}
                      >
                        {hotelName(h, rtl)}
                      </h2>
                      <div className="hotel-rating-line">
                        <span>{rtl ? "فندق" : "Hotel"} · {"★".repeat(Math.max(0, Math.min(5, Number(h.starRating) || 0)))}</span>
                        {reviewScore > 0 ? <><b>{reviewScore.toFixed(1)}</b><span>{rtl ? `${reviewCount ? `${reviewCount} تقييم` : "تقييم عملاء"}` : `${reviewCount || "Guest"} reviews`}</span></> : <span>{rtl ? "جديد على ضيوف" : "New on Duyuf"}</span>}
                      </div>
                      <p
                        style={{
                          margin: "5px 0",
                          color: T.textMuted,
                          font: "500 12px/1.6 Alexandria",
                        }}
                      >
                        {hotelLocalized(h.address || h.city, rtl)}
                      </p>
                      <div
                        style={{
                          display: "flex",
                          gap: 6,
                          flexWrap: "wrap",
                          marginTop: 12,
                        }}
                      >
                        {hotelFacilityItems(h.amenities).slice(0, 4).map((a) => (
                          <span
                            key={a}
                            style={{
                              padding: "5px 8px",
                              borderRadius: 99,
                              background: T.bg,
                              color: T.textMuted,
                              font: "500 10px Alexandria",
                            }}
                          >
                            {hotelLocalized(a, rtl)}
                          </span>
                        ))}
                      </div>
                      {best && (
                        <p
                          style={{
                            margin: "14px 0 0",
                            color: best.isRefundable ? "#238753" : T.textMuted,
                            font: "600 11px Alexandria",
                          }}
                        >
                          {best.isRefundable
                            ? rtl
                              ? "✓ خيار قابل للاسترداد"
                              : "✓ Refundable option"
                            : rtl
                              ? "غير قابل للاسترداد"
                              : "Non-refundable"}{" "}
                          · {hotelBoard(best.boardType, rtl)}
                        </p>
                      )}
                    </div>
                    <div
                      style={{
                        padding: 18,
                        borderInlineStart: `1px solid ${T.hairline}`,
                        display: "flex",
                        flexDirection: "column",
                        justifyContent: "flex-end",
                        textAlign: "end",
                      }}
                    >
                      <small
                        style={{
                          color: T.textMuted,
                          font: "500 10px Alexandria",
                        }}
                      >
                        {rtl ? "السعر الإجمالي من" : "Total from"}
                      </small>
                      <strong
                        style={{ color: T.text, font: "700 22px Alexandria" }}
                      >
                        {money(total)}{" "}
                        <small style={{ fontSize: 11 }}>
                          {currencyLabel}
                        </small>
                      </strong>
                      {best && (
                        <small style={{ marginTop: 4, color: T.textMuted, font: "500 9px Alexandria" }}>
                          {rtl
                            ? `${money(perNight)} ${currencyLabel} لليلة · ${nightCount} ${nightCount === 1 ? "ليلة" : "ليالٍ"}`
                            : `${currencyLabel} ${money(perNight)} per night · ${nightCount} nights`}
                        </small>
                      )}
                      <small style={{ marginTop: 3, color: T.textMuted, font: "500 8px Alexandria" }}>
                        {rtl ? `الإجمالي لـ ${nightCount} ${nightCount === 1 ? "ليلة" : "ليالٍ"} · شامل الضرائب والرسوم المعروضة` : `Total for ${nightCount} nights · displayed taxes and fees included`}
                      </small>
                      <button
                        onClick={() => open(h)}
                        style={{
                          marginTop: 12,
                          minHeight: 44,
                          border: 0,
                          borderRadius: 10,
                          background: T.primary,
                          color: "#fff",
                          font: "700 12px Alexandria",
                        }}
                      >
                        {rtl ? "عرض الغرف" : "See rooms"}
                      </button>
                    </div>
                  </article>
                );
              })}
              {!hotels.length && !loading && (
                <div
                  style={{
                    padding: 40,
                    textAlign: "center",
                    background: T.surface,
                    borderRadius: 16,
                    color: T.textMuted,
                  }}
                >
                  {rtl
                    ? "لا توجد نتائج مطابقة. غيّر التاريخ أو الفلاتر."
                    : "No matching stays. Change dates or filters."}
                </div>
              )}
            </div>
          </section>
        </div>
      </div>
      {sheet && <div className="hotel-sheet-backdrop" onClick={() => setSheet(null)}>
        <section className="hotel-bottom-sheet" onClick={(e) => e.stopPropagation()}>
          <div className="hotel-sheet-handle" />
          <button type="button" className="hotel-sheet-close" onClick={() => setSheet(null)}>×</button>
          {sheet === "search" && <>
            <h2>{rtl ? "تعديل البحث" : "Edit search"}</h2>
            <HotelSearchForm compact theme={T} lang={lang} initial={data.query} onSearch={async (query, hotelIds) => { await search(query, hotelIds); setSheet(null); }} />
          </>}
          {sheet === "currency" && <>
            <h2>{rtl ? "اختر العملة" : "Choose currency"}</h2>
            <div className="hotel-sheet-options">{["SAR", "USD", "AED"].map((code) => <button type="button" key={code} className={displayCurrency === code ? "is-active" : ""} onClick={() => { setDisplayCurrency(code); setSheet(null); }}>{code}</button>)}</div>
          </>}
          {sheet === "sort" && <>
            <h2>{rtl ? "ترتيب النتائج" : "Sort results"}</h2>
            <div className="hotel-sheet-options">{[["recommended", rtl ? "الأكثر شعبية" : "Most popular"], ["smart", rtl ? "الأنسب لرحلتي" : "Best match"], ["price", rtl ? "السعر: الأقل أولاً" : "Lowest price"], ["price-high", rtl ? "السعر: الأعلى أولاً" : "Highest price"], ["stars", rtl ? "التصنيف الأعلى" : "Highest rated"]].map(([key,label]) => <button type="button" key={key} className={sort === key ? "is-active" : ""} onClick={() => { setSort(key); setSheet(null); }}>{label}</button>)}</div>
          </>}
          {sheet === "filters" && <>
            <h2>{rtl ? "تصفية البحث" : "Filter results"}</h2>
            <label className="hotel-sheet-check"><input type="checkbox" checked={refundable} onChange={(e) => setRefundable(e.target.checked)} /> {rtl ? "إلغاء مجاني أو قابل للاسترداد" : "Refundable rates"}</label>
            <h3>{rtl ? "تصنيف الفندق" : "Hotel stars"}</h3>
            <div className="hotel-sheet-options hotel-sheet-options-inline">{[0,3,4,5].map((n) => <button type="button" key={n} className={stars === n ? "is-active" : ""} onClick={() => setStars(n)}>{n ? `${n}★+` : (rtl ? "الكل" : "All")}</button>)}</div>
            <button type="button" className="hotel-sheet-primary" onClick={() => setSheet(null)}>{rtl ? `عرض ${hotels.length} فندق` : `Show ${hotels.length} stays`}</button>
          </>}
        </section>
      </div>}
    </main>
  );
}

function cancellationText(room, rtl, currency = "SAR") {
  if (!room.isRefundable) return rtl ? "غير قابل للاسترداد" : "Non-refundable";
  const rule = room.cancellationPolicy?.rules?.[0];
  if (!rule)
    return rtl
      ? "قابل للاسترداد حسب شروط الفندق"
      : "Refundable subject to hotel terms";
  const when = hotelFormatDate(rule.fromDate, rtl),
    amount = Number(rule.chargeAmount || 0),
    amountText = amount > 0
      ? `${amount.toLocaleString(rtl ? "ar-SA" : "en-US", { maximumFractionDigits: 2 })} ${hotelCurrency(currency, rtl)}`
      : "";
  if (when && amountText)
    return rtl
      ? `إلغاء مجاني حتى ${when}، وبعدها قد تُطبّق رسوم بقيمة ${amountText}.`
      : `Free cancellation until ${when}; after that, a charge of ${amountText} may apply.`;
  if (when)
    return rtl
      ? `إلغاء مجاني حتى ${when}، وتُطبّق شروط الفندق بعد ذلك.`
      : `Free cancellation until ${when}; hotel terms apply after that.`;
  return rtl ? "قابل للاسترداد حسب شروط الفندق" : "Refundable subject to hotel terms";
}

function WebHotelDetailsPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    ctx = useWeb(),
    data = ctx.hotel || {},
    h = data.selectedHotel,
    [busy, setBusy] = React.useState(false),
    [error, setError] = React.useState(""),
    [activeImage, setActiveImage] = React.useState(0),
    [galleryOpen, setGalleryOpen] = React.useState(false),
    [showAmenities, setShowAmenities] = React.useState(false),
    detailSwipeStart = React.useRef(0);
  if (!h) return <WebHotelsSearchPage theme={T} lang={lang} />;
  const choose = async (room) => {
    setBusy(true);
    setError("");
    try {
      const q = data.query,
        body = await hotelApi("check-availability", {
          token: room.token,
          checkInDate: q.checkInDate,
          checkOutDate: q.checkOutDate,
          nationality: q.nationality,
          residency: q.residency,
          rooms: q.rooms,
        });
      const option = body.roomOptions?.[0];
      if (!option) throw new Error("no_room");
      ctx.setHotel({
        ...data,
        selectedRoom: room,
        availability: option,
        currency: body.currency || data.currency,
      });
      ctx.setPage("hotel-checkout");
    } catch (_) {
      setError(
        rtl
          ? "هذا السعر لم يعد متاحاً. ارجع للنتائج واختر خياراً آخر."
          : "This rate is no longer available. Please choose another option.",
      );
    } finally {
      setBusy(false);
    }
  };
  const images = hotelImages(h),
    nightCount = hotelNightCount(data.query),
    guestCount = hotelGuestCount(data.query),
    roomCount = Math.max(1, (data.query?.rooms || []).length);
  const facilityItems = hotelFacilityItems(h.amenities);
  const spokenLanguages = hotelSpokenLanguages(h.amenities, rtl);
  return (
    <main
      style={{ minHeight: 720, background: T.bg, padding: "24px 16px 70px" }}
    >
      <div style={{ maxWidth: 1120, margin: "0 auto" }}>
        <HotelStepBar theme={T} lang={lang} active={2} />
        <button
          onClick={() => ctx.setPage("hotel-results")}
          style={{
            border: 0,
            background: "transparent",
            color: T.primary,
            font: "700 12px Alexandria",
          }}
        >
          {rtl ? "→" : "←"} {rtl ? "العودة للنتائج" : "Back to results"}
        </button>
        <div className="hotel-gallery"
          onTouchStart={(e)=>{detailSwipeStart.current=e.touches[0].clientX}}
          onTouchEnd={(e)=>{const delta=e.changedTouches[0].clientX-detailSwipeStart.current;if(images.length>1&&Math.abs(delta)>40)setActiveImage(i=>(i+(delta<0?1:-1)+images.length)%images.length)}}>
          <button type="button" className="hotel-gallery-main" onClick={()=>images.length&&setGalleryOpen(true)}>
            {images[activeImage]
              ? <img src={images[activeImage]} alt={`${hotelName(h,rtl)} ${activeImage+1}`} />
              : <span className="hotel-gallery-empty">{rtl?"لا توجد صور متاحة للفندق":"No hotel photos available"}</span>}
            {images.length>0&&<span className="hotel-gallery-count">{activeImage+1} / {images.length}</span>}
          </button>
          {images.length>1&&<>
            <button type="button" className="hotel-detail-gallery-nav is-prev" aria-label={rtl?"الصورة السابقة":"Previous image"} onClick={()=>setActiveImage(i=>(i-1+images.length)%images.length)}>‹</button>
            <button type="button" className="hotel-detail-gallery-nav is-next" aria-label={rtl?"الصورة التالية":"Next image"} onClick={()=>setActiveImage(i=>(i+1)%images.length)}>›</button>
            <span className="hotel-detail-gallery-dots">{images.slice(0,8).map((_,i)=><i key={i} className={activeImage===i?"is-active":""}/>)}</span>
          </>}
        </div>
        {galleryOpen && images.length>0 && <div className="hotel-lightbox" role="dialog" aria-modal="true" onClick={()=>setGalleryOpen(false)}>
          <button type="button" className="hotel-lightbox-close" onClick={()=>setGalleryOpen(false)}>×</button>
          <button type="button" aria-label={rtl?"الصورة السابقة":"Previous image"} onClick={e=>{e.stopPropagation();setActiveImage(i=>(i-1+images.length)%images.length)}}>‹</button>
          <img onClick={e=>e.stopPropagation()} src={images[activeImage]} alt={`${hotelName(h,rtl)} ${activeImage+1}`} />
          <button type="button" aria-label={rtl?"الصورة التالية":"Next image"} onClick={e=>{e.stopPropagation();setActiveImage(i=>(i+1)%images.length)}}>›</button>
        </div>}
        <section style={{ padding: "24px 0" }}>
          <div style={{ color: T.camel }}>
            {"★".repeat(Number(h.starRating) || 0)}
          </div>
          <h1
            style={{
              margin: "5px 0",
              color: T.text,
              font: "700 30px Alexandria",
            }}
          >
            {hotelName(h, rtl)}
          </h1>
          <p style={{ color: T.textMuted, font: "500 13px/1.7 Alexandria" }}>
            {hotelLocalized(h.address, rtl)} · {hotelLocalized(h.city, rtl)}
          </p>
          <div className="hotel-stay-summary" style={{ display: "grid", gridTemplateColumns: "repeat(3,minmax(0,1fr))", gap: 10, maxWidth: 850, margin: "16px 0 24px" }}>
            {[
              [rtl ? "فترة الإقامة" : "Stay dates", `${hotelFormatDate(data.query?.checkInDate, rtl)} — ${hotelFormatDate(data.query?.checkOutDate, rtl)}`],
              [rtl ? "المدة" : "Duration", rtl ? `${nightCount} ${nightCount === 1 ? "ليلة" : "ليالٍ"}` : `${nightCount} nights`],
              [rtl ? "الضيوف والغرف" : "Guests and rooms", rtl ? `${guestCount} ضيف · ${roomCount} غرفة` : `${guestCount} guests · ${roomCount} rooms`],
            ].map(([label, value]) => (
              <div key={label} style={{ padding: 13, borderRadius: 12, background: T.surface, border: `1px solid ${T.hairline}` }}>
                <small style={{ display: "block", color: T.textMuted, font: "500 9px Alexandria" }}>{label}</small>
                <strong style={{ display: "block", marginTop: 5, color: T.text, font: "700 11px Alexandria" }}>{value}</strong>
              </div>
            ))}
          </div>
          <div
            style={{
              maxWidth: 850,
              color: T.text,
              font: "400 13px/1.9 Alexandria",
            }}
          >
            {rtl ? (
              <>
                <h2 style={{ font: "700 18px Alexandria" }}>نبذة عن الفندق</h2>
                <p>
                  يوفر {h.hotelName} خيارات إقامة في{" "}
                  {hotelLocalized(h.city || data.query?.destination, true)}.
                  اختر الغرفة المناسبة وراجع الوجبات وسياسة الإلغاء والسعر
                  النهائي قبل إتمام الحجز.
                </p>
              </>
            ) : (
              <>
                <h2 style={{ font: "700 18px Alexandria" }}>About this hotel</h2>
                <p>
                  {h.hotelName} offers accommodation in {hotelLocalized(h.city || data.query?.destination, false)}.
                  Choose a suitable room and review the meal plan, cancellation policy and final price before booking.
                </p>
              </>
            )}
          </div>
          <h2 style={{font:"700 19px Alexandria",color:T.text,margin:"28px 0 14px"}}>{rtl ? "أبرز مرافق الفندق" : "Popular facilities"}</h2>
          <div className="hotel-amenities-grid">
            {facilityItems.slice(0, showAmenities ? 60 : 12).map((a) => {
              return <div key={a} className="hotel-amenity-card"><span aria-hidden="true">{hotelAmenityIcon(a)}</span><span>{hotelLocalized(a,rtl)}</span></div>;
            })}
          </div>
          {facilityItems.length > 12 && (
            <button type="button" onClick={() => setShowAmenities((value) => !value)} style={{ marginTop: 14, minHeight: 42, padding: "0 18px", borderRadius: 10, border: `1px solid ${T.primary}`, background: T.surface, color: T.primary, font: "700 11px Alexandria" }}>
              {showAmenities ? (rtl ? "عرض المرافق الأساسية" : "Show key facilities") : (rtl ? "عرض جميع المرافق" : "Show all facilities")}
            </button>
          )}
          {spokenLanguages.length > 0 && <>
            <h2 style={{font:"700 19px Alexandria",color:T.text,margin:"28px 0 14px"}}>{rtl ? "اللغات التي يتحدث بها الموظفون" : "Languages spoken by staff"}</h2>
            <div className="hotel-language-list">
              {spokenLanguages.map((language) => <span key={language}>{language}</span>)}
            </div>
          </>}
        </section>
        <h2 style={{ color: T.text, font: "700 21px Alexandria" }}>
          {rtl ? "اختر الغرفة والسعر" : "Choose a room and rate"}
        </h2>
        {error && (
          <p style={{ color: "#b42318", font: "600 12px Alexandria" }}>
            {error}
          </p>
        )}
        <div style={{ display: "grid", gap: 11 }}>
          {(h.rooms || []).map((r, i) => {
            const total = Number(r.totalPrice ?? r.price ?? 0), perNight = total / nightCount;
            return (
            <article
              key={`${r.token}-${i}`}
              className="hotel-room-rate-card"
              style={{
                display: "grid",
                gridTemplateColumns: "minmax(0,1fr) 220px",
                gap: 16,
                padding: 18,
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                borderRadius: 14,
              }}
            >
              <div>
                <h3
                  style={{
                    margin: "0 0 7px",
                    color: T.text,
                    font: "700 16px Alexandria",
                  }}
                >
                  {hotelLocalized(r.roomName, rtl)}
                </h3>
                <p
                  style={{
                    margin: "4px 0",
                    color: T.textMuted,
                    font: "500 12px Alexandria",
                  }}
                >
                  {hotelBoard(r.boardType, rtl)}
                </p>
                <p
                  style={{
                    margin: "8px 0",
                    color: r.isRefundable ? "#238753" : "#b42318",
                    font: "600 11px/1.6 Alexandria",
                  }}
                >
                  {cancellationText(r, rtl, data.currency)}
                </p>
              </div>
              <div className="hotel-room-rate-price" style={{ textAlign: "end" }}>
                <strong
                  style={{
                    display: "block",
                    color: T.text,
                    font: "700 21px Alexandria",
                  }}
                >
                  {total.toLocaleString(undefined, { maximumFractionDigits: 2 })}{" "}
                  <small style={{ fontSize: 11 }}>
                    {hotelCurrency(data.currency, rtl)}
                  </small>
                </strong>
                <small style={{ display: "block", marginTop: 4, color: T.textMuted, font: "500 9px Alexandria" }}>
                  {rtl
                    ? `${perNight.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${hotelCurrency(data.currency, rtl)} لليلة · الإجمالي لـ ${nightCount} ${nightCount === 1 ? "ليلة" : "ليالٍ"}`
                    : `${hotelCurrency(data.currency, rtl)} ${perNight.toLocaleString(undefined, { maximumFractionDigits: 2 })} per night · total for ${nightCount} nights`}
                </small>
                <button
                  disabled={busy}
                  onClick={() => choose(r)}
                  style={{
                    minHeight: 43,
                    padding: "0 20px",
                    marginTop: 12,
                    border: 0,
                    borderRadius: 10,
                    background: T.primary,
                    color: "#fff",
                    font: "700 12px Alexandria",
                  }}
                >
                  {rtl ? "اختيار" : "Select"}
                </button>
              </div>
            </article>
          );})}
        </div>
      </div>
    </main>
  );
}

function WebHotelCheckoutPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    ctx = useWeb(),
    data = ctx.hotel || {},
    h = data.selectedHotel,
    a = data.availability,
    [busy, setBusy] = React.useState(false),
    [result, setResult] = React.useState(null),
    [error, setError] = React.useState(""),
    [otpStage, setOtpStage] = React.useState("details"),
    [otpCode, setOtpCode] = React.useState(""),
    [otpHint, setOtpHint] = React.useState(""),
    [pendingBooking, setPendingBooking] = React.useState(null);
  const count =
    (data.query?.rooms || []).reduce(
      (n, r) => n + r.adults + (r.childrenAges?.length || 0),
      0,
    ) || 1;
  const [guests, setGuests] = React.useState(
    Array.from({ length: count }, (_, i) => ({
      title: i ? "Mrs" : "Mr",
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
      nationality: data.query?.nationality || "SA",
      residency: data.query?.residency || "SA",
      isLeadGuest: i === 0,
    })),
  );
  if (!h || !a) return <WebHotelsSearchPage theme={T} lang={lang} />;
  const change = (i, k, v) =>
    setGuests((gs) => gs.map((g, x) => (x === i ? { ...g, [k]: v } : g)));
  const normalizePhone = (value) => {
    let digits = String(value || "").replace(/\D/g, "");
    if (digits.startsWith("00966")) digits = digits.slice(2);
    if (digits.startsWith("966")) return `+${digits}`;
    if (digits.startsWith("0")) digits = digits.slice(1);
    return `+966${digits}`;
  };
  const finalizeBooking = async (code) => {
    if (!pendingBooking || busy) return;
    setBusy(true);
    setError("");
    try {
      const credential = await window.duyufHotelConfirmation.confirm(code);
      const firebaseIdToken = await credential.user.getIdToken();
      const body = await hotelApi("book", {
        ...pendingBooking,
        firebaseIdToken,
        confirmation: {
          email: guests[0].email.trim(),
          phone: normalizePhone(guests[0].phone),
          hotelName: h.hotelName,
          roomName: hotelLocalized(a.roomName, false),
          checkInDate: data.query.checkInDate,
          checkOutDate: data.query.checkOutDate,
          totalPrice: Number(a.price),
          currency: data.currency || "SAR",
          leadGuest: `${guests[0].firstName} ${guests[0].lastName}`.trim(),
        },
      });
      try {
        const saved = JSON.parse(localStorage.getItem("duyuf_hotel_bookings") || "[]");
        saved.unshift({
          reference: body.bookingReference || body.clientReference || pendingBooking.clientReference,
          hotelName: h.hotelName,
          checkInDate: data.query.checkInDate,
          checkOutDate: data.query.checkOutDate,
          voucherUrl: body.confirmation?.voucherUrl || "",
          status: "confirmed",
          createdAt: new Date().toISOString(),
        });
        localStorage.setItem("duyuf_hotel_bookings", JSON.stringify(saved.slice(0, 20)));
      } catch (_) {}
      setResult(body);
    } catch (err) {
      setError(
        rtl
          ? "رمز التحقق غير صحيح أو انتهت صلاحيته. اطلب رمزاً جديداً وحاول مرة أخرى."
          : "The verification code is invalid or expired. Request a new code and try again.",
      );
    } finally {
      setBusy(false);
    }
  };
  React.useEffect(() => {
    if (otpStage === "otp" && /^\d{6}$/.test(otpCode) && !busy)
      finalizeBooking(otpCode);
  }, [otpCode, otpStage]);
  const submit = async (e) => {
    e.preventDefault();
    setError("");
    if (guests.some((g) => !g.firstName.trim() || !g.lastName.trim()))
      return setError(
        rtl
          ? "أدخل الاسم الأول والأخير لكل ضيف."
          : "Enter first and last name for every guest.",
      );
    const leadGuest = guests.find((guest) => guest.isLeadGuest) || guests[0];
    const leadEmail = String(leadGuest?.email || "").trim();
    const leadPhone = String(leadGuest?.phone || "").replace(/\D/g, "");
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(leadEmail))
      return setError(
        rtl
          ? "أدخل بريداً إلكترونياً صحيحاً للضيف الرئيسي."
          : "Enter a valid email for the lead guest.",
      );
    if (leadPhone.length < 8)
      return setError(
        rtl
          ? "أدخل رقم جوال صحيحاً للضيف الرئيسي."
          : "Enter a valid phone number for the lead guest.",
      );
    setBusy(true);
    try {
      const ref = `DUY-HOTEL-${Date.now().toString(36).toUpperCase()}-${crypto.randomUUID().slice(0, 8).toUpperCase()}`;
      const payload = {
        checkInDate: data.query.checkInDate,
        checkOutDate: data.query.checkOutDate,
        clientReference: ref,
        rooms: [
          {
            token: a.token,
            totalPrice: Number(a.price),
            adults: data.query.rooms[0].adults,
            childrenAges: data.query.rooms[0].childrenAges || [],
            guests,
          },
        ],
      };
      if (!window.firebase?.auth)
        throw new Error("Firebase Auth is unavailable");
      if (window.duyufHotelRecaptcha) {
        try { window.duyufHotelRecaptcha.clear(); } catch (_) {}
      }
      window.duyufHotelRecaptcha = new firebase.auth.RecaptchaVerifier(
        "duyuf-hotel-recaptcha",
        { size: "invisible" },
      );
      window.duyufHotelConfirmation = await firebase
        .auth()
        .signInWithPhoneNumber(normalizePhone(leadGuest.phone), window.duyufHotelRecaptcha);
      setPendingBooking(payload);
      setOtpStage("otp");
      setOtpHint(
        rtl
          ? `أرسلنا رمزاً من 6 أرقام إلى ${normalizePhone(leadGuest.phone)}`
          : `We sent a 6-digit code to ${normalizePhone(leadGuest.phone)}`,
      );
    } catch (err) {
      setError(
        rtl
          ? "تعذر إرسال رمز التحقق. تأكد من رقم الجوال وإعدادات Firebase ثم حاول مرة أخرى."
          : "Could not send the verification code. Check the phone number and try again.",
      );
    } finally {
      setBusy(false);
    }
  };
  if (result)
    return (
      <main
        style={{
          minHeight: 650,
          display: "grid",
          placeItems: "center",
          background: T.bg,
          padding: 20,
        }}
      >
        <section
          style={{
            maxWidth: 620,
            padding: 32,
            textAlign: "center",
            background: T.surface,
            border: `1px solid ${T.hairline}`,
            borderRadius: 20,
          }}
        >
          <div style={{ fontSize: 44, color: "#238753" }}>✓</div>
          <h1 style={{ color: T.text, font: "700 26px Alexandria" }}>
            {rtl ? "تم تأكيد الحجز" : "Booking confirmed"}
          </h1>
          <p style={{ color: T.textMuted, font: "500 13px/1.8 Alexandria" }}>
            {h.hotelName}
            <br />
            {hotelFormatDate(data.query.checkInDate, rtl)} — {hotelFormatDate(data.query.checkOutDate, rtl)}
          </p>
          <div
            style={{
              padding: 13,
              borderRadius: 11,
              background: T.camelMist,
              color: T.text,
              font: "700 14px Alexandria",
            }}
          >
            {rtl ? "رقم الحجز" : "Booking reference"}: {result.bookingReference || result.clientReference}
          </div>
          <p style={{ color: T.textMuted, font: "500 12px/1.8 Alexandria" }}>
            {result.confirmation?.emailSent
              ? rtl ? "أرسلنا تأكيد الحجز وملف PDF إلى بريدك الإلكتروني." : "The booking confirmation and PDF voucher were emailed to you."
              : rtl ? "تم الحجز، ويمكنك تنزيل تأكيد الحجز من الزر أدناه." : "The booking is confirmed. Download the voucher below."}
          </p>
          {result.confirmation?.voucherUrl && (
            <a href={result.confirmation.voucherUrl} target="_blank" rel="noreferrer" style={{ display: "inline-block", marginTop: 10, padding: "12px 22px", borderRadius: 10, border: `1px solid ${T.primary}`, color: T.primary, textDecoration: "none", font: "700 13px Alexandria" }}>
              {rtl ? "تنزيل تأكيد الحجز PDF" : "Download PDF voucher"}
            </a>
          )}
          <button
            onClick={() => ctx.setPage("home")}
            style={{
              marginTop: 18,
              padding: "12px 22px",
              border: 0,
              borderRadius: 10,
              background: T.primary,
              color: "#fff",
              font: "700 13px Alexandria",
            }}
          >
            {rtl ? "العودة للرئيسية" : "Back home"}
          </button>
        </section>
      </main>
    );
  const inputStyle = {
    width: "100%",
    minHeight: 47,
    padding: "10px 11px",
    border: `1px solid ${T.hairlineStrong}`,
    borderRadius: 10,
    background: T.bg,
    color: T.text,
    font: "500 13px Alexandria",
  };
  if (otpStage === "otp")
    return (
      <main style={{ minHeight: 650, display: "grid", placeItems: "center", background: T.bg, padding: 20 }}>
        <section style={{ width: "min(100%,520px)", padding: 28, textAlign: "center", background: T.surface, border: `1px solid ${T.hairline}`, borderRadius: 20 }}>
          <div style={{ fontSize: 34 }}>🔐</div>
          <h1 style={{ color: T.text, font: "700 25px Alexandria" }}>{rtl ? "تحقق من رقم الجوال" : "Verify your phone"}</h1>
          <p style={{ color: T.textMuted, font: "500 12px/1.8 Alexandria" }}>{otpHint}</p>
          <input autoFocus inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={otpCode} onChange={(e) => setOtpCode(e.target.value.replace(/\D/g, "").slice(0, 6))} placeholder="••••••" style={{ ...inputStyle, direction: "ltr", textAlign: "center", letterSpacing: 10, fontSize: 24 }} />
          <p style={{ color: T.textMuted, font: "500 11px/1.7 Alexandria" }}>{rtl ? "سيتم التحقق وتأكيد الحجز تلقائياً عند إدخال الرقم السادس." : "Verification and booking will start automatically after the sixth digit."}</p>
          {busy && <p style={{ color: T.primary, font: "700 12px Alexandria" }}>{rtl ? "جارٍ تأكيد الحجز التجريبي…" : "Confirming your test booking…"}</p>}
          {error && <p role="alert" style={{ color: "#b42318", font: "600 12px/1.7 Alexandria" }}>{error}</p>}
          <button type="button" onClick={() => { setOtpStage("details"); setOtpCode(""); setError(""); }} style={{ marginTop: 12, padding: "10px 18px", border: `1px solid ${T.hairline}`, borderRadius: 10, background: T.surface, color: T.text, font: "700 12px Alexandria" }}>{rtl ? "تعديل البيانات" : "Edit details"}</button>
        </section>
      </main>
    );
  return (
    <main
      style={{ minHeight: 720, background: T.bg, padding: "24px 16px 70px" }}
    >
      <form onSubmit={submit} style={{ maxWidth: 1050, margin: "0 auto" }}>
        <HotelStepBar theme={T} lang={lang} active={3} />
        <div
          className="hotel-checkout-layout"
          style={{
            display: "grid",
            gridTemplateColumns: "minmax(0,1fr) 330px",
            gap: 22,
            alignItems: "start",
          }}
        >
          <section>
            <h1 style={{ color: T.text, font: "700 26px Alexandria" }}>
              {rtl ? "بيانات الضيوف" : "Guest details"}
            </h1>
            <p style={{ color: T.textMuted, font: "500 12px Alexandria" }}>
              {rtl
                ? "أدخل الأسماء كما تظهر في الهوية أو جواز السفر."
                : "Use names exactly as shown on the ID or passport."}
            </p>
            {guests.map((g, i) => (
              <div
                key={i}
                style={{
                  padding: 18,
                  marginBottom: 12,
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 14,
                }}
              >
                <h3
                  style={{
                    margin: "0 0 13px",
                    color: T.text,
                    font: "700 14px Alexandria",
                  }}
                >
                  {rtl ? "الضيف" : "Guest"} {i + 1}
                  {i === 0 ? ` · ${rtl ? "الرئيسي" : "Lead"}` : ""}
                </h3>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "100px 1fr 1fr",
                    gap: 9,
                  }}
                >
                  <select
                    value={g.title}
                    onChange={(e) => change(i, "title", e.target.value)}
                    style={inputStyle}
                  >
                    <option value="Mr">{rtl ? "السيد" : "Mr"}</option>
                    <option value="Mrs">{rtl ? "السيدة" : "Mrs"}</option>
                    <option value="Ms">{rtl ? "الآنسة" : "Ms"}</option>
                  </select>
                  <input
                    required
                    placeholder={rtl ? "الاسم الأول" : "First name"}
                    value={g.firstName}
                    onChange={(e) => change(i, "firstName", e.target.value)}
                    style={inputStyle}
                  />
                  <input
                    required
                    placeholder={rtl ? "اسم العائلة" : "Last name"}
                    value={g.lastName}
                    onChange={(e) => change(i, "lastName", e.target.value)}
                    style={inputStyle}
                  />
                </div>
                {i === 0 && (
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "1fr 1fr",
                      gap: 9,
                      marginTop: 9,
                    }}
                  >
                    <input
                      type="email"
                      placeholder={rtl ? "البريد الإلكتروني" : "Email"}
                      value={g.email}
                      onChange={(e) => change(i, "email", e.target.value)}
                      style={inputStyle}
                    />
                    <input
                      placeholder={rtl ? "رقم الجوال" : "Phone"}
                      value={g.phone}
                      onChange={(e) => change(i, "phone", e.target.value)}
                      style={inputStyle}
                    />
                  </div>
                )}
              </div>
            ))}
            {error && (
              <p
                role="alert"
                style={{ color: "#b42318", font: "600 12px/1.7 Alexandria" }}
              >
                {error}
              </p>
            )}
            <div id="duyuf-hotel-recaptcha" />
          </section>
          <aside
            style={{
              position: "sticky",
              top: 90,
              padding: 20,
              background: T.surface,
              border: `1px solid ${T.hairline}`,
              borderRadius: 16,
            }}
          >
            <h2
              style={{
                margin: "0 0 8px",
                color: T.text,
                font: "700 18px Alexandria",
              }}
            >
              {h.hotelName}
            </h2>
            <p style={{ color: T.textMuted, font: "500 11px/1.7 Alexandria" }}>
              {hotelFormatDate(data.query.checkInDate, rtl)} — {hotelFormatDate(data.query.checkOutDate, rtl)}
              <br />
              {hotelLocalized(a.roomName, rtl)} · {hotelBoard(a.boardType, rtl)}
            </p>
            <hr style={{ border: 0, borderTop: `1px solid ${T.hairline}` }} />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                color: T.text,
                font: "700 15px Alexandria",
              }}
            >
              <span>{rtl ? "الإجمالي" : "Total"}</span>
              <span>
                {Number(a.price).toLocaleString()}{" "}
                {hotelCurrency(data.currency, rtl)}
              </span>
            </div>
            {(a.messages || []).length > 0 &&
              (rtl ? (
                <details
                  style={{
                    margin: "12px 0",
                    padding: 10,
                    borderRadius: 8,
                    background: T.camelMist,
                    color: T.textMuted,
                    font: "500 10px/1.7 Alexandria",
                  }}
                >
                  <summary
                    style={{
                      cursor: "pointer",
                      fontWeight: 700,
                      color: T.text,
                    }}
                  >
                    شروط إضافية من الفندق
                  </summary>
                  <p>
                    لدى الفندق تعليمات خاصة بتسجيل الوصول أو وسائل الدفع. افتح
                    النص الأصلي أدناه واقرأه قبل الموافقة.
                  </p>
                  {a.messages.map((m, i) => (
                    <p
                      dir="ltr"
                      key={i}
                      style={{ textAlign: "left", fontFamily: "system-ui" }}
                    >
                      {m.messageFull || m.messageShort}
                    </p>
                  ))}
                </details>
              ) : (
                a.messages.map((m, i) => (
                  <p
                    key={i}
                    style={{
                      padding: 9,
                      borderRadius: 8,
                      background: T.camelMist,
                      color: T.textMuted,
                      font: "500 10px/1.6 Alexandria",
                    }}
                  >
                    {m.messageFull || m.messageShort}
                  </p>
                ))
              ))}
            <p style={{ color: T.textMuted, font: "500 10px/1.7 Alexandria" }}>
              {cancellationText(a, rtl, data.currency)}
            </p>
            <label
              style={{
                display: "flex",
                gap: 8,
                alignItems: "flex-start",
                color: T.text,
                font: "500 10px/1.6 Alexandria",
              }}
            >
              <input required type="checkbox" />
              {rtl
                ? "أوافق على شروط السعر وسياسة الإلغاء الموضحة."
                : "I accept the displayed rate terms and cancellation policy."}
            </label>
            <button
              disabled={busy}
              type="submit"
              style={{
                width: "100%",
                minHeight: 50,
                marginTop: 14,
                border: 0,
                borderRadius: 11,
                background: T.primary,
                color: "#fff",
                font: "700 13px Alexandria",
                opacity: busy ? 0.65 : 1,
              }}
            >
              {busy
                ? rtl
                  ? "جارٍ التأكيد…"
                  : "Confirming…"
                : rtl
                  ? "تأكيد الحجز"
                  : "Confirm booking"}
            </button>
          </aside>
        </div>
      </form>
    </main>
  );
}

Object.assign(window, {
  hotelApi,
  WebHotelsSearchPage,
  WebHotelResultsPage,
  WebHotelDetailsPage,
  WebHotelCheckoutPage,
});
