// Standalone web pages — browse, detail, become-provider, contact, sign-in
// All consume the WebContext (set by WebApp).

const WebContext = React.createContext(null);
const useWeb = () => React.useContext(WebContext);

// ─── Page header (used on subpages) ────────────────────────────────────
function WebPageHeader({ theme, lang, eyebrow, title, sub, tone = "camel" }) {
  const T = theme;
  const rtl = isRTL(lang);
  const tones = {
    camel: `linear-gradient(135deg, ${T.camel} 0%, ${T.camelDeep} 100%)`,
    ink: `linear-gradient(135deg, ${T.ink} 0%, ${T.inkSoft} 100%)`,
    brown: `linear-gradient(135deg, ${T.pastelBrown} 0%, ${T.camelDeep} 100%)`,
  };
  return (
    <div
      style={{
        position: "relative",
        padding: "50px 32px 60px",
        background: tones[tone],
        color: "#fff",
        overflow: "hidden",
      }}
    >
      <div style={{ position: "absolute", inset: 0, opacity: 0.12 }}>
        <DuyufPattern color="#fff" opacity={0.4} size={64} />
      </div>
      <PetalAccent
        size={300}
        color="#fff"
        opacity={0.08}
        rotate={20}
        style={{ position: "absolute", right: -80, top: -80 }}
      />
      <div style={{ position: "relative", maxWidth: 1180, margin: "0 auto" }}>
        {eyebrow && (
          <div
            style={{
              fontFamily: "Alexandria",
              fontSize: 11.5,
              fontWeight: 600,
              letterSpacing: "0.1em",
              textTransform: "uppercase",
              opacity: 0.85,
              marginBottom: 10,
            }}
          >
            {eyebrow}
          </div>
        )}
        <h1
          style={{
            margin: 0,
            fontFamily: "Alexandria",
            fontWeight: 700,
            fontSize: 40,
            lineHeight: 1.15,
            letterSpacing: "-0.02em",
            maxWidth: 720,
            textWrap: "pretty",
          }}
        >
          {title}
        </h1>
        {sub && (
          <p
            style={{
              margin: "12px 0 0",
              fontFamily: "Alexandria",
              fontSize: 15,
              opacity: 0.78,
              lineHeight: 1.55,
              maxWidth: 560,
            }}
          >
            {sub}
          </p>
        )}
      </div>
    </div>
  );
}

// ─── Browse / search results page ──────────────────────────────────────
function WebBrowsePage({ theme, lang }) {
  const T = theme;
  const l = L[lang];
  const rtl = isRTL(lang);
  const { setPage, setPkg, umrahSearch } = useWeb();
  const [filtersOpen, setFiltersOpen] = React.useState(false);

  const basePackages = [
    {
      id: "fairmont",
      hotel: rtl ? "فيرمونت ساعة مكة" : "Fairmont Makkah Clock Tower",
      dist: rtl ? "50م من الحرم" : "50m from Haram",
      stars: 5,
      nights: 7,
      price: 4899,
      was: 5499,
      seats: 4,
      board: rtl ? "إفطار+عشاء" : "B&D",
      tone: "dark",
      provider: rtl ? "الإيلاف الفاخرة" : "Elaf Premium",
      dates: rtl ? "16–25 رمضان" : "16–25 Ramadan",
    },
    {
      id: "swiss",
      hotel: rtl ? "سويس أوتيل برج الزمزم" : "Swissôtel Al Maqam",
      dist: rtl ? "120م من الحرم" : "120m from Haram",
      stars: 5,
      nights: 7,
      price: 3899,
      seats: 9,
      board: rtl ? "إفطار" : "Breakfast",
      tone: "camel",
      provider: rtl ? "الرحمة للحج" : "Al-Rahma",
      dates: rtl ? "1–8 شوال" : "1–8 Shawwal",
    },
    {
      id: "hilton",
      hotel: rtl ? "هيلتون مكة المكرمة" : "Hilton Suites Makkah",
      dist: rtl ? "200م من الحرم" : "200m from Haram",
      stars: 4,
      nights: 7,
      price: 2799,
      seats: 12,
      board: rtl ? "بدون" : "Room only",
      tone: "brown",
      provider: rtl ? "إيلاف ضيوف" : "Elaf Guests",
      dates: rtl ? "20 رمضان" : "20 Ramadan",
    },
    {
      id: "safwah",
      hotel: rtl ? "الصفوة رويال أوركيد" : "Al Safwah Royal Orchid",
      dist: rtl ? "320م" : "320m",
      stars: 4,
      nights: 6,
      price: 1199,
      seats: 9,
      board: rtl ? "إفطار" : "Breakfast",
      tone: "cream",
      provider: rtl ? "حجاج الجزيرة" : "Hujjaj Aljazeera",
      dates: rtl ? "8 ذو القعدة" : "8 Dhul Qadah",
    },
    {
      id: "fairmont2",
      hotel: rtl ? "فيرمونت — شوال" : "Fairmont — Shawwal",
      dist: "50m",
      stars: 5,
      nights: 10,
      price: 5499,
      seats: 2,
      board: rtl ? "إفطار+عشاء" : "B&D",
      tone: "dark",
      provider: rtl ? "الإيلاف الفاخرة" : "Elaf Premium",
      dates: rtl ? "12 شوال" : "12 Shawwal",
    },
    {
      id: "movenpick",
      hotel: rtl ? "موڤنبيك حجاج" : "Mövenpick Hajar",
      dist: "180m",
      stars: 5,
      nights: 10,
      price: 5290,
      seats: 7,
      board: rtl ? "إفطار" : "Breakfast",
      tone: "brown",
      provider: rtl ? "بوابة الكعبة" : "Kaaba Gate",
      dates: rtl ? "20 شوال" : "20 Shawwal",
    },
  ];
  const [approved, setApproved] = React.useState([]);
  React.useEffect(() => {
    fetch(`${window.DUYUF_API_URL}/v1/public/packages`)
      .then((r) => r.json())
      .then((body) => {
        if (!body.ok) return;
        setApproved(
          (body.packages || []).map((p, i) => ({
            id: p.id,
            hotel: p.hotel_name,
            dist: rtl ? "من مزوّد موثوق" : "Verified provider",
            stars: 5,
            nights: p.duration_days,
            price: Number(p.price_per_person),
            seats: p.seats,
            board: rtl ? "حسب الباقة" : "As listed",
            tone: ["camel", "brown", "cream", "dark"][i % 4],
            provider: p.business_name,
            providerLogoUrl: p.provider_logo_key
              ? `${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(p.provider_logo_key)}`
              : "",
            dates: `${p.available_from} — ${p.available_to}`,
            title: p.title,
            imageUrl: p.cover_key
              ? `${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(p.cover_key)}`
              : JSON.parse(p.hotel_images_json || "[]")[0] || "",
            inclusions: JSON.parse(p.inclusions || "[]"),
            exclusions: JSON.parse(p.exclusions || "[]"),
            originCity: p.origin_city,
            destinationCity: p.destination_city,
            notes: p.notes || "",
            occupancyPrices: JSON.parse(p.occupancy_prices_json || "{}"),
            roomOptions: JSON.parse(p.room_options_json || "[]"),
            cancellationPolicy: p.cancellation_policy || "",
            supportsTabby: Boolean(p.supports_tabby),
            supportsTamara: Boolean(p.supports_tamara),
            paymentConfirmationMode: p.payment_confirmation_mode || "pay_on_arrival",
            availableSeats: Math.max(0,Number(p.seats||0)-Number(p.booked_travelers||0)),
            departureAt:p.departure_at, returnAt:p.return_at, travelMode:p.travel_mode,
            airline:p.airline, flightNumber:p.flight_number, flightArrivalCity:p.flight_arrival_city,
            returnAirline:p.return_airline, returnFlightNumber:p.return_flight_number,
            returnOriginCity:p.return_origin_city, returnDestinationCity:p.return_destination_city,
            roomType:p.room_type, mealPlan:p.meal_plan,
            isDynamic: true,
          })),
        );
      })
      .catch(() => {});
  }, [lang]);
  const normalizeCity = (value) =>
    String(value || "")
      .replace("مكة المكرمة", "مكة")
      .replace("المدينة المنورة", "المدينة")
      .trim();
  const matchesSearch = (p) => {
    if (!p.isDynamic)
      return (
        normalizeCity(umrahSearch?.origin) === "جدة" &&
        normalizeCity(umrahSearch?.destination) === "مكة"
      );
    const originMatches =
      !umrahSearch?.origin ||
      normalizeCity(p.originCity) === normalizeCity(umrahSearch.origin);
    const destinationMatches =
      !umrahSearch?.destination ||
      normalizeCity(p.destinationCity) ===
        normalizeCity(umrahSearch.destination);
    const seatsMatch =
      Number(p.seats || 0) >= Number(umrahSearch?.travelers || 1);
    return originMatches && destinationMatches && seatsMatch;
  };
  const packages = approved.filter(matchesSearch);
  const routeLabel = `${rtl ? umrahSearch?.origin : { جدة: "Jeddah", الرياض: "Riyadh", "المدينة المنورة": "Madinah", الدمام: "Dammam", الطائف: "Taif" }[umrahSearch?.origin] || umrahSearch?.origin} → ${rtl ? umrahSearch?.destination : { "مكة المكرمة": "Makkah", "المدينة المنورة": "Madinah" }[umrahSearch?.destination] || umrahSearch?.destination}`;

  return (
    <>
      {/* Compact search re-bar */}
      <div
        className="browse-searchbar"
        style={{
          background: T.surface,
          borderBottom: `1px solid ${T.hairline}`,
          padding: "20px 32px",
        }}
      >
        <div style={{ maxWidth: 1180, margin: "0 auto" }}>
          <div
            className="browse-searchbar-inner"
            style={{
              display: "flex",
              alignItems: "center",
              gap: 8,
              flexWrap: "wrap",
            }}
          >
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 14px",
                borderRadius: 12,
                background: T.bg,
                border: `1px solid ${T.hairline}`,
              }}
            >
              <Icon name="plane" size={14} color={T.primary} />
              <span
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 12.5,
                  color: T.text,
                  fontWeight: 600,
                }}
              >
                {routeLabel}
              </span>
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 14px",
                borderRadius: 12,
                background: T.bg,
                border: `1px solid ${T.hairline}`,
              }}
            >
              <Icon name="calendar" size={14} color={T.primary} />
              <span
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 12.5,
                  color: T.text,
                  fontWeight: 600,
                }}
              >
                {umrahSearch?.date || (rtl ? "أي موعد" : "Any date")}
              </span>
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                padding: "10px 14px",
                borderRadius: 12,
                background: T.bg,
                border: `1px solid ${T.hairline}`,
              }}
            >
              <Icon name="user" size={14} color={T.primary} />
              <span
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 12.5,
                  color: T.text,
                  fontWeight: 600,
                }}
              >
                {umrahSearch?.travelers || 1} {rtl ? "مسافرين" : "travelers"}
              </span>
            </div>
            <button
              onClick={() => setPage("home")}
              style={{
                marginInlineStart: "auto",
                padding: "10px 20px",
                borderRadius: 12,
                background: T.primary,
                color: "#fff",
                border: 0,
                fontFamily: "Alexandria",
                fontWeight: 600,
                fontSize: 13,
                cursor: "pointer",
              }}
            >
              {rtl ? "تعديل البحث" : "Edit search"}
            </button>
          </div>
        </div>
      </div>

      <div
        className="browse-page"
        style={{ padding: "32px", background: T.bg, minHeight: 600 }}
      >
        <div
          className="browse-layout"
          style={{
            maxWidth: 1180,
            margin: "0 auto",
            display: "grid",
            gridTemplateColumns: "260px 1fr",
            gap: 28,
          }}
        >
          {filtersOpen && (
            <button
              className="filter-backdrop"
              aria-label={rtl ? "إغلاق الفلاتر" : "Close filters"}
              onClick={() => setFiltersOpen(false)}
            />
          )}
          {/* Filter sidebar */}
          <aside
            className={`browse-filters ${filtersOpen ? "is-open" : ""}`}
            style={{
              background: T.surface,
              border: `1px solid ${T.hairline}`,
              borderRadius: 16,
              padding: 20,
              height: "fit-content",
              position: "sticky",
              top: 88,
            }}
          >
            <div
              className="browse-filter-heading"
              style={{
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 14,
                color: T.text,
                marginBottom: 16,
              }}
            >
              <span>{rtl ? "الفلاتر" : "Filters"}</span>
              <button
                aria-label={rtl ? "إغلاق" : "Close"}
                onClick={() => setFiltersOpen(false)}
              >
                ×
              </button>
            </div>

            {/* Price range */}
            <div style={{ marginBottom: 18 }}>
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 11.5,
                  fontWeight: 600,
                  color: T.textMuted,
                  letterSpacing: "0.05em",
                  textTransform: "uppercase",
                  marginBottom: 10,
                }}
              >
                {rtl ? "السعر" : "Price (SAR)"}
              </div>
              <div
                style={{
                  height: 4,
                  borderRadius: 99,
                  background: T.hairlineStrong,
                  position: "relative",
                  margin: "14px 0",
                }}
              >
                <div
                  style={{
                    position: "absolute",
                    insetInlineStart: "20%",
                    width: "55%",
                    height: "100%",
                    background: T.primary,
                    borderRadius: 99,
                  }}
                />
                <div
                  style={{
                    position: "absolute",
                    insetInlineStart: "20%",
                    top: "50%",
                    transform: "translate(-50%,-50%)",
                    width: 16,
                    height: 16,
                    borderRadius: 99,
                    background: "#fff",
                    border: `2px solid ${T.primary}`,
                    boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
                  }}
                />
                <div
                  style={{
                    position: "absolute",
                    insetInlineStart: "75%",
                    top: "50%",
                    transform: "translate(-50%,-50%)",
                    width: 16,
                    height: 16,
                    borderRadius: 99,
                    background: "#fff",
                    border: `2px solid ${T.primary}`,
                    boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
                  }}
                />
              </div>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  fontFamily: "Alexandria",
                  fontSize: 12,
                  color: T.text,
                  fontWeight: 600,
                }}
              >
                <span>1,200</span>
                <span>5,500</span>
              </div>
            </div>

            {/* Stars */}
            <div style={{ marginBottom: 18 }}>
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 11.5,
                  fontWeight: 600,
                  color: T.textMuted,
                  letterSpacing: "0.05em",
                  textTransform: "uppercase",
                  marginBottom: 10,
                }}
              >
                {rtl ? "تقييم الفندق" : "Hotel rating"}
              </div>
              {[5, 4, 3].map((n, i) => (
                <label
                  key={n}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    padding: "5px 0",
                    cursor: "pointer",
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: 4,
                      background: i === 0 ? T.primary : T.surface,
                      border: `1.5px solid ${i === 0 ? T.primary : T.hairlineStrong}`,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    {i === 0 && (
                      <Icon
                        name="check"
                        size={12}
                        color="#fff"
                        strokeWidth={3}
                      />
                    )}
                  </div>
                  <Stars value={n} size={12} />
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12,
                      color: T.text,
                      marginInlineStart: "auto",
                    }}
                  >
                    {[24, 18, 8][i]}
                  </span>
                </label>
              ))}
            </div>

            {/* Distance from Haram */}
            <div style={{ marginBottom: 18 }}>
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 11.5,
                  fontWeight: 600,
                  color: T.textMuted,
                  letterSpacing: "0.05em",
                  textTransform: "uppercase",
                  marginBottom: 10,
                }}
              >
                {rtl ? "المسافة من الحرم" : "Distance from Haram"}
              </div>
              {[
                rtl ? "أقل من 100م" : "Within 100m",
                rtl ? "100–300م" : "100–300m",
                rtl ? "300–500م" : "300–500m",
                rtl ? "أكثر من 500م" : "Over 500m",
              ].map((d, i) => (
                <label
                  key={d}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    padding: "5px 0",
                    cursor: "pointer",
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: 4,
                      background: i === 1 ? T.primary : T.surface,
                      border: `1.5px solid ${i === 1 ? T.primary : T.hairlineStrong}`,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    {i === 1 && (
                      <Icon
                        name="check"
                        size={12}
                        color="#fff"
                        strokeWidth={3}
                      />
                    )}
                  </div>
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12.5,
                      color: T.text,
                    }}
                  >
                    {d}
                  </span>
                </label>
              ))}
            </div>

            {/* Board */}
            <div>
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 11.5,
                  fontWeight: 600,
                  color: T.textMuted,
                  letterSpacing: "0.05em",
                  textTransform: "uppercase",
                  marginBottom: 10,
                }}
              >
                {rtl ? "الإقامة" : "Board"}
              </div>
              {[
                rtl ? "بدون" : "Room only",
                rtl ? "إفطار" : "Breakfast",
                rtl ? "نصف إقامة" : "Half board",
                rtl ? "كاملة" : "Full board",
              ].map((b, i) => (
                <label
                  key={b}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    padding: "5px 0",
                    cursor: "pointer",
                  }}
                >
                  <div
                    style={{
                      width: 18,
                      height: 18,
                      borderRadius: 4,
                      background: T.surface,
                      border: `1.5px solid ${T.hairlineStrong}`,
                    }}
                  />
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12.5,
                      color: T.text,
                    }}
                  >
                    {b}
                  </span>
                </label>
              ))}
            </div>
          </aside>

          {/* Results */}
          <main className="browse-results">
            <button
              className="mobile-filter-button"
              onClick={() => setFiltersOpen(true)}
              style={{
                background: T.surface,
                color: T.text,
                border: `1px solid ${T.hairline}`,
              }}
            >
              <Icon name="filter" size={16} color={T.primary} />
              {rtl ? "الفلاتر" : "Filters"}
            </button>
            <div
              className="browse-results-heading"
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                marginBottom: 18,
              }}
            >
              <div>
                <h2
                  style={{
                    margin: 0,
                    fontFamily: "Alexandria",
                    fontWeight: 700,
                    fontSize: 22,
                    color: T.text,
                    letterSpacing: "-0.01em",
                  }}
                >
                  {packages.length} {rtl ? "باقة متاحة" : "packages available"}
                </h2>
                <div
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 12.5,
                    color: T.textMuted,
                    marginTop: 4,
                  }}
                >
                  {routeLabel} · {umrahSearch?.travelers || 1}{" "}
                  {rtl ? "مسافرين" : "travelers"}
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 12,
                    color: T.textMuted,
                  }}
                >
                  {rtl ? "ترتيب:" : "Sort:"}
                </span>
                <select
                  style={{
                    padding: "8px 12px",
                    borderRadius: 10,
                    border: `1px solid ${T.hairline}`,
                    background: T.surface,
                    color: T.text,
                    fontFamily: "Alexandria",
                    fontSize: 12.5,
                    fontWeight: 600,
                    cursor: "pointer",
                  }}
                >
                  <option>{rtl ? "الأنسب" : "Recommended"}</option>
                  <option>{rtl ? "الأرخص" : "Cheapest"}</option>
                  <option>
                    {rtl ? "الأقرب للحرم" : "Distance from Haram"}
                  </option>
                  <option>{rtl ? "التقييم" : "Rating"}</option>
                </select>
              </div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {packages.map((p) => (
                <div
                  className="package-result-card"
                  key={p.id}
                  onClick={() => {
                    setPkg(p);
                    setPage("detail");
                  }}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "280px 1fr 200px",
                    background: T.surface,
                    borderRadius: 18,
                    border: `1px solid ${T.hairline}`,
                    boxShadow: T.cardShadow,
                    overflow: "hidden",
                    cursor: "pointer",
                  }}
                >
                  <div
                    className="package-result-image"
                    style={{ position: "relative" }}
                  >
                    {p.imageUrl ? (
                      <img
                        src={p.imageUrl}
                        alt={p.hotel}
                        style={{
                          width: "100%",
                          height: 210,
                          objectFit: "cover",
                          display: "block",
                        }}
                      />
                    ) : (
                      <ImgSlot
                        theme={T}
                        tone={p.tone}
                        height={210}
                        radius={0}
                        label={null}
                      />
                    )}
                    {p.was && (
                      <div
                        style={{
                          position: "absolute",
                          top: 12,
                          insetInlineStart: 12,
                        }}
                      >
                        <Badge tone="red" theme={T}>
                          -{Math.round((1 - p.price / p.was) * 100)}%
                        </Badge>
                      </div>
                    )}
                    <div
                      style={{
                        position: "absolute",
                        bottom: 10,
                        insetInlineStart: 10,
                        background: "rgba(255,255,255,0.92)",
                        backdropFilter: "blur(6px)",
                        borderRadius: 99,
                        padding: "4px 8px 4px 4px",
                      }}
                    >
                      <ProviderBadge
                        theme={T}
                        name={p.provider}
                        logoUrl={p.providerLogoUrl}
                        size="xs"
                      />
                    </div>
                  </div>
                  <div
                    className="package-result-content"
                    style={{ padding: 18 }}
                  >
                    <div
                      style={{
                        fontFamily: "Alexandria",
                        fontWeight: 700,
                        fontSize: 17,
                        color: T.text,
                        letterSpacing: "-0.005em",
                      }}
                    >
                      {p.hotel}
                    </div>
                    <div
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: 8,
                        marginTop: 6,
                      }}
                    >
                      <Stars value={p.stars} size={12} />
                      <span
                        style={{
                          fontFamily: "Alexandria",
                          fontSize: 12,
                          color: T.textMuted,
                        }}
                      >
                        4.7 · 312 {rtl ? "تقييم" : "reviews"}
                      </span>
                    </div>
                    <div
                      style={{
                        display: "flex",
                        flexWrap: "wrap",
                        gap: 12,
                        marginTop: 12,
                        fontFamily: "Alexandria",
                        fontSize: 12.5,
                        color: T.textMuted,
                      }}
                    >
                      <span
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 5,
                        }}
                      >
                        <Icon name="pin" size={12} color={T.textMuted} />
                        {p.dist}
                      </span>
                      <span
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 5,
                        }}
                      >
                        <Icon name="calendar" size={12} color={T.textMuted} />
                        {p.dates}
                      </span>
                      <span
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 5,
                        }}
                      >
                        <Icon name="bed" size={12} color={T.textMuted} />
                        {p.nights} {rtl ? "ليالٍ" : "nights"}
                      </span>
                      <span
                        style={{
                          display: "flex",
                          alignItems: "center",
                          gap: 5,
                        }}
                      >
                        <Icon name="coffee" size={12} color={T.textMuted} />
                        {p.board}
                      </span>
                    </div>
                    <div style={{ marginTop: 14, display: "flex", gap: 6 }}>
                      <Badge tone="green" theme={T}>
                        {rtl ? "إلغاء مجاني" : "Free cancellation"}
                      </Badge>
                      <Badge tone="warn" theme={T}>
                        {p.seats} {rtl ? "مقاعد متبقية" : "seats left"}
                      </Badge>
                    </div>
                  </div>
                  <div
                    className="package-result-price"
                    style={{
                      padding: 18,
                      borderInlineStart: `1px solid ${T.hairline}`,
                      display: "flex",
                      flexDirection: "column",
                      justifyContent: "space-between",
                      textAlign: "center",
                      alignItems: "center",
                    }}
                  >
                    <div>
                      {p.was && (
                        <div
                          style={{
                            fontFamily: "Alexandria",
                            fontSize: 12,
                            color: T.textFaint,
                            textDecoration: "line-through",
                          }}
                        >
                          {p.was.toLocaleString()} SAR
                        </div>
                      )}
                      <div
                        style={{
                          fontFamily: "Alexandria",
                          fontWeight: 700,
                          fontSize: 24,
                          color: T.text,
                          letterSpacing: "-0.01em",
                          margin: "4px 0",
                        }}
                      >
                        {p.price.toLocaleString()}
                      </div>
                      <div
                        style={{
                          fontFamily: "Alexandria",
                          fontSize: 11,
                          color: T.textMuted,
                        }}
                      >
                        SAR / {rtl ? "للفرد" : "person"}
                      </div>
                    </div>
                    <button
                      style={{
                        padding: "11px 0",
                        borderRadius: 10,
                        border: 0,
                        width: "100%",
                        background: T.primary,
                        color: "#fff",
                        fontFamily: "Alexandria",
                        fontWeight: 600,
                        fontSize: 13,
                        cursor: "pointer",
                        boxShadow: "0 4px 10px rgba(193,152,114,0.3)",
                      }}
                    >
                      {rtl ? "عرض التفاصيل" : "View details"}
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </main>
        </div>
      </div>
    </>
  );
}

// ─── Package detail page ───────────────────────────────────────────────
function WebDetailPage({ theme, lang }) {
  const T = theme;
  const l = L[lang];
  const rtl = isRTL(lang);
  const { pkg, setPage } = useWeb();
  const p = pkg || {
    hotel: rtl ? "فيرمونت ساعة مكة" : "Fairmont Makkah Clock Royal",
    provider: rtl ? "الإيلاف الفاخرة" : "Elaf Premium",
    price: 4899,
    was: 5499,
    dates: rtl ? "16–25 رمضان" : "16–25 Ramadan",
    nights: 7,
    dist: rtl ? "50م من الحرم" : "50m from Haram",
    stars: 5,
    tone: "dark",
    board: rtl ? "إفطار+عشاء" : "B&D",
    seats: 4,
  };

  return (
    <div style={{ background: T.bg, paddingBottom: 60 }}>
      {/* Breadcrumb */}
      <div
        style={{
          padding: "14px 32px",
          borderBottom: `1px solid ${T.hairline}`,
          background: T.surface,
        }}
      >
        <div
          style={{
            maxWidth: 1180,
            margin: "0 auto",
            display: "flex",
            alignItems: "center",
            gap: 6,
            fontFamily: "Alexandria",
            fontSize: 12,
          }}
        >
          <a
            onClick={() => setPage("home")}
            style={{ color: T.textMuted, cursor: "pointer" }}
          >
            {rtl ? "الرئيسية" : "Home"}
          </a>
          <Icon
            name={rtl ? "chevron-l" : "chevron-r"}
            size={12}
            color={T.textFaint}
          />
          <a
            onClick={() => setPage("browse")}
            style={{ color: T.textMuted, cursor: "pointer" }}
          >
            {rtl ? "الباقات" : "Packages"}
          </a>
          <Icon
            name={rtl ? "chevron-l" : "chevron-r"}
            size={12}
            color={T.textFaint}
          />
          <span style={{ color: T.text, fontWeight: 600 }}>{p.hotel}</span>
        </div>
      </div>

      <div style={{ padding: "32px", maxWidth: 1180, margin: "0 auto" }}>
        {/* Gallery */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "2fr 1fr 1fr",
            gridTemplateRows: "200px 200px",
            gap: 10,
            marginBottom: 28,
            borderRadius: 22,
            overflow: "hidden",
          }}
        >
          <div style={{ gridRow: "span 2", position: "relative" }}>
            {p.imageUrl ? (
              <img
                src={p.imageUrl}
                alt={p.hotel}
                style={{ width: "100%", height: "100%", objectFit: "cover" }}
              />
            ) : (
              <ImgSlot
                theme={T}
                tone={p.tone}
                height="100%"
                radius={0}
                label={p.hotel}
              />
            )}
          </div>
          <ImgSlot
            theme={T}
            tone="camel"
            height="100%"
            radius={0}
            label={rtl ? "الغرفة" : "Room"}
          />
          <ImgSlot
            theme={T}
            tone="brown"
            height="100%"
            radius={0}
            label={rtl ? "الحرم" : "Haram view"}
          />
          <ImgSlot
            theme={T}
            tone="cream"
            height="100%"
            radius={0}
            label={rtl ? "اللوبي" : "Lobby"}
          />
          <div style={{ position: "relative" }}>
            <ImgSlot
              theme={T}
              tone="dark"
              height="100%"
              radius={0}
              label={null}
            />
            <div
              style={{
                position: "absolute",
                inset: 0,
                background: "rgba(31,27,23,0.55)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <span
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 13,
                  fontWeight: 700,
                  color: "#fff",
                }}
              >
                {rtl ? "+8 صور" : "+8 photos"}
              </span>
            </div>
          </div>
        </div>

        <div
          style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 32 }}
        >
          {/* Main column */}
          <div>
            <ProviderBadge
              theme={T}
              name={p.provider}
              logoUrl={p.providerLogoUrl}
              size="md"
              style={{ marginBottom: 10 }}
            />
            <h1
              style={{
                margin: 0,
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 32,
                color: T.text,
                letterSpacing: "-0.02em",
                lineHeight: 1.2,
              }}
            >
              {p.hotel}
            </h1>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 10,
                marginTop: 8,
                color: T.textMuted,
                fontSize: 13,
              }}
            >
              <Stars value={p.stars} size={14} />
              <span style={{ fontFamily: "Alexandria" }}>
                4.8 · 312 {rtl ? "تقييم" : "reviews"}
              </span>
              <span>·</span>
              <span
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 4,
                  fontFamily: "Alexandria",
                }}
              >
                <Icon name="pin" size={13} color={T.textMuted} />
                {p.dist}
              </span>
            </div>

            {/* Stats strip */}
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(4, 1fr)",
                gap: 0,
                marginTop: 24,
                background: T.surface,
                borderRadius: 14,
                border: `1px solid ${T.hairline}`,
                padding: "14px 0",
              }}
            >
              {[
                { i: "calendar", t: p.dates, l: rtl ? "الموعد" : "Window" },
                {
                  i: "bed",
                  t: `${p.nights} ${rtl ? "ليالٍ" : "nights"}`,
                  l: rtl ? "الإقامة" : "Stay",
                },
                {
                  i: p.isDynamic ? "user" : "plane",
                  t: p.isDynamic
                    ? `${p.seats} ${rtl ? "شخص" : "people"}`
                    : rtl
                      ? "مع طيران"
                      : "Flight included",
                  l: p.isDynamic
                    ? rtl
                      ? "السعة"
                      : "Capacity"
                    : rtl
                      ? "السفر"
                      : "Travel",
                },
                {
                  i: "coffee",
                  t: p.isDynamic ? `${p.inclusions?.length || 0}` : p.board,
                  l: p.isDynamic
                    ? rtl
                      ? "مشتملات محددة"
                      : "Selected items"
                    : rtl
                      ? "الوجبات"
                      : "Meals",
                },
              ].map((m, i) => (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    flexDirection: "column",
                    alignItems: "center",
                    gap: 4,
                    borderInlineEnd: i < 3 ? `1px solid ${T.hairline}` : "none",
                  }}
                >
                  <Icon name={m.i} size={18} color={T.primary} />
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 13,
                      color: T.text,
                      fontWeight: 600,
                      marginTop: 4,
                    }}
                  >
                    {m.t}
                  </span>
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 10.5,
                      color: T.textMuted,
                    }}
                  >
                    {m.l}
                  </span>
                </div>
              ))}
            </div>

            {/* Description */}
            <h2
              style={{
                margin: "32px 0 10px",
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 20,
                color: T.text,
                letterSpacing: "-0.01em",
              }}
            >
              {rtl ? "عن الباقة" : "About this package"}
            </h2>
            <p
              style={{
                margin: 0,
                fontFamily: "Alexandria",
                fontSize: 14,
                color: T.textMuted,
                lineHeight: 1.7,
              }}
            >
              {p.isDynamic
                ? p.notes ||
                  (rtl
                    ? "باقة مقدمة من مزود معتمد. راجع المشتملات والتواريخ قبل الحجز."
                    : "A package from a verified provider. Review inclusions and dates before booking.")
                : rtl
                  ? "باقة عمرة كاملة تشمل الطيران والإقامة في فيرمونت ساعة مكة على بُعد 50 متراً فقط من الحرم. الإقامة شاملة الإفطار والعشاء يومياً، ونقل من المطار، ومرشد ميداني طوال فترة الإقامة. الباقة مجدولة مسبقاً من المزوّد ولا تتطلب اختيار مقعد."
                  : "A complete Umrah package including flight and stay at Fairmont Makkah Clock Royal — just 50m from the Haram. Includes daily breakfast & dinner, airport transfers, and an on-site guide throughout your stay. Pre-arranged by the provider; no seat selection required."}
            </p>

            <WebItineraryTimeline theme={T} lang={lang} pkg={p} />

            {/* What's included */}
            <h2
              style={{
                margin: "32px 0 14px",
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 20,
                color: T.text,
                letterSpacing: "-0.01em",
              }}
            >
              {rtl ? "ما يشمله" : "What's included"}
            </h2>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gap: 10,
              }}
            >
              {(p.isDynamic
                ? (p.inclusions || []).map((t) => ({ i: "check", t }))
                : [
                    {
                      i: "plane",
                      t: rtl
                        ? "تذكرة طيران ذهاب وعودة"
                        : "Round-trip flight ticket",
                    },
                    {
                      i: "bed",
                      t: rtl ? "6 ليالٍ في فيرمونت" : "6 nights at Fairmont",
                    },
                    {
                      i: "coffee",
                      t: rtl
                        ? "إفطار وعشاء يومياً"
                        : "Daily breakfast & dinner",
                    },
                    {
                      i: "car",
                      t: rtl ? "نقل من المطار" : "Airport transfers",
                    },
                    { i: "compass", t: rtl ? "مرشد ميداني" : "On-site guide" },
                    { i: "shield", t: rtl ? "تأمين سفر" : "Travel insurance" },
                  ]
              ).map((it, i) => (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 10,
                    padding: 12,
                    background: T.surface,
                    border: `1px solid ${T.hairline}`,
                    borderRadius: 12,
                  }}
                >
                  <div
                    style={{
                      width: 32,
                      height: 32,
                      borderRadius: 8,
                      background: "rgba(63,142,92,0.12)",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                    }}
                  >
                    <Icon name="check" size={16} color={T.success} />
                  </div>
                  <span
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 13,
                      color: T.text,
                    }}
                  >
                    {it.t}
                  </span>
                </div>
              ))}
              {p.isDynamic && !p.inclusions?.length && (
                <div
                  style={{
                    gridColumn: "1 / -1",
                    padding: 14,
                    color: T.textMuted,
                    font: "500 12px Alexandria",
                  }}
                >
                  {rtl
                    ? "لم يحدد المزود مشتملات الباقة بعد."
                    : "The provider has not selected inclusions yet."}
                </div>
              )}
            </div>

            {p.exclusions?.length > 0 && (
              <>
                <h2
                  style={{
                    margin: "32px 0 14px",
                    fontFamily: "Alexandria",
                    fontWeight: 700,
                    fontSize: 20,
                    color: T.text,
                  }}
                >
                  {rtl ? "ما لا تشمله الباقة" : "Not included"}
                </h2>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr",
                    gap: 10,
                  }}
                >
                  {p.exclusions.map((text, i) => (
                    <div
                      key={i}
                      style={{
                        padding: 12,
                        border: `1px solid ${T.hairline}`,
                        borderRadius: 12,
                        color: T.textMuted,
                        font: "500 13px Alexandria",
                      }}
                    >
                      × {text}
                    </div>
                  ))}
                </div>
              </>
            )}

            {/* Provider card */}
            <h2
              style={{
                margin: "32px 0 14px",
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 20,
                color: T.text,
                letterSpacing: "-0.01em",
              }}
            >
              {rtl ? "عن المزوّد" : "About the provider"}
            </h2>
            <div
              style={{
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                borderRadius: 16,
                padding: 20,
                display: "flex",
                alignItems: "center",
                gap: 16,
              }}
            >
              <ProviderBadge
                theme={T}
                name={p.provider}
                logoUrl={p.providerLogoUrl}
                size="md"
                verified={false}
              />
              <div style={{ flex: 1 }}>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 6,
                    fontFamily: "Alexandria",
                    fontSize: 12.5,
                    color: T.textMuted,
                  }}
                >
                  <Icon name="shield" size={12} color={T.success} />{" "}
                  {rtl
                    ? "مزوّد موثّق · منذ 2019"
                    : "Verified provider · since 2019"}
                </div>
                <div
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 12.5,
                    color: T.textMuted,
                    marginTop: 2,
                  }}
                >
                  142 {rtl ? "باقة نشطة · 4.7★" : "active packages · 4.7★"}
                </div>
              </div>
              <button
                onClick={() => setPage("browse")}
                style={{
                  padding: "9px 16px",
                  borderRadius: 10,
                  background: "transparent",
                  border: `1px solid ${T.hairline}`,
                  color: T.text,
                  fontFamily: "Alexandria",
                  fontWeight: 600,
                  fontSize: 12.5,
                  cursor: "pointer",
                }}
              >
                {rtl ? "كل باقاته" : "All packages"}
              </button>
            </div>
          </div>

          {/* Sticky booking panel */}
          <aside>
            <div
              style={{
                position: "sticky",
                top: 88,
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                borderRadius: 18,
                padding: 22,
                boxShadow: T.cardShadow,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "flex-end",
                  justifyContent: "space-between",
                  marginBottom: 12,
                }}
              >
                <div>
                  {p.was && (
                    <div
                      style={{
                        fontFamily: "Alexandria",
                        fontSize: 13,
                        color: T.textFaint,
                        textDecoration: "line-through",
                      }}
                    >
                      {p.was.toLocaleString()} SAR
                    </div>
                  )}
                  <div
                    style={{
                      fontFamily: "Alexandria",
                      fontWeight: 700,
                      fontSize: 32,
                      color: T.text,
                      letterSpacing: "-0.02em",
                    }}
                  >
                    {p.price.toLocaleString()}{" "}
                    <span
                      style={{
                        fontSize: 14,
                        fontWeight: 500,
                        color: T.textMuted,
                      }}
                    >
                      SAR
                    </span>
                  </div>
                  <div
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12,
                      color: T.textMuted,
                      marginTop: 2,
                    }}
                  >
                    {rtl ? "للفرد · شامل الضريبة" : "per person · incl. tax"}
                  </div>
                </div>
                {p.was && (
                  <Badge tone="red" theme={T}>
                    -{Math.round((1 - p.price / p.was) * 100)}%
                  </Badge>
                )}
              </div>

              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 8,
                  padding: "10px 12px",
                  borderRadius: 10,
                  background: "rgba(180,81,59,0.10)",
                  marginBottom: 12,
                }}
              >
                <Icon name="bell" size={14} color={T.danger} />
                <span
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 12,
                    color: T.danger,
                    fontWeight: 600,
                  }}
                >
                  {p.seats}{" "}
                  {rtl
                    ? "مقاعد متاحة في هذه الباقة"
                    : "seats available in this package"}
                </span>
              </div>

              {/* Traveler selector */}
              <div
                style={{
                  padding: 12,
                  borderRadius: 10,
                  border: `1px solid ${T.hairline}`,
                  marginBottom: 12,
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                }}
              >
                <div>
                  <div
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 10.5,
                      color: T.textMuted,
                      fontWeight: 600,
                      letterSpacing: "0.05em",
                      textTransform: "uppercase",
                    }}
                  >
                    {l.travelers}
                  </div>
                  <div
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 13.5,
                      color: T.text,
                      fontWeight: 600,
                      marginTop: 2,
                    }}
                  >
                    {rtl ? "يُحدد في الخطوة التالية" : "Select in the next step"}
                  </div>
                </div>
                <Icon name="user" size={18} color={T.primary} />
              </div>

              <button
                onClick={() => setPage("checkout")}
                style={{
                  width: "100%",
                  padding: "14px",
                  borderRadius: 12,
                  border: 0,
                  background: T.primary,
                  color: "#fff",
                  fontFamily: "Alexandria",
                  fontWeight: 700,
                  fontSize: 14,
                  cursor: "pointer",
                  boxShadow: "0 8px 20px rgba(193,152,114,0.35)",
                  marginBottom: 8,
                }}
              >
                {rtl ? "احجز الآن" : "Book now"}
              </button>
              <button
                onClick={() => {
                  const saved = JSON.parse(
                    localStorage.getItem("duyuf_saved_packages") || "[]",
                  );
                  if (!saved.includes(p.id)) saved.push(p.id);
                  localStorage.setItem(
                    "duyuf_saved_packages",
                    JSON.stringify(saved),
                  );
                  window.alert(
                    rtl
                      ? "تم حفظ الباقة في هذا الجهاز."
                      : "Package saved on this device.",
                  );
                }}
                style={{
                  width: "100%",
                  padding: "12px",
                  borderRadius: 12,
                  border: `1px solid ${T.hairline}`,
                  background: T.surface,
                  color: T.text,
                  fontFamily: "Alexandria",
                  fontWeight: 600,
                  fontSize: 13,
                  cursor: "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 8,
                }}
              >
                <Icon name="heart" size={14} color={T.text} />{" "}
                {rtl ? "حفظ" : "Save"}
              </button>

              <div
                style={{
                  marginTop: 16,
                  padding: 12,
                  borderRadius: 10,
                  background: T.surfaceAlt,
                  fontFamily: "Alexandria",
                  fontSize: 11.5,
                  color: T.textMuted,
                  lineHeight: 1.6,
                }}
              >
                <strong style={{ color: T.text }}>
                  {rtl ? "سياسة الإلغاء:" : "Cancellation:"}
                </strong>{" "}
                {p.cancellationPolicy ||
                  (rtl
                    ? "تطبق سياسة الإلغاء الموضحة من المزود."
                    : "The provider cancellation policy applies.")}
                {p.occupancyPrices &&
                  Object.keys(p.occupancyPrices).length > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <strong style={{ color: T.text }}>
                        {rtl ? "أسعار الإشغال:" : "Occupancy prices:"}
                      </strong>{" "}
                      {Object.entries(p.occupancyPrices)
                        .map(
                          ([k, v]) =>
                            `${k}: ${Number(v).toLocaleString()} ${rtl ? "ر.س" : "SAR"}`,
                        )
                        .join(" · ")}
                    </div>
                  )}
                {(p.supportsTabby || p.supportsTamara) && (
                  <div style={{ marginTop: 8, color: T.text }}>
                    {rtl ? "متاح عبر: " : "Available with: "}
                    {[
                      p.supportsTabby ? "Tabby" : "",
                      p.supportsTamara ? "Tamara" : "",
                    ]
                      .filter(Boolean)
                      .join(" · ")}
                  </div>
                )}
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function WebCustomerBookingsPage({theme,lang}){
  const T=theme,rtl=isRTL(lang),{setPage}=useWeb();
  const [user,setUser]=React.useState(()=>firebase.auth().currentUser),[phone,setPhone]=React.useState(""),[otp,setOtp]=React.useState(""),[step,setStep]=React.useState(firebase.auth().currentUser?"bookings":"phone"),[bookings,setBookings]=React.useState([]),[tab,setTab]=React.useState("upcoming"),[busy,setBusy]=React.useState(false),[message,setMessage]=React.useState("");
  const verifying=React.useRef(false);
  const load=async(current=user||firebase.auth().currentUser)=>{if(!current)return;setBusy(true);try{const token=await current.getIdToken(true),r=await fetch(`${window.DUYUF_API_URL}/v1/customer/bookings`,{headers:{authorization:`Bearer ${token}`}}),b=await r.json();if(!r.ok)throw new Error(b.error);setBookings(b.bookings||[]);localStorage.setItem("duyuf_dashboard_mode","customer");localStorage.setItem("duyuf_customer",JSON.stringify({phone:b.phone}));setStep("bookings");}catch(_){setMessage(rtl?"تعذر تحميل الحجوزات.":"Could not load bookings.");}finally{setBusy(false);}};
  React.useEffect(()=>{if(user)load(user);},[]);
  const send=async()=>{const digits=phone.replace(/\D/g,"").replace(/^966/,"").replace(/^0/,"");if(!/^5\d{8}$/.test(digits)){setMessage(rtl?"أدخل رقم جوال صحيحًا.":"Enter a valid mobile number.");return;}setBusy(true);setMessage("");try{if(window.duyufCustomerRecaptcha)window.duyufCustomerRecaptcha.clear();window.duyufCustomerRecaptcha=new firebase.auth.RecaptchaVerifier("duyuf-customer-recaptcha",{size:"invisible"});window.duyufCustomerConfirmation=await firebase.auth().signInWithPhoneNumber(`+966${digits}`,window.duyufCustomerRecaptcha);setPhone(digits);setStep("otp");}catch(_){setMessage(rtl?"تعذر إرسال رمز التحقق.":"Could not send verification code.");}finally{setBusy(false);}};
  const verify=async(value=otp)=>{if(verifying.current||!/^\d{6}$/.test(value))return;verifying.current=true;setBusy(true);try{const credential=await window.duyufCustomerConfirmation.confirm(value);setUser(credential.user);await load(credential.user);}catch(_){setMessage(rtl?"الرمز غير صحيح أو انتهت صلاحيته.":"Invalid or expired code.");}finally{verifying.current=false;setBusy(false);}};
  const groups={upcoming:bookings.filter(b=>["confirmed","checked_in"].includes(b.status)),past:bookings.filter(b=>["checked_out","completed"].includes(b.status)),cancelled:bookings.filter(b=>["cancelled","no_show"].includes(b.status))},shown=groups[tab]||[];
  const statusLabel=s=>s==="confirmed"?(rtl?"مؤكد":"Confirmed"):s==="checked_in"?(rtl?"أثناء الرحلة":"In progress"):s==="checked_out"?(rtl?"مكتمل":"Completed"):s==="cancelled"?(rtl?"ملغي من المزود":"Cancelled by provider"):s==="no_show"?(rtl?"لم يحضر":"No-show"):s;
  const download=async b=>{const r=await fetch(`${window.DUYUF_API_URL}/v1/public/bookings/${encodeURIComponent(b.booking_reference)}/pdf?token=${encodeURIComponent(b.public_token)}`),blob=await r.blob(),u=URL.createObjectURL(blob),a=document.createElement("a");a.href=u;a.download=`Duyuf-${b.booking_reference}.pdf`;a.click();setTimeout(()=>URL.revokeObjectURL(u),30000);};
  if(step!=="bookings")return <div style={{minHeight:650,background:T.bg,padding:"40px 16px"}}><main style={{maxWidth:520,margin:"0 auto",padding:28,borderRadius:22,background:T.surface,border:`1px solid ${T.hairline}`}}><h1 style={{color:T.text,marginTop:0}}>{rtl?"الدخول إلى حجوزاتي":"Sign in to my bookings"}</h1><p style={{color:T.textMuted}}>{rtl?"استخدم رقم الجوال المرتبط بالحجز.":"Use the mobile number linked to your booking."}</p><div id="duyuf-customer-recaptcha"/>{step==="phone"?<div style={{display:"grid",gap:14}}><div dir="ltr" style={{display:"flex",border:`1px solid ${T.hairlineStrong}`,borderRadius:13,overflow:"hidden"}}><span style={{padding:15}}>+966</span><input inputMode="numeric" value={phone} onChange={e=>setPhone(e.target.value.replace(/\D/g,"").slice(0,10))} placeholder="5xxxxxxxx" style={{flex:1,border:0,padding:14,fontSize:16}}/></div><button disabled={busy} onClick={send} style={{minHeight:54,border:0,borderRadius:13,background:T.primary,color:"#fff",fontWeight:700}}>{rtl?"إرسال رمز التحقق":"Send verification code"}</button></div>:<div style={{display:"grid",gap:14}}><div>{rtl?<>أرسلنا رمزًا إلى <b dir="ltr">+966 {phone}</b></>:<>Code sent to +966 {phone}</>}</div><input autoFocus inputMode="numeric" pattern="[0-9]*" autoComplete="one-time-code" name="one-time-code" value={otp} maxLength={6} onChange={e=>{const n=e.target.value.replace(/\D/g,"").slice(0,6);setOtp(n);if(n.length===6)setTimeout(()=>verify(n),0);}} style={{minHeight:54,textAlign:"center",fontSize:24,letterSpacing:8,direction:"ltr"}}/><button disabled={busy} onClick={()=>verify()} style={{minHeight:54,border:0,borderRadius:13,background:T.primary,color:"#fff",fontWeight:700}}>{rtl?"تحقق ومتابعة":"Verify and continue"}</button></div>}{message&&<p style={{color:"#b42318"}}>{message}</p>}</main></div>;
  return <div style={{minHeight:700,background:T.bg,padding:"32px 16px 80px"}}><main style={{maxWidth:980,margin:"0 auto"}}><div style={{display:"flex",justifyContent:"space-between",alignItems:"center",gap:12,flexWrap:"wrap"}}><div><h1 style={{margin:0,color:T.text}}>{rtl?"إدارة حجوزاتي":"Manage my bookings"}</h1><p style={{color:T.textMuted}}>{rtl?"تابع رحلاتك، السداد ومستندات التأكيد من مكان واحد.":"Track trips, payments and confirmation documents."}</p></div><button onClick={()=>setPage("home")} style={{padding:"11px 16px",border:`1px solid ${T.hairlineStrong}`,borderRadius:11,background:T.surface}}>{rtl?"استكشاف الباقات":"Explore packages"}</button></div><div style={{display:"flex",gap:8,margin:"22px 0",overflowX:"auto"}}>{[["upcoming",rtl?"القادمة":"Upcoming"],["past",rtl?"السابقة":"Past"],["cancelled",rtl?"الملغاة":"Cancelled"]].map(([id,label])=><button key={id} onClick={()=>setTab(id)} style={{padding:"10px 18px",borderRadius:99,border:`1px solid ${tab===id?T.primary:T.hairlineStrong}`,background:tab===id?T.primary:T.surface,color:tab===id?"#fff":T.text,whiteSpace:"nowrap"}}>{label} ({groups[id].length})</button>)}</div>{busy?<p>{rtl?"جارٍ تحميل الحجوزات…":"Loading bookings…"}</p>:shown.length===0?<div style={{padding:40,textAlign:"center",background:T.surface,borderRadius:18,border:`1px solid ${T.hairline}`}}><h3>{rtl?"لا توجد حجوزات في هذا القسم":"No bookings here"}</h3><p style={{color:T.textMuted}}>{rtl?"أي حجز مرتبط بهذا الرقم سيظهر هنا تلقائيًا.":"Bookings linked to this phone appear automatically."}</p></div>:<div style={{display:"grid",gap:16}}>{shown.map(b=>{const p=b.package||{};return <article key={b.id} style={{padding:20,borderRadius:18,background:T.surface,border:`1px solid ${T.hairline}`,boxShadow:T.cardShadow}}><div style={{display:"flex",justifyContent:"space-between",gap:12,flexWrap:"wrap"}}><div><span style={{display:"inline-flex",padding:"6px 11px",borderRadius:99,background:b.status==="cancelled"?"#feeceb":"#eaf7ef",color:b.status==="cancelled"?"#b42318":"#237a4b",fontWeight:700,fontSize:12}}>{statusLabel(b.status)}</span><h2 style={{margin:"12px 0 5px",color:T.text}}>{p.title||b.title}</h2><p style={{margin:0,color:T.textMuted}}>{p.hotel||b.hotel_name} · {p.provider||b.business_name}</p></div><div style={{textAlign:rtl?"left":"right"}}><small style={{color:T.textMuted}}>{rtl?"رقم الحجز":"Booking reference"}</small><strong dir="ltr" style={{display:"block",marginTop:4}}>{b.booking_reference}</strong></div></div><div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(150px,1fr))",gap:14,margin:"18px 0",padding:"16px 0",borderBlock:`1px solid ${T.hairline}`}}><div><small>{rtl?"التاريخ":"Dates"}</small><strong style={{display:"block"}}>{String(p.departureAt||b.available_from||"—").slice(0,10)} - {String(p.returnAt||b.available_to||"—").slice(0,10)}</strong></div><div><small>{rtl?"المسافرون":"Travelers"}</small><strong style={{display:"block"}}>{b.travelers}</strong></div><div><small>{rtl?"الغرف":"Rooms"}</small><strong style={{display:"block"}}>{(b.rooms||[]).reduce((s,r)=>s+Number(r.count||0),0)}</strong></div><div><small>{rtl?"الإجمالي / المتبقي":"Total / due"}</small><strong style={{display:"block"}}>{Number(b.total_amount).toLocaleString()} {b.currency}</strong></div><div><small>{rtl?"السداد":"Payment"}</small><strong style={{display:"block"}}>{rtl?"عند الوصول":"Pay on arrival"}</strong></div></div><div style={{display:"flex",gap:10,flexWrap:"wrap"}}><button onClick={()=>download(b)} style={{padding:"11px 16px",border:0,borderRadius:11,background:T.primary,color:"#fff",fontWeight:700}}>{rtl?"تحميل تأكيد الحجز":"Download confirmation"}</button><button onClick={()=>{localStorage.setItem("duyuf_last_booking",JSON.stringify({bookingReference:b.booking_reference,publicToken:b.public_token,customerName:b.customer_name,customerPhone:b.customer_phone,travelers:b.travelers,adults:b.adults,children:b.children,infants:b.infants,rooms:b.rooms,totalAmount:b.total_amount,balanceAmount:b.total_amount,currency:b.currency,confirmedAt:b.confirmed_at,package:p}));location.assign("/?page=booking-confirmation");}} style={{padding:"11px 16px",border:`1px solid ${T.hairlineStrong}`,borderRadius:11,background:T.surface,color:T.text}}>{rtl?"عرض التفاصيل":"View details"}</button></div></article>})}</div>}</main></div>;
}

function WebCheckoutPage({ theme, lang }) {
  const T = theme, rtl = isRTL(lang), { pkg, setPage, setBookingConfirmation } = useWeb();
  const [step, setStep] = React.useState("details");
  const [form, setForm] = React.useState({ fullName: "", email: "", phone: "", adults: 1, children: 0, infants: 0, rooms:{ single:0,double:1,triple:0,quad:0 }, roomPreference:"" });
  const [firebaseIdToken, setFirebaseIdToken] = React.useState("");
  const [providerSessionToken,setProviderSessionToken]=React.useState("");
  const [adminSessionToken,setAdminSessionToken]=React.useState("");
  const [otp, setOtp] = React.useState("");
  const otpVerifyingRef = React.useRef(false);
  const [busy, setBusy] = React.useState(false), [message, setMessage] = React.useState("");
  const totalTravelers = form.adults + form.children + form.infants;
  const roomMeta = { single:{capacity:1,ar:"مفردة",en:"Single"}, double:{capacity:2,ar:"مزدوجة",en:"Double"}, triple:{capacity:3,ar:"ثلاثية",en:"Triple"}, quad:{capacity:4,ar:"رباعية",en:"Quad"} };
  const availableRooms = Object.entries(roomMeta).map(([key,meta])=>({key,...meta,price:Number(pkg?.occupancyPrices?.[key]||0)})).filter(x=>x.price>0);
  const selectedRooms = availableRooms.map(x=>({...x,count:Number(form.rooms?.[x.key]||0)})).filter(x=>x.count>0);
  const roomCapacity = selectedRooms.reduce((sum,x)=>sum+x.capacity*x.count,0);
  const roomCount = selectedRooms.reduce((sum,x)=>sum+x.count,0);
  const estimatedTotal = selectedRooms.reduce((sum,x)=>sum+x.price*x.count,0);
  const fieldStyle = { width: "100%", minHeight: 52, boxSizing: "border-box", border: `1px solid ${T.hairlineStrong}`, borderRadius: 13, padding: "0 14px", background: T.surfaceAlt, color: T.text, font: "500 14px Alexandria", outline: "none" };
  const requestCode = async () => {
    if (form.fullName.trim().length < 3 || (form.email.trim() && !/^\S+@\S+\.\S+$/.test(form.email)) || !/^5\d{8}$/.test(form.phone)) {
      setMessage(rtl ? "أدخل الاسم الكامل ورقم جوال صحيحًا. البريد الإلكتروني اختياري." : "Enter your full name and a valid mobile number. Email is optional."); return;
    }
    if (!roomCount || roomCapacity < totalTravelers) { setMessage(rtl?`اختر غرفًا تستوعب ${totalTravelers} أشخاص على الأقل.`:`Select rooms for at least ${totalTravelers} guests.`); return; }
    if (Number(pkg?.availableSeats ?? pkg?.seats ?? 0) < totalTravelers) { setMessage(rtl?`لا توجد سعة كافية. المتاح حاليًا ${Number(pkg?.availableSeats||0)} فقط. اختر عددًا أقل أو باقة أخرى.`:`Not enough capacity. Only ${Number(pkg?.availableSeats||0)} places remain.`); return; }
    setBusy(true); setMessage("");
    try {
      const currentUser=firebase.auth().currentUser,currentPhone=String(currentUser?.phoneNumber||"").replace(/\D/g,"").replace(/^966/,"");
      if(currentUser&&currentPhone===form.phone){
        const idToken=await currentUser.getIdToken(true);
        localStorage.setItem("duyuf_customer",JSON.stringify({phone:currentUser.phoneNumber}));
        setFirebaseIdToken(idToken);setStep("review");return;
      }
      if(currentUser&&currentPhone!==form.phone){
        throw new Error("different_signed_in_phone");
      }
      const storedSession=localStorage.getItem("duyuf_provider_session")||"";
      if(!currentUser&&storedSession){
        const sessionResponse=await fetch(`${window.DUYUF_API_URL}/v1/provider/packages`,{headers:{authorization:`Bearer ${storedSession}`}});
        const sessionBody=await sessionResponse.json().catch(()=>({}));
        const sessionPhone=String(sessionBody?.provider?.phone||"").replace(/\D/g,"").replace(/^966/,"");
        if(sessionResponse.ok&&sessionPhone===form.phone){setProviderSessionToken(storedSession);setStep("review");return;}
      }
      const storedAdminSession=localStorage.getItem("duyuf_admin_session")||"";
      const storedAdmin=(()=>{try{return JSON.parse(localStorage.getItem("duyuf_admin")||"null");}catch(_){return null;}})();
      const storedAdminPhone=String(storedAdmin?.phone||"").replace(/\D/g,"").replace(/^966/,"");
      if(!currentUser&&storedAdminSession&&storedAdminPhone===form.phone){setAdminSessionToken(storedAdminSession);setStep("review");return;}
      if (window.duyufCheckoutRecaptcha) window.duyufCheckoutRecaptcha.clear();
      const recaptchaHost=document.getElementById("duyuf-checkout-recaptcha");
      if(recaptchaHost)recaptchaHost.replaceChildren();
      firebase.auth().languageCode=rtl?"ar":"en";
      window.duyufCheckoutRecaptcha = new firebase.auth.RecaptchaVerifier("duyuf-checkout-recaptcha",{size:"invisible"});
      await window.duyufCheckoutRecaptcha.render();
      window.duyufCheckoutConfirmation = await firebase.auth().signInWithPhoneNumber(`+966${form.phone}`,window.duyufCheckoutRecaptcha);
      setStep("otp");
    } catch (error) { console.error("Checkout OTP failed",error); const errorCode=String(error?.code||error?.message||"unknown").replace(/^auth\//,""); setMessage(error.message==="different_signed_in_phone"?(rtl?"أنت مسجل الدخول برقم جوال مختلف. استخدم الرقم المسجل حاليًا أو سجل الخروج أولًا.":"You are signed in with a different mobile number. Use it or sign out first."):(rtl ? `تعذر إرسال رمز التحقق (${errorCode}).` : `Could not send the verification code (${errorCode}).`)); }
    finally { setBusy(false); }
  };
  const verifyCode = async (codeValue=otp) => {
    if (otpVerifyingRef.current) return;
    if (!/^\d{6}$/.test(codeValue)) { setMessage(rtl ? "أدخل رمز التحقق المكوّن من 6 أرقام." : "Enter the 6-digit code."); return; }
    otpVerifyingRef.current=true;
    setBusy(true); setMessage("");
    try {
      if (!window.duyufCheckoutConfirmation) throw new Error("missing_confirmation");
      const credential = await window.duyufCheckoutConfirmation.confirm(codeValue);
      const idToken = await credential.user.getIdToken(true);
      localStorage.setItem("duyuf_customer",JSON.stringify({phone:credential.user.phoneNumber}));
      setFirebaseIdToken(idToken); setStep("review");
    } catch (_) { setMessage(rtl ? "رمز التحقق غير صحيح أو انتهت صلاحيته." : "The verification code is invalid or expired."); }
    finally { setBusy(false); otpVerifyingRef.current=false; }
  };
  const confirmBooking = async () => {
    if (pkg?.paymentConfirmationMode === "prepay_required") {
      setMessage(rtl ? "يتطلب هذا العرض الدفع مسبقًا لتأكيد الحجز. سيتم إتاحة المتابعة عند تفعيل بوابة الدفع." : "This offer requires prepayment. Checkout will be available when online payment is enabled.");
      return;
    }
    setBusy(true); setMessage("");
    try {
      const r = await fetch(`${window.DUYUF_API_URL}/v1/public/bookings`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ packageId: pkg?.id, ...form, phone: `+966${form.phone}`, firebaseIdToken,providerSessionToken,adminSessionToken }) });
      const b = await r.json(); if (!r.ok || !b.booking) throw new Error(b.error);
      localStorage.setItem("duyuf_last_booking", JSON.stringify(b.booking));
      setBookingConfirmation(b.booking); setPage("booking-confirmation");
    } catch (error) { setMessage(error.message === "insufficient_capacity" ? (rtl ? "لا توجد سعة كافية لهذا العدد." : "Not enough capacity.") : (rtl ? "تعذر إتمام الحجز. حاول مرة أخرى." : "Could not complete the booking.")); }
    finally { setBusy(false); }
  };
  const counter = (key, label, min = 0) => <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 14px", border: `1px solid ${T.hairline}`, borderRadius: 12 }}><strong style={{ color: T.text, font: "600 13px Alexandria" }}>{label}</strong><div style={{ display: "flex", alignItems: "center", gap: 12 }}><button type="button" onClick={() => setForm(v => ({ ...v, [key]: Math.max(min, v[key] - 1) }))} style={{ width: 34, height: 34, borderRadius: 9, border: `1px solid ${T.hairlineStrong}`, background: T.surface, color: T.text }}>−</button><b>{form[key]}</b><button type="button" onClick={() => setForm(v => ({ ...v, [key]: Math.min(20, v[key] + 1) }))} style={{ width: 34, height: 34, borderRadius: 9, border: 0, background: T.primary, color: "#fff" }}>+</button></div></div>;
  const steps = [["details", rtl ? "البيانات" : "Details"], ["otp", rtl ? "التحقق" : "Verify"], ["review", rtl ? "المراجعة" : "Review"]];
  return (
    <div style={{ minHeight: 650, background: T.bg, padding: "28px 16px 80px" }}>
      <main style={{ maxWidth: 760, margin: "0 auto", padding: "clamp(20px,5vw,34px)", background: T.surface, border: `1px solid ${T.hairline}`, borderRadius: 22, boxShadow: T.cardShadow }}>
        <button type="button" onClick={() => setPage("detail")} style={{ border: 0, background: "transparent", color: T.textMuted, cursor: "pointer" }}>→ {rtl ? "العودة إلى الباقة" : "Back to package"}</button>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, margin: "20px 0 28px" }}>{steps.map(([id,label],i) => { const current = steps.findIndex(x => x[0] === step); return <div key={id} style={{ textAlign: "center" }}><div style={{ height: 5, borderRadius: 99, background: i <= current ? T.primary : T.hairlineStrong }} /><small style={{ display: "block", marginTop: 7, color: i <= current ? T.primary : T.textMuted }}>{label}</small></div>; })}</div>
        <h1 style={{ color: T.text, font: "700 27px Alexandria", marginBottom: 6 }}>{step === "details" ? (rtl ? "بيانات الحجز" : "Booking details") : step === "otp" ? (rtl ? "تحقق من رقم الجوال" : "Verify mobile") : (rtl ? "راجع طلبك" : "Review booking")}</h1>
        <p style={{ color: T.textMuted, font: "400 13px/1.8 Alexandria" }}>{pkg?.title} · {pkg?.hotel}</p>
        <div id="duyuf-checkout-recaptcha" />
        {step === "details" && <div style={{ display: "grid", gap: 14 }}><div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))", gap: 12 }}><input aria-label={rtl ? "الاسم الكامل" : "Full name"} placeholder={rtl ? "الاسم الكامل" : "Full name"} value={form.fullName} onChange={e=>setForm(v=>({...v,fullName:e.target.value}))} style={fieldStyle}/><input aria-label={rtl ? "البريد الإلكتروني اختياري" : "Email optional"} type="email" placeholder={rtl?"البريد الإلكتروني (اختياري)":"Email (optional)"} value={form.email} onChange={e=>setForm(v=>({...v,email:e.target.value}))} style={fieldStyle}/><label style={{ display:"flex",direction:"ltr",alignItems:"center",border:`1px solid ${T.hairlineStrong}`,borderRadius:13,background:T.surfaceAlt,overflow:"hidden" }}><span style={{ padding:"0 12px",color:T.text,font:"600 14px Alexandria" }}>+966</span><input aria-label={rtl ? "رقم الجوال" : "Mobile number"} inputMode="numeric" maxLength={9} placeholder={rtl?"رقم الجوال":"Mobile number"} value={form.phone} onChange={e=>setForm(v=>({...v,phone:e.target.value.replace(/\D/g,"").slice(0,9)}))} style={{...fieldStyle,border:0,borderRadius:0,paddingInlineStart:0}}/></label></div><div style={{ display:"grid",gap:8 }}>{counter("adults",rtl?"البالغون":"Adults",1)}{counter("children",rtl?"الأطفال":"Children")}{counter("infants",rtl?"الرضّع":"Infants")}</div><div style={{padding:16,border:`1px solid ${T.hairline}`,borderRadius:15,display:"grid",gap:10}}><strong style={{color:T.text}}>{rtl?"الغرف المطلوبة":"Required rooms"}</strong>{availableRooms.map(room=><div key={room.key} style={{display:"flex",justifyContent:"space-between",alignItems:"center",gap:10}}><span style={{color:T.text,font:"600 13px Alexandria"}}>{rtl?`غرفة ${room.ar}`:room.en} · {room.price.toLocaleString()} SAR</span><div style={{display:"flex",alignItems:"center",gap:10}}><button type="button" onClick={()=>setForm(v=>({...v,rooms:{...v.rooms,[room.key]:Math.max(0,(v.rooms?.[room.key]||0)-1)}}))} style={{width:34,height:34,borderRadius:9,border:`1px solid ${T.hairlineStrong}`,background:T.surface}}>−</button><b>{form.rooms?.[room.key]||0}</b><button type="button" onClick={()=>setForm(v=>({...v,rooms:{...v.rooms,[room.key]:Math.min(20,(v.rooms?.[room.key]||0)+1)}}))} style={{width:34,height:34,borderRadius:9,border:0,background:T.primary,color:"#fff"}}>+</button></div></div>)}{pkg?.roomOptions?.length>0&&<select value={form.roomPreference} onChange={e=>setForm(v=>({...v,roomPreference:e.target.value}))} style={fieldStyle}><option value="">{rtl?"تفضيل الغرفة أو الإطلالة (اختياري)":"Room or view preference (optional)"}</option>{pkg.roomOptions.map((option,i)=><option key={i} value={option.name}>{option.name}{option.boardType?` · ${option.boardType}`:""}</option>)}</select>}<div style={{paddingTop:10,borderTop:`1px solid ${T.hairline}`,display:"flex",justifyContent:"space-between",color:roomCapacity<totalTravelers?"#b42318":T.text}}><span>{rtl?`${roomCount} غرفة · سعة ${roomCapacity} أشخاص`:`${roomCount} rooms · capacity ${roomCapacity}`}</span><strong>{estimatedTotal.toLocaleString()} SAR</strong></div></div><button disabled={busy} onClick={requestCode} style={{ minHeight:54,border:0,borderRadius:13,background:T.primary,color:"#fff",font:"700 15px Alexandria" }}>{busy?(rtl?"جارٍ الإرسال…":"Sending…"):(rtl?"إرسال رمز التحقق":"Send verification code")}</button></div>}
        {step === "otp" && <div style={{ display:"grid",gap:16 }}><div style={{ padding:15,borderRadius:13,background:T.camelMist,color:T.text,font:"600 13px/1.8 Alexandria" }}>{rtl?<>أرسلنا رمزًا إلى <b dir="ltr" style={{display:"inline-block"}}>+966 {form.phone}</b></>:<>We sent a code to <b dir="ltr">+966 {form.phone}</b></>}</div><input autoFocus name="one-time-code" aria-label={rtl?"رمز التحقق":"Verification code"} inputMode="numeric" pattern="[0-9]*" autoComplete="one-time-code" enterKeyHint="done" maxLength={6} value={otp} onChange={e=>{const next=e.target.value.replace(/\D/g,"").slice(0,6);setOtp(next);if(next.length===6)setTimeout(()=>verifyCode(next),0);}} placeholder="• • • • • •" style={{...fieldStyle,textAlign:"center",fontSize:24,letterSpacing:8,direction:"ltr"}}/><button disabled={busy} onClick={()=>verifyCode()} style={{ minHeight:54,border:0,borderRadius:13,background:T.primary,color:"#fff",font:"700 15px Alexandria" }}>{busy?(rtl?"جارٍ التحقق…":"Verifying…"):(rtl?"تحقق ومتابعة":"Verify and continue")}</button><button onClick={requestCode} style={{border:0,background:"transparent",color:T.primary}}>{rtl?"إعادة إرسال الرمز":"Resend code"}</button></div>}
        {step === "review" && <div style={{ display:"grid",gap:14 }}><div style={{ padding:18,borderRadius:15,border:`1px solid ${T.hairline}`,display:"grid",gap:9,color:T.text,font:"500 13px/1.8 Alexandria" }}><strong>{form.fullName}</strong><span dir="ltr" style={{textAlign:rtl?"right":"left"}}>+966 {form.phone}{form.email?` · ${form.email}`:""}</span><span>{rtl?"المسافرون":"Travelers"}: {form.adults} {rtl?"بالغ":"adult"} · {form.children} {rtl?"طفل":"child"} · {form.infants} {rtl?"رضيع":"infant"}</span><span>{rtl?"الغرف":"Rooms"}: {selectedRooms.map(x=>`${x.count}× ${rtl?x.ar:x.en}`).join(" · ")}</span>{form.roomPreference&&<span>{rtl?"تفضيل الغرفة":"Room preference"}: {form.roomPreference}</span>}<span>{rtl?"الفندق":"Hotel"}: <b>{pkg?.hotel||"—"}</b></span><span>{rtl?"الإقامة":"Stay"}: {pkg?.nights||pkg?.durationDays||"—"} {rtl?"ليالٍ":"nights"} · {pkg?.mealPlan||"—"}</span><span>{rtl?"مسار الرحلة":"Route"}: {pkg?.originCity||"—"} ← {pkg?.destinationCity||pkg?.flightArrivalCity||"—"}</span><span>{rtl?"موعد الانطلاق":"Departure"}: {pkg?.departureAt?new Date(pkg.departureAt).toLocaleString(rtl?"ar-SA":"en-US"):"—"}</span><span>{rtl?"موعد العودة":"Return"}: {pkg?.returnAt?new Date(pkg.returnAt).toLocaleString(rtl?"ar-SA":"en-US"):"—"}</span>{pkg?.flightNumber&&<span>{rtl?"رحلة الذهاب":"Outbound flight"}: {pkg.airline||"—"} · {pkg.flightNumber}</span>}{pkg?.returnFlightNumber&&<span>{rtl?"رحلة العودة":"Return flight"}: {pkg.returnAirline||"—"} · {pkg.returnFlightNumber}</span>}<span>{rtl?"إجمالي الحجز":"Booking total"}: <b>{estimatedTotal.toLocaleString()} SAR</b></span><span>{rtl?"طريقة السداد":"Payment method"}: <b>{pkg?.paymentConfirmationMode==="prepay_required"?(rtl?"الدفع مسبقًا لتأكيد الحجز":"Prepayment required"):(rtl?"الدفع عند الوصول":"Pay on arrival")}</b></span>{pkg?.cancellationPolicy&&<span style={{paddingTop:8,borderTop:`1px solid ${T.hairline}`}}>{rtl?"سياسة الإلغاء":"Cancellation policy"}: {pkg.cancellationPolicy}</span>}</div><div style={{padding:13,borderRadius:12,background:T.camelMist,color:T.textMuted,font:"500 12px/1.7 Alexandria"}}>{rtl?"بعد إتمام الحجز سيصدر رقم التأكيد ويمكنك تنزيل نموذج PDF الرسمي.":"After completion, a confirmation number and official PDF will be available."}</div><button disabled={busy||pkg?.paymentConfirmationMode==="prepay_required"} onClick={confirmBooking} style={{ minHeight:56,border:0,borderRadius:13,background:T.primary,color:"#fff",font:"700 15px Alexandria",opacity:pkg?.paymentConfirmationMode==="prepay_required"?.55:1 }}>{busy?(rtl?"جارٍ إتمام الحجز…":"Completing…"):(rtl?"إتمام الحجز":"Complete booking")}</button>{pkg?.paymentConfirmationMode==="prepay_required"&&<p style={{margin:0,color:"#9a3412",font:"600 12px/1.7 Alexandria"}}>{rtl?"يتطلب هذا العرض الدفع قبل إصدار تأكيد الحجز.":"Payment is required before this booking can be confirmed."}</p>}</div>}
        {message && <p style={{ marginTop:14,color:"#b42318",font:"600 12px Alexandria" }}>{message}</p>}
      </main>
    </div>
  );
}

function WebBookingConfirmationPage({ theme, lang }) {
  const T = theme, rtl = isRTL(lang), { bookingConfirmation, setPage } = useWeb();
  const booking = bookingConfirmation || (() => { try { return JSON.parse(localStorage.getItem("duyuf_last_booking") || "null"); } catch (_) { return null; } })();
  const [busy, setBusy] = React.useState(false);
  const voucherRef = React.useRef(null);
  if (!booking) return <div style={{ minHeight:600,display:"grid",placeItems:"center",background:T.bg }}><button onClick={()=>setPage("home")}>{rtl?"العودة للرئيسية":"Back home"}</button></div>;
  const p = booking.package || {};
  const formatDate = value => value ? new Date(value).toLocaleString(rtl ? "ar-SA" : "en-US", { dateStyle:"medium", timeStyle:value.includes?.("T")?"short":undefined }) : "—";
  const downloadPdf = async () => {
    setBusy(true);
    try {
      const url=`${window.DUYUF_API_URL}/v1/public/bookings/${encodeURIComponent(booking.bookingReference)}/pdf?token=${encodeURIComponent(booking.publicToken)}`;
      const response=await fetch(url);
      if(!response.ok) throw new Error("pdf_failed");
      const blob=await response.blob(),objectUrl=URL.createObjectURL(blob),link=document.createElement("a");
      link.href=objectUrl;link.download=`Duyuf-${booking.bookingReference}.pdf`;document.body.appendChild(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(objectUrl),30000);
    } finally { setBusy(false); }
  };
  const row = (label,value) => <div style={{ display:"grid",gap:3 }}><span style={{ color:"#7b7168",fontSize:12 }}>{label}</span><strong style={{ color:"#1f1b17",fontSize:15 }}>{value || "—"}</strong></div>;
  const milestones = p.travelMode === "flight" ? [
    { title:rtl?"رحلة الذهاب":"Outbound flight", detail:`${rtl?"من":"From"} ${p.originCity||"—"} ${rtl?"إلى":"to"} ${p.flightArrivalCity||"—"} · ${p.airline||"—"} · ${p.flightNumber||"—"}`, date:formatDate(p.departureAt) },
    { title:rtl?"الوصول والانتقال إلى الفندق":"Arrival and hotel transfer", detail:p.airportTransferType||"—", date:p.flightArrivalCity||"—" },
    { title:rtl?"الإقامة":"Hotel stay", detail:`${p.hotel||"—"} · ${p.roomType||"—"}`, date:`${p.durationDays||"—"} ${rtl?"أيام":"days"}` },
    { title:rtl?"المغادرة من الفندق":"Hotel checkout", detail:p.hotel||"—", date:formatDate(p.returnAt) },
    { title:rtl?"رحلة العودة":"Return flight", detail:`${rtl?"من":"From"} ${p.returnOriginCity||"—"} ${rtl?"إلى":"to"} ${p.returnDestinationCity||"—"} · ${p.returnAirline||"—"} · ${p.returnFlightNumber||"—"}`, date:formatDate(p.returnDepartureAt) },
  ] : [
    { title:rtl?"الانطلاق بالنقل البري":"Ground transport departure", detail:`${rtl?"من":"From"} ${p.originCity||"—"} ${rtl?"إلى":"to"} ${p.destinationCity||"—"} · ${p.busType||"—"}`, date:formatDate(p.departureAt) },
    { title:rtl?"الوصول والإقامة":"Arrival and stay", detail:`${p.hotel||"—"} · ${p.roomType||"—"}`, date:`${p.durationDays||"—"} ${rtl?"أيام":"days"}` },
    { title:rtl?"العودة":"Return", detail:p.destinationCity||"—", date:formatDate(p.returnAt) },
  ];
  return <div style={{ minHeight:700,background:T.bg,padding:"28px 12px 80px" }}>
    <div className="duyuf-voucher-actions" style={{ maxWidth:794,margin:"0 auto 18px",display:"flex",justifyContent:"space-between",gap:10,flexWrap:"wrap" }}><button onClick={()=>setPage("home")} style={{padding:"11px 16px",border:`1px solid ${T.hairlineStrong}`,borderRadius:11,background:T.surface,color:T.text}}>{rtl?"العودة للرئيسية":"Back home"}</button><button disabled={busy} onClick={downloadPdf} style={{padding:"12px 20px",border:0,borderRadius:11,background:T.primary,color:"#fff",font:"700 13px Alexandria"}}>{busy?(rtl?"جارٍ تجهيز الملف…":"Preparing…"):(rtl?"تحميل PDF":"Download PDF")}</button></div>
    <section className="duyuf-mobile-confirmation" dir={rtl?"rtl":"ltr"}>
      <div className="duyuf-confirmation-card" style={{textAlign:"center"}}><DuyufWordmark height={42} color="#1f1b17" lang={rtl?"ar":"en"}/><span style={{display:"inline-flex",marginTop:14,padding:"7px 13px",borderRadius:99,background:"#eaf7ef",color:"#237a4b",fontWeight:700}}>✓ {rtl?"تم تأكيد حجزك":"Booking confirmed"}</span><h1 style={{margin:"16px 0 5px",fontSize:25,color:T.text}}>{p.title}</h1><p style={{margin:0,color:T.textMuted}}>{p.provider} · {p.hotel}</p><strong dir="ltr" style={{display:"block",marginTop:12,fontSize:13}}>{booking.bookingReference}</strong></div>
      <div className="duyuf-confirmation-card"><h2 style={{margin:"0 0 14px",fontSize:20}}>{rtl?"ملخص الحجز":"Booking summary"}</h2><div className="duyuf-confirmation-grid"><div><span>{rtl?"الاسم الكامل":"Full name"}</span><strong>{booking.customerName}</strong></div><div><span>{rtl?"رقم الجوال":"Mobile"}</span><strong dir="ltr">{booking.customerPhone}</strong></div><div><span>{rtl?"المسافرون":"Travelers"}</span><strong>{booking.adults} {rtl?"بالغ":"adult"} · {booking.children} {rtl?"طفل":"child"}</strong></div><div><span>{rtl?"الغرف":"Rooms"}</span><strong>{booking.rooms?.map(x=>`${x.count}× ${rtl?({single:"مفردة",double:"مزدوجة",triple:"ثلاثية",quad:"رباعية"}[x.type]||x.type):x.type}`).join(" · ")}</strong></div><div><span>{rtl?"طريقة السداد":"Payment"}</span><strong>{rtl?"الدفع عند الوصول":"Pay on arrival"}</strong></div><div><span>{rtl?"تاريخ التأكيد":"Confirmed"}</span><strong>{new Date(booking.confirmedAt).toLocaleDateString(rtl?"ar-SA":"en-US")}</strong></div></div></div>
      <div className="duyuf-confirmation-card"><h2 style={{margin:"0 0 16px",fontSize:20,color:T.primary}}>{rtl?"برنامج الرحلة":"Trip itinerary"}</h2><div className="duyuf-confirmation-timeline">{milestones.map((m,i)=><div key={i}><strong style={{display:"block",fontSize:14}}>{m.title}</strong><span style={{display:"block",color:T.textMuted,fontSize:12,lineHeight:1.7}}>{m.detail}</span><small style={{color:T.primary}}>{m.date}</small></div>)}</div></div>
      <div className="duyuf-confirmation-total"><div><small>{rtl?"إجمالي الحجز":"Total"}</small><strong dir="ltr" style={{display:"block",fontSize:20}}>{Number(booking.totalAmount).toLocaleString()} SAR</strong></div><div><small>{rtl?"المبلغ المتبقي":"Amount due"}</small><strong dir="ltr" style={{display:"block",fontSize:20}}>{Number(booking.balanceAmount??booking.totalAmount).toLocaleString()} SAR</strong></div></div>
    </section>
    <div className="duyuf-voucher-shell"><article className="duyuf-voucher duyuf-voucher-preview" ref={voucherRef} dir={rtl?"rtl":"ltr"} style={{ width:794,height:1123,boxSizing:"border-box",margin:"0 auto",padding:"52px 58px 40px",background:"#fff",color:"#1f1b17",fontFamily:'Alexandria,"Sakkal Majalla",sans-serif',position:"relative",overflow:"hidden",boxShadow:"0 18px 50px rgba(31,27,23,.12)",letterSpacing:0 }}>
      <div style={{position:"absolute",insetInlineStart:0,top:0,width:12,height:"100%",background:"#c19872"}} />
      <header style={{display:"flex",justifyContent:"space-between",alignItems:"flex-start",paddingBottom:24,borderBottom:"2px solid #c19872"}}><div><DuyufWordmark height={46} color="#1f1b17" lang={rtl?"ar":"en"} /><div style={{color:"#8c6e53",fontSize:14,marginTop:5}}>DUYUF · {rtl?"رحلة موثوقة إلى بيت الله":"A trusted journey"}</div></div><div style={{textAlign:rtl?"left":"right"}}><span style={{display:"inline-flex",padding:"8px 16px",borderRadius:99,background:"#eaf7ef",color:"#237a4b",fontWeight:700}}>✓ {rtl?"حجز مؤكد":"Confirmed"}</span><div style={{marginTop:10,fontFamily:"Alexandria",fontSize:12,direction:"ltr"}}>{booking.bookingReference}</div></div></header>
      <section style={{padding:"26px 0 18px"}}><h1 style={{margin:0,fontFamily:'"Sakkal Majalla",Alexandria,sans-serif',fontSize:37,lineHeight:1.15,letterSpacing:0}}>{rtl?"تأكيد حجز باقة عمرة":"Umrah Package Booking Confirmation"}</h1><p style={{margin:"6px 0 0",color:"#766d65",fontSize:15}}>{p.title} · {p.provider}</p></section>
      <section style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:18,padding:20,borderRadius:15,background:"#faf7f2",border:"1px solid #eadfd3"}}>{row(rtl?"الاسم الكامل":"Full name",booking.customerName)}{row(rtl?"رقم الجوال":"Mobile",booking.customerPhone)}{booking.customerEmail?row(rtl?"البريد الإلكتروني":"Email",booking.customerEmail):null}{row(rtl?"المسافرون":"Travelers",`${booking.travelers} (${booking.adults}/${booking.children}/${booking.infants})`)}{booking.rooms?.length?row(rtl?"الغرف":"Rooms",booking.rooms.map(x=>`${x.count}× ${rtl?({single:"مفردة",double:"مزدوجة",triple:"ثلاثية",quad:"رباعية"}[x.type]||x.type):x.type}`).join(" · ")):null}{row(rtl?"طريقة السداد":"Payment method",rtl?"الدفع عند الوصول":"Pay on arrival")}{row(rtl?"تاريخ التأكيد":"Confirmed",new Date(booking.confirmedAt).toLocaleString(rtl?"ar-SA":"en-US"))}</section>
      <section style={{marginTop:24}}><h2 style={{margin:"0 0 12px",fontSize:21,color:"#8c6e53"}}>{rtl?"تفاصيل الباقة":"Package details"}</h2><div style={{display:"grid",gridTemplateColumns:"repeat(3,1fr)",gap:"16px 24px",paddingBottom:20,borderBottom:"1px solid #e7ded5"}}>{row(rtl?"الفندق":"Hotel",p.hotel)}{row(rtl?"نوع الغرفة":"Room",p.roomType)}{row(rtl?"الإعاشة":"Meals",p.mealPlan)}{row(rtl?"المدة":"Duration",`${p.durationDays||"—"} ${rtl?"أيام":"days"}`)}{row(rtl?"الانطلاق":"Departure",formatDate(p.departureAt))}{row(rtl?"العودة":"Return",formatDate(p.returnAt))}</div></section>
      <section style={{marginTop:22}}><h2 style={{margin:"0 0 12px",fontFamily:'"Sakkal Majalla",Alexandria,sans-serif',fontSize:27,lineHeight:1.1,letterSpacing:0,color:"#8c6e53"}}>{rtl?"برنامج الرحلة":"Trip itinerary"}</h2><div style={{position:"relative",paddingInlineStart:28}}><div style={{position:"absolute",insetInlineStart:7,top:8,bottom:8,width:2,background:"#d7b89a"}} />{milestones.map((m,i)=><div key={i} style={{position:"relative",display:"grid",gridTemplateColumns:"1fr auto",gap:14,paddingBottom:i===milestones.length-1?0:13}}><span style={{position:"absolute",insetInlineStart:-27,top:5,width:14,height:14,boxSizing:"border-box",borderRadius:"50%",background:i===0?"#c19872":"#fff",border:"3px solid #c19872"}} /><div><strong style={{display:"block",fontSize:14}}>{m.title}</strong><span style={{display:"block",marginTop:2,color:"#6f665e",fontSize:12,lineHeight:1.55}}>{m.detail}</span></div><span style={{color:"#8c6e53",fontSize:11,whiteSpace:"nowrap",paddingTop:2}}>{m.date}</span></div>)}</div></section>
      <section style={{marginTop:22,display:"flex",justifyContent:"space-between",alignItems:"center",padding:"18px 20px",borderRadius:14,background:"#1f1b17",color:"#fff"}}><div><span style={{display:"block",opacity:.7,fontSize:12}}>{rtl?"إجمالي الحجز":"Booking total"}</span><strong style={{fontFamily:"Alexandria",fontSize:24}}>{Number(booking.totalAmount).toLocaleString()} SAR</strong></div><div style={{textAlign:rtl?"left":"right"}}><span style={{display:"block",opacity:.7,fontSize:12}}>{rtl?"المبلغ المتبقي":"Amount due"}</span><strong style={{fontFamily:"Alexandria",fontSize:22}}>{Number(booking.balanceAmount ?? booking.totalAmount).toLocaleString()} SAR</strong></div></section>
      <footer style={{position:"absolute",insetInlineStart:58,insetInlineEnd:58,bottom:38,paddingTop:16,borderTop:"1px solid #e7ded5",display:"flex",justifyContent:"space-between",gap:20,color:"#7b7168",fontSize:12}}><span>{rtl?"يرجى إبراز هذا التأكيد عند الطلب. تطبق سياسة المزود وشروط الباقة.":"Present this confirmation when requested. Provider terms apply."}</span><span style={{direction:"ltr",whiteSpace:"nowrap"}}>duyufsa.com · +966 55 614 7561</span></footer>
    </article></div>
  </div>;
}

function WebPaymentResultPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb();
  const orderId =
    new URLSearchParams(window.location.search).get("order") || "";
  const [status, setStatus] = React.useState(null);
  React.useEffect(() => {
    if (orderId)
      fetch(
        `${window.DUYUF_API_URL}/v1/payments/status?order=${encodeURIComponent(orderId)}`,
      )
        .then((r) => r.json())
        .then((b) => setStatus(b.order?.status || "pending"))
        .catch(() => setStatus("pending"));
  }, [orderId]);
  return (
    <div
      style={{
        minHeight: 620,
        display: "grid",
        placeItems: "center",
        padding: 20,
        background: T.bg,
      }}
    >
      <div
        style={{
          maxWidth: 560,
          width: "100%",
          textAlign: "center",
          padding: "38px 24px",
          borderRadius: 20,
          background: T.surface,
          border: `1px solid ${T.hairline}`,
        }}
      >
        <div style={{ fontSize: 42 }}>⌛</div>
        <h1 style={{ color: T.text, font: "700 25px Alexandria" }}>
          {rtl ? "جارٍ التحقق من عملية السداد" : "Verifying payment"}
        </h1>
        <p style={{ color: T.textMuted, font: "400 13px/1.8 Alexandria" }}>
          {rtl
            ? "لا نعتبر العملية ناجحة حتى يصل تأكيد آمن من بوابة الدفع. يمكنك العودة للموقع الآن."
            : "The payment is not considered successful until a secure gateway confirmation arrives."}
        </p>
        {orderId && (
          <p
            style={{
              color: T.textFaint,
              font: "400 11px Alexandria",
              overflowWrap: "anywhere",
            }}
          >
            {orderId} · {status || "..."}
          </p>
        )}
        <button
          onClick={() => setPage("home")}
          style={{
            marginTop: 14,
            padding: "12px 22px",
            border: 0,
            borderRadius: 12,
            background: T.primary,
            color: "#fff",
            font: "700 14px Alexandria",
          }}
        >
          {rtl ? "العودة للرئيسية" : "Back home"}
        </button>
      </div>
    </div>
  );
}

// ─── Become provider page ──────────────────────────────────────────────
function WebProviderSignupPage({ theme, lang }) {
  const T = theme;
  const l = L[lang];
  const rtl = isRTL(lang);
  const { setPage } = useWeb();
  const [businessName, setBusinessName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [otp, setOtp] = React.useState("");
  const [step, setStep] = React.useState("details");
  const [busy, setBusy] = React.useState(false);
  const [message, setMessage] = React.useState("");
  const verifyingRef = React.useRef(false);

  const normalizeSaudiPhone = (value) => {
    const digits = String(value || "").replace(/\D/g, "");
    if (/^05\d{8}$/.test(digits)) return `+966${digits.slice(1)}`;
    if (/^9665\d{8}$/.test(digits)) return `+${digits}`;
    if (/^5\d{8}$/.test(digits)) return `+966${digits}`;
    return "";
  };

  const sendOtp = async () => {
    const formattedPhone = normalizeSaudiPhone(phone);
    if (!businessName.trim() || !formattedPhone) {
      setMessage(
        rtl
          ? "أدخل الاسم التجاري ورقم جوال سعودي صحيح."
          : "Enter a business name and valid Saudi mobile.",
      );
      return;
    }
    setBusy(true);
    setMessage("");
    try {
      if (window.duyufRecaptcha) window.duyufRecaptcha.clear();
      window.duyufRecaptcha = new firebase.auth.RecaptchaVerifier(
        "duyuf-recaptcha",
        { size: "invisible" },
      );
      window.duyufConfirmation = await firebase
        .auth()
        .signInWithPhoneNumber(formattedPhone, window.duyufRecaptcha);
      setStep("otp");
      setMessage(
        rtl
          ? "أرسلنا رمز التحقق إلى جوالك."
          : "We sent a verification code to your phone.",
      );
    } catch (error) {
      console.error(error);
      setMessage(
        rtl
          ? "تعذّر إرسال الرمز. تأكد من تفعيل Phone وإضافة الدومين في Firebase."
          : "Could not send code. Check Phone Auth and Firebase authorized domains.",
      );
    } finally {
      setBusy(false);
    }
  };

  const verifyOtp = async (codeValue = otp) => {
    if (
      !/^\d{6}$/.test(codeValue) ||
      !window.duyufConfirmation ||
      verifyingRef.current
    )
      return;
    verifyingRef.current = true;
    setBusy(true);
    setMessage("");
    let credential;
    try {
      credential = await window.duyufConfirmation.confirm(codeValue);
    } catch (error) {
      console.error("Firebase OTP confirmation failed", error);
      setMessage(
        rtl
          ? "الرمز غير صحيح أو انتهت صلاحيته. اطلب رمزاً جديداً."
          : "The code is invalid or expired. Request a new one.",
      );
      setBusy(false);
      verifyingRef.current = false;
      return;
    }
    try {
      const idToken = await credential.user.getIdToken(true);
      const response = await fetch(
        `${window.DUYUF_API_URL}/v1/auth/firebase-provider`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ idToken, businessName: businessName.trim() }),
        },
      );
      const result = await response.json();
      if (!response.ok || !result.ok)
        throw new Error(result.error || "provider_login_failed");
      localStorage.setItem("duyuf_provider_session", result.sessionToken);
      localStorage.setItem("duyuf_provider", JSON.stringify(result.provider));
      setPage("provider-dashboard");
    } catch (error) {
      console.error("Provider account creation failed", error);
      setMessage(
        rtl
          ? "تم توثيق الجوال، لكن تعذّر إنشاء حساب المزود. حاول مرة أخرى دون طلب رمز جديد."
          : "Phone verified, but provider account creation failed. Try again without requesting a new code.",
      );
    } finally {
      setBusy(false);
      verifyingRef.current = false;
    }
  };

  return (
    <>
      <WebPageHeader
        theme={T}
        lang={lang}
        tone="ink"
        eyebrow={rtl ? "انضم إلى ضيوف" : "Join Duyuf"}
        title={
          rtl
            ? "ابدأ في بيع باقاتك خلال أيام"
            : "Start selling your packages in days"
        }
        sub={
          rtl
            ? "سجّل ببياناتك التجارية، ابعث المستندات المطلوبة، واحصل على لوحة إدارة وتطبيق تشغيل بمجرد الموافقة."
            : "Register with your business details, send the required documents, and get a dashboard + ops app upon approval."
        }
      />

      <WebBecomeProvider theme={T} lang={lang} />

      <div style={{ padding: "60px 32px", background: T.bg }}>
        <div
          style={{
            maxWidth: 1100,
            margin: "0 auto",
            display: "grid",
            gridTemplateColumns: "1fr 1fr",
            gap: 40,
          }}
        >
          {/* Form */}
          <div
            style={{
              background: T.surface,
              border: `1px solid ${T.hairline}`,
              borderRadius: 20,
              padding: 32,
            }}
          >
            <h2
              style={{
                margin: 0,
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 22,
                color: T.text,
                letterSpacing: "-0.01em",
              }}
            >
              {rtl ? "بيانات الشركة" : "Company information"}
            </h2>
            <p
              style={{
                margin: "6px 0 24px",
                fontFamily: "Alexandria",
                fontSize: 13,
                color: T.textMuted,
                lineHeight: 1.55,
              }}
            >
              {step === "details"
                ? rtl
                  ? "ابدأ بالاسم التجاري والجوال فقط"
                  : "Start with business name and mobile only"
                : step === "otp"
                  ? rtl
                    ? "تحقق من رقم الجوال"
                    : "Verify mobile"
                  : rtl
                    ? "تم التسجيل بنجاح"
                    : "Registration complete"}
            </p>

            <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              {step === "details" && (
                <>
                  <label
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12,
                      color: T.textMuted,
                    }}
                  >
                    {rtl ? "الاسم التجاري" : "Business name"}
                  </label>
                  <input
                    value={businessName}
                    onChange={(e) => setBusinessName(e.target.value)}
                    placeholder={
                      rtl ? "مثال: رحلات النور" : "Example: Al Noor Travel"
                    }
                    style={{
                      height: 46,
                      padding: "0 14px",
                      borderRadius: 12,
                      background: T.bg,
                      border: `1px solid ${T.hairlineStrong}`,
                      color: T.text,
                      fontFamily: "Alexandria",
                      fontSize: 14,
                    }}
                  />
                  <label
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12,
                      color: T.textMuted,
                    }}
                  >
                    {rtl ? "رقم الجوال" : "Mobile number"}
                  </label>
                  <div
                    dir="ltr"
                    style={{
                      height: 50,
                      borderRadius: 12,
                      background: T.bg,
                      border: `1px solid ${T.hairlineStrong}`,
                      display: "flex",
                      alignItems: "center",
                      overflow: "hidden",
                    }}
                  >
                    <div
                      style={{
                        height: "100%",
                        padding: "0 12px",
                        display: "flex",
                        alignItems: "center",
                        gap: 7,
                        borderRight: `1px solid ${T.hairline}`,
                        color: T.text,
                        fontFamily: "Alexandria",
                        fontWeight: 600,
                        flex: "0 0 auto",
                      }}
                    >
                      <span>🇸🇦</span>
                      <span>+966</span>
                    </div>
                    <input
                      type="tel"
                      value={phone}
                      onChange={(e) =>
                        setPhone(e.target.value.replace(/\D/g, "").slice(0, 10))
                      }
                      inputMode="numeric"
                      autoComplete="tel-national"
                      placeholder="5xxxxxxxx"
                      aria-label={rtl ? "رقم الجوال" : "Mobile number"}
                      style={{
                        minWidth: 0,
                        flex: 1,
                        height: "100%",
                        padding: "0 12px",
                        border: 0,
                        outline: 0,
                        background: "transparent",
                        color: T.text,
                        fontFamily: "Alexandria",
                        fontSize: 16,
                        textAlign: "left",
                      }}
                    />
                  </div>
                </>
              )}
              {step === "otp" && (
                <>
                  <label
                    style={{
                      fontFamily: "Alexandria",
                      fontSize: 12,
                      color: T.textMuted,
                    }}
                  >
                    {rtl
                      ? "رمز التحقق المكوّن من 6 أرقام"
                      : "6-digit verification code"}
                  </label>
                  <input
                    value={otp}
                    onChange={(e) => {
                      const value = e.target.value
                        .replace(/\D/g, "")
                        .slice(0, 6);
                      setOtp(value);
                      if (value.length === 6)
                        setTimeout(() => verifyOtp(value), 0);
                    }}
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    placeholder="••••••"
                    dir="ltr"
                    style={{
                      height: 54,
                      padding: "0 14px",
                      borderRadius: 12,
                      textAlign: "center",
                      letterSpacing: 8,
                      background: T.bg,
                      border: `1px solid ${T.hairlineStrong}`,
                      color: T.text,
                      fontSize: 22,
                    }}
                  />
                </>
              )}
              {step === "done" && (
                <div
                  style={{
                    padding: 18,
                    borderRadius: 12,
                    background: T.camelMist,
                    color: T.text,
                    fontFamily: "Alexandria",
                    lineHeight: 1.8,
                  }}
                >
                  {rtl
                    ? "حالة الملف: غير مكتمل. ستجد داخل لوحة المزود السجل التجاري والترخيص والبريد والوثائق المطلوبة."
                    : "Profile status: incomplete. Complete registration, license, email and documents from your dashboard."}
                </div>
              )}
              <div id="duyuf-recaptcha"></div>
              {message && (
                <div
                  role="status"
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 12,
                    color: step === "done" ? T.success : T.textMuted,
                    lineHeight: 1.6,
                  }}
                >
                  {message}
                </div>
              )}
            </div>

            <div style={{ display: "flex", gap: 10, marginTop: 24 }}>
              <button
                onClick={() => setPage("home")}
                style={{
                  padding: "12px 24px",
                  borderRadius: 12,
                  background: "transparent",
                  border: `1px solid ${T.hairline}`,
                  color: T.text,
                  fontFamily: "Alexandria",
                  fontWeight: 600,
                  fontSize: 13,
                  cursor: "pointer",
                }}
              >
                {rtl ? "إلغاء" : "Cancel"}
              </button>
              <button
                disabled={busy}
                onClick={
                  step === "details"
                    ? sendOtp
                    : step === "otp"
                      ? () => verifyOtp()
                      : () => setPage("provider-dashboard")
                }
                style={{
                  flex: 1,
                  padding: "12px 24px",
                  borderRadius: 12,
                  background: T.primary,
                  border: 0,
                  color: "#fff",
                  fontFamily: "Alexandria",
                  fontWeight: 700,
                  fontSize: 13,
                  cursor: "pointer",
                  opacity: busy ? 0.6 : 1,
                }}
              >
                {busy
                  ? rtl
                    ? "جارٍ التنفيذ…"
                    : "Please wait…"
                  : step === "details"
                    ? rtl
                      ? "إرسال رمز التحقق"
                      : "Send verification code"
                    : step === "otp"
                      ? rtl
                        ? "تحقق وادخل"
                        : "Verify and continue"
                      : rtl
                        ? "الدخول إلى الموقع"
                        : "Continue"}
              </button>
            </div>
          </div>

          {/* Side info */}
          <div>
            <h3
              style={{
                margin: 0,
                fontFamily: "Alexandria",
                fontWeight: 700,
                fontSize: 18,
                color: T.text,
              }}
            >
              {rtl ? "ماذا تحصل عليه" : "What you'll get"}
            </h3>
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: 12,
                marginTop: 14,
              }}
            >
              {[
                {
                  i: "trend-up",
                  t: rtl ? "لوحة إحصائيات لحظية" : "Live analytics dashboard",
                  d: rtl
                    ? "تابع الإيرادات والحجوزات بالوقت الفعلي"
                    : "Track revenue and bookings in real time",
                },
                {
                  i: "kaaba",
                  t: rtl ? "معالج تكوين الباقات" : "Package wizard",
                  d: rtl
                    ? "انشر باقات جديدة خلال دقائق"
                    : "Publish new packages in minutes",
                },
                {
                  i: "scan",
                  t: rtl ? "تطبيق التشغيل" : "Operations app",
                  d: rtl
                    ? "تحقّق من العملاء وتنبيهات أثناء الرحلة"
                    : "Check in travelers and send in-trip alerts",
                },
                {
                  i: "card",
                  t: rtl ? "دفعات مجدولة وآمنة" : "Scheduled secure payouts",
                  d: rtl
                    ? "تحويل أسبوعي لحسابك البنكي"
                    : "Weekly payouts to your bank account",
                },
              ].map((b, i) => (
                <div
                  key={i}
                  style={{
                    display: "flex",
                    gap: 12,
                    padding: 16,
                    background: T.surface,
                    border: `1px solid ${T.hairline}`,
                    borderRadius: 14,
                  }}
                >
                  <div
                    style={{
                      width: 38,
                      height: 38,
                      borderRadius: 10,
                      background: T.camelMist,
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      flex: "0 0 auto",
                    }}
                  >
                    <Icon name={b.i} size={18} color={T.primary} />
                  </div>
                  <div>
                    <div
                      style={{
                        fontFamily: "Alexandria",
                        fontWeight: 600,
                        fontSize: 13.5,
                        color: T.text,
                      }}
                    >
                      {b.t}
                    </div>
                    <div
                      style={{
                        fontFamily: "Alexandria",
                        fontSize: 12,
                        color: T.textMuted,
                        marginTop: 2,
                        lineHeight: 1.5,
                      }}
                    >
                      {b.d}
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div
              style={{
                marginTop: 20,
                padding: 16,
                borderRadius: 14,
                background: T.camelMist,
              }}
            >
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 11,
                  color: T.primaryDeep,
                  fontWeight: 700,
                  letterSpacing: "0.05em",
                  textTransform: "uppercase",
                  marginBottom: 6,
                }}
              >
                {rtl ? "العمولة الشفافة" : "Transparent commission"}
              </div>
              <div
                style={{
                  fontFamily: "Alexandria",
                  fontSize: 13,
                  color: T.text,
                  lineHeight: 1.6,
                }}
              >
                {rtl
                  ? "عمولة ضيوف 8% فقط من سعر الباقة الأساسي. لا رسوم مخفية، لا اشتراك شهري."
                  : "Just 8% Duyuf commission on base package price. No hidden fees, no monthly subscription."}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ─── Contact page ──────────────────────────────────────────────────────
function WebContactPage({ theme, lang }) {
  const T = theme;
  const rtl = isRTL(lang);
  const submitContact = (e) => {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    const subject = encodeURIComponent(
      data.get("subject") || "Duyuf website enquiry",
    );
    const body = encodeURIComponent(
      `${data.get("name")}\n${data.get("email")}\n\n${data.get("message")}`,
    );
    window.location.href = `mailto:info@duyufsa.com?subject=${subject}&body=${body}`;
  };

  return (
    <>
      <WebPageHeader
        theme={T}
        lang={lang}
        eyebrow={rtl ? "تواصل معنا" : "Get in touch"}
        title={rtl ? "كيف يمكننا مساعدتك؟" : "How can we help?"}
        sub={
          rtl
            ? "فريق دعم ضيوف متاح 24/7 لمساعدة المعتمرين والمزوّدين."
            : "Our team is available 24/7 to support pilgrims and providers."
        }
      />

      <div style={{ padding: "60px 32px", background: T.bg }}>
        <div style={{ maxWidth: 1100, margin: "0 auto" }}>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 16,
              marginBottom: 40,
            }}
          >
            {[
              {
                i: "phone",
                t: rtl ? "واتساب" : "WhatsApp",
                sub: "+966 800 200 0",
                meta: rtl ? "الرد خلال دقائق" : "Reply in minutes",
                tone: "green",
              },
              {
                i: "mail",
                t: rtl ? "بريد إلكتروني" : "Email",
                sub: "support@duyuf.app",
                meta: rtl ? "الرد خلال 24 ساعة" : "Reply in 24h",
                tone: "camel",
              },
              {
                i: "shield",
                t: rtl ? "للمزوّدين" : "Providers",
                sub: "providers@duyuf.app",
                meta: rtl ? "فريق مخصّص" : "Dedicated team",
                tone: "ink",
              },
            ].map((c, i) => (
              <div
                key={i}
                style={{
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 18,
                  padding: 24,
                }}
              >
                <div
                  style={{
                    width: 44,
                    height: 44,
                    borderRadius: 12,
                    background:
                      c.tone === "green"
                        ? "rgba(63,142,92,0.12)"
                        : c.tone === "ink"
                          ? T.inkSoft
                          : T.camelMist,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <Icon
                    name={c.i}
                    size={20}
                    color={
                      c.tone === "green"
                        ? T.success
                        : c.tone === "ink"
                          ? T.cream
                          : T.primary
                    }
                  />
                </div>
                <div
                  style={{
                    fontFamily: "Alexandria",
                    fontWeight: 700,
                    fontSize: 15,
                    color: T.text,
                    marginTop: 14,
                    letterSpacing: "-0.005em",
                  }}
                >
                  {c.t}
                </div>
                <div
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 14,
                    color: T.text,
                    marginTop: 6,
                    fontWeight: 500,
                  }}
                >
                  {c.sub}
                </div>
                <div
                  style={{
                    fontFamily: "Alexandria",
                    fontSize: 11.5,
                    color: T.textMuted,
                    marginTop: 4,
                  }}
                >
                  {c.meta}
                </div>
              </div>
            ))}
          </div>

          {/* Contact form */}
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1.4fr 1fr",
              gap: 32,
            }}
          >
            <form
              onSubmit={submitContact}
              style={{
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                borderRadius: 18,
                padding: 28,
              }}
            >
              <h3
                style={{
                  margin: 0,
                  fontFamily: "Alexandria",
                  fontWeight: 700,
                  fontSize: 20,
                  color: T.text,
                  letterSpacing: "-0.01em",
                }}
              >
                {rtl ? "أرسل لنا رسالة" : "Send us a message"}
              </h3>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 12,
                  marginTop: 18,
                }}
              >
                {[
                  { n: "name", l: rtl ? "الاسم" : "Name", type: "text" },
                  { n: "email", l: rtl ? "البريد" : "Email", type: "email" },
                ].map((f, i) => (
                  <div key={i}>
                    <label
                      style={{
                        display: "block",
                        fontFamily: "Alexandria",
                        fontSize: 11,
                        color: T.textMuted,
                        marginBottom: 6,
                        fontWeight: 600,
                        letterSpacing: "0.04em",
                        textTransform: "uppercase",
                      }}
                    >
                      {f.l}
                    </label>
                    <input
                      required
                      name={f.n}
                      type={f.type}
                      style={{
                        boxSizing: "border-box",
                        width: "100%",
                        height: 44,
                        padding: "0 12px",
                        borderRadius: 10,
                        background: T.bg,
                        border: `1px solid ${T.hairlineStrong}`,
                        fontFamily: "Alexandria",
                        fontSize: 13.5,
                        color: T.text,
                      }}
                    />
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 12 }}>
                <label
                  style={{
                    display: "block",
                    fontFamily: "Alexandria",
                    fontSize: 11,
                    color: T.textMuted,
                    marginBottom: 6,
                    fontWeight: 600,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  {rtl ? "الموضوع" : "Subject"}
                </label>
                <input
                  required
                  name="subject"
                  defaultValue={
                    rtl
                      ? "استفسار عن حجز قائم"
                      : "Question about an existing booking"
                  }
                  style={{
                    boxSizing: "border-box",
                    width: "100%",
                    height: 44,
                    padding: "0 12px",
                    borderRadius: 10,
                    background: T.bg,
                    border: `1px solid ${T.hairlineStrong}`,
                    fontFamily: "Alexandria",
                    fontSize: 13.5,
                    color: T.text,
                  }}
                />
              </div>
              <div style={{ marginTop: 12 }}>
                <label
                  style={{
                    display: "block",
                    fontFamily: "Alexandria",
                    fontSize: 11,
                    color: T.textMuted,
                    marginBottom: 6,
                    fontWeight: 600,
                    letterSpacing: "0.04em",
                    textTransform: "uppercase",
                  }}
                >
                  {rtl ? "الرسالة" : "Message"}
                </label>
                <textarea
                  required
                  name="message"
                  placeholder={
                    rtl ? "اكتب رسالتك هنا…" : "Type your message here…"
                  }
                  style={{
                    boxSizing: "border-box",
                    width: "100%",
                    minHeight: 120,
                    padding: 12,
                    borderRadius: 10,
                    background: T.bg,
                    border: `1px solid ${T.hairlineStrong}`,
                    fontFamily: "Alexandria",
                    fontSize: 13.5,
                    color: T.text,
                    lineHeight: 1.6,
                  }}
                />
              </div>
              <button
                type="submit"
                style={{
                  marginTop: 18,
                  padding: "12px 28px",
                  borderRadius: 12,
                  background: T.primary,
                  color: "#fff",
                  border: 0,
                  fontFamily: "Alexandria",
                  fontWeight: 700,
                  fontSize: 13.5,
                  cursor: "pointer",
                }}
              >
                {rtl ? "إرسال الرسالة" : "Send message"}
              </button>
            </form>

            {/* Office */}
            <div
              style={{
                background: T.surface,
                border: `1px solid ${T.hairline}`,
                borderRadius: 18,
                padding: 24,
              }}
            >
              <h3
                style={{
                  margin: 0,
                  fontFamily: "Alexandria",
                  fontWeight: 700,
                  fontSize: 16,
                  color: T.text,
                }}
              >
                {rtl ? "المكتب الرئيسي" : "Head office"}
              </h3>
              <p
                style={{
                  margin: "8px 0 0",
                  fontFamily: "Alexandria",
                  fontSize: 13,
                  color: T.textMuted,
                  lineHeight: 1.6,
                }}
              >
                {rtl
                  ? "برج المملكة، الطابق 22\nطريق الملك فهد، الرياض 12241\nالمملكة العربية السعودية"
                  : "Kingdom Tower, Floor 22\nKing Fahd Road, Riyadh 12241\nSaudi Arabia"}
              </p>
              <div
                style={{
                  marginTop: 16,
                  height: 180,
                  borderRadius: 12,
                  overflow: "hidden",
                  position: "relative",
                  background: "#E8E1D3",
                }}
              >
                <svg
                  width="100%"
                  height="100%"
                  viewBox="0 0 320 180"
                  preserveAspectRatio="none"
                >
                  <rect width="320" height="180" fill="#E8E1D3" />
                  <path
                    d="M0 90 Q 100 60, 200 90 T 320 90"
                    stroke="#C9BFAF"
                    strokeWidth="1.5"
                    fill="none"
                  />
                  <path
                    d="M0 130 L 320 130"
                    stroke="#C9BFAF"
                    strokeWidth="1"
                    fill="none"
                  />
                  <path
                    d="M40 0 L 80 180"
                    stroke="#C9BFAF"
                    strokeWidth="1"
                    fill="none"
                  />
                  <rect
                    x="130"
                    y="70"
                    width="60"
                    height="40"
                    fill="#7F6D5F"
                    opacity="0.4"
                    rx="2"
                  />
                </svg>
                <div
                  style={{
                    position: "absolute",
                    left: "50%",
                    top: "50%",
                    transform: "translate(-50%,-100%)",
                  }}
                >
                  <div
                    style={{
                      background: T.primary,
                      color: "#fff",
                      padding: "6px 12px",
                      borderRadius: 99,
                      fontFamily: "Alexandria",
                      fontSize: 11,
                      fontWeight: 700,
                      boxShadow: "0 4px 12px rgba(0,0,0,0.2)",
                      display: "flex",
                      alignItems: "center",
                      gap: 5,
                    }}
                  >
                    <Icon name="pin" size={12} color="#fff" /> Duyuf HQ
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ─── Sign-in page ──────────────────────────────────────────────────────
function WebSignInPage({ theme, lang }) {
  const T = theme;
  const rtl = isRTL(lang);
  const { setPage } = useWeb();
  const [phone, setPhone] = React.useState("");
  const [otp, setOtp] = React.useState("");
  const [step, setStep] = React.useState("phone");
  const [busy, setBusy] = React.useState(false);
  const [message, setMessage] = React.useState("");
  const loginVerifyingRef = React.useRef(false);
  React.useEffect(() => {
    if (localStorage.getItem("duyuf_provider_session"))
      setPage("provider-dashboard");
  }, []);
  const normalize = (value) => {
    const d = String(value || "").replace(/\D/g, "");
    if (/^05\d{8}$/.test(d)) return `+966${d.slice(1)}`;
    if (/^9665\d{8}$/.test(d)) return `+${d}`;
    if (/^5\d{8}$/.test(d)) return `+966${d}`;
    return "";
  };
  const send = async () => {
    const mobile = normalize(phone);
    if (!mobile)
      return setMessage(
        rtl ? "أدخل رقم جوال سعودي صحيح." : "Enter a valid Saudi mobile.",
      );
    setBusy(true);
    setMessage("");
    try {
      if (window.duyufLoginRecaptcha) window.duyufLoginRecaptcha.clear();
      window.duyufLoginRecaptcha = new firebase.auth.RecaptchaVerifier(
        "duyuf-login-recaptcha",
        { size: "invisible" },
      );
      window.duyufLoginConfirmation = await firebase
        .auth()
        .signInWithPhoneNumber(mobile, window.duyufLoginRecaptcha);
      setStep("otp");
      setMessage(
        rtl ? "أرسلنا رمز التحقق إلى جوالك." : "Verification code sent.",
      );
    } catch (e) {
      console.error(e);
      setMessage(
        rtl
          ? "تعذر إرسال الرمز. راجع إعدادات Firebase."
          : "Could not send the code.",
      );
    } finally {
      setBusy(false);
    }
  };
  const verify = async (codeValue = otp) => {
    if (!/^\d{6}$/.test(codeValue) || loginVerifyingRef.current) return;
    loginVerifyingRef.current = true;
    setBusy(true);
    setMessage("");
    let credential;
    try {
      credential = await window.duyufLoginConfirmation.confirm(codeValue);
    } catch (e) {
      console.error("Firebase OTP confirmation failed", e);
      setMessage(
        rtl
          ? "الرمز غير صحيح أو انتهت صلاحيته. اطلب رمزاً جديداً."
          : "Invalid or expired code. Request a new one.",
      );
      setBusy(false);
      loginVerifyingRef.current = false;
      return;
    }
    try {
      const idToken = await credential.user.getIdToken(true);
      const response = await fetch(
        `${window.DUYUF_API_URL}/v1/auth/firebase-provider`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ idToken }),
        },
      );
      const result = await response.json();
      if (!response.ok || !result.ok)
        throw new Error(result.error || "login_failed");
      localStorage.setItem("duyuf_provider_session", result.sessionToken);
      localStorage.setItem("duyuf_provider", JSON.stringify(result.provider));
      setPage("provider-dashboard");
    } catch (e) {
      console.error("Provider login failed", e);
      setMessage(
        e.message === "provider_not_registered"
          ? rtl
            ? "تم توثيق الجوال، لكن الرقم غير مسجل كمزوّد. اختر «سجّل هنا» أولاً."
            : "Phone verified, but it is not registered as a provider."
          : rtl
            ? "تم توثيق الجوال، لكن تعذّر فتح حساب المزود. حاول مرة أخرى."
            : "Phone verified, but the provider account could not be opened. Try again.",
      );
    } finally {
      setBusy(false);
      loginVerifyingRef.current = false;
    }
  };

  return (
    <div
      style={{
        minHeight: 600,
        padding: "60px 32px",
        background: T.bg,
        display: "flex",
        alignItems: "center",
      }}
    >
      <div style={{ maxWidth: 460, margin: "0 auto", width: "100%" }}>
        <div
          style={{
            background: T.surface,
            border: `1px solid ${T.hairline}`,
            borderRadius: 22,
            padding: 36,
            boxShadow: T.cardShadow,
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              marginBottom: 18,
            }}
          >
            <DuyufMark size={44} color={T.primary} />
          </div>
          <h1
            style={{
              margin: 0,
              fontFamily: "Alexandria",
              fontWeight: 700,
              fontSize: 24,
              color: T.text,
              textAlign: "center",
              letterSpacing: "-0.01em",
            }}
          >
            {rtl ? "مرحباً بعودتك" : "Welcome back"}
          </h1>
          <p
            style={{
              margin: "6px 0 28px",
              fontFamily: "Alexandria",
              fontSize: 13,
              color: T.textMuted,
              textAlign: "center",
            }}
          >
            {rtl ? "سجّل الدخول برقم جوالك" : "Sign in with your phone number"}
          </p>

          <label
            style={{
              display: "block",
              fontFamily: "Alexandria",
              fontSize: 11,
              color: T.textMuted,
              marginBottom: 6,
              fontWeight: 600,
            }}
          >
            {step === "phone"
              ? rtl
                ? "رقم الجوال"
                : "Mobile number"
              : rtl
                ? "رمز التحقق"
                : "Verification code"}
          </label>
          {step === "phone" ? (
            <div
              dir="ltr"
              style={{
                boxSizing: "border-box",
                width: "100%",
                height: 52,
                borderRadius: 14,
                background: T.bg,
                border: `1.5px solid ${T.primary}`,
                display: "flex",
                alignItems: "center",
                overflow: "hidden",
              }}
            >
              <div
                style={{
                  height: "100%",
                  padding: "0 12px",
                  display: "flex",
                  alignItems: "center",
                  gap: 7,
                  borderRight: `1px solid ${T.hairline}`,
                  color: T.text,
                  fontFamily: "Alexandria",
                  fontWeight: 600,
                  flex: "0 0 auto",
                }}
              >
                <span>🇸🇦</span>
                <span>+966</span>
              </div>
              <input
                type="tel"
                value={phone}
                onChange={(e) =>
                  setPhone(e.target.value.replace(/\D/g, "").slice(0, 10))
                }
                inputMode="numeric"
                autoComplete="tel-national"
                dir="ltr"
                placeholder="5xxxxxxxx"
                aria-label={rtl ? "رقم الجوال" : "Mobile number"}
                style={{
                  minWidth: 0,
                  flex: 1,
                  height: "100%",
                  padding: "0 12px",
                  border: 0,
                  outline: 0,
                  background: "transparent",
                  color: T.text,
                  fontFamily: "Alexandria",
                  fontSize: 16,
                  textAlign: "left",
                }}
              />
            </div>
          ) : (
            <input
              value={otp}
              onChange={(e) => {
                const value = e.target.value.replace(/\D/g, "").slice(0, 6);
                setOtp(value);
                if (value.length === 6) setTimeout(() => verify(value), 0);
              }}
              inputMode="numeric"
              autoComplete="one-time-code"
              dir="ltr"
              placeholder="••••••"
              style={{
                boxSizing: "border-box",
                width: "100%",
                height: 52,
                padding: "0 14px",
                textAlign: "center",
                letterSpacing: 8,
                borderRadius: 14,
                background: T.bg,
                color: T.text,
                border: `1.5px solid ${T.primary}`,
                fontSize: 22,
              }}
            />
          )}
          <div id="duyuf-login-recaptcha"></div>
          {message && (
            <div
              role="status"
              style={{
                marginTop: 10,
                color: T.textMuted,
                fontFamily: "Alexandria",
                fontSize: 12,
                lineHeight: 1.6,
              }}
            >
              {message}
            </div>
          )}

          <button
            disabled={busy}
            onClick={step === "phone" ? send : () => verify()}
            style={{
              width: "100%",
              marginTop: 22,
              padding: "14px",
              borderRadius: 14,
              border: 0,
              background: T.primary,
              color: "#fff",
              fontFamily: "Alexandria",
              fontWeight: 700,
              fontSize: 14,
              cursor: "pointer",
              boxShadow: "0 8px 20px rgba(193,152,114,0.35)",
              opacity: busy ? 0.6 : 1,
            }}
          >
            {busy
              ? rtl
                ? "جارٍ التنفيذ…"
                : "Please wait…"
              : step === "phone"
                ? rtl
                  ? "إرسال رمز التحقق"
                  : "Send verification code"
                : rtl
                  ? "تحقق وادخل"
                  : "Verify and sign in"}
          </button>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 12,
              margin: "22px 0 18px",
            }}
          >
            <div style={{ flex: 1, height: 1, background: T.hairline }} />
            <span
              style={{
                fontFamily: "Alexandria",
                fontSize: 11,
                color: T.textFaint,
                letterSpacing: "0.06em",
                textTransform: "uppercase",
              }}
            >
              {rtl ? "أو" : "or"}
            </span>
            <div style={{ flex: 1, height: 1, background: T.hairline }} />
          </div>

          <button
            onClick={() => setPage("browse")}
            style={{
              width: "100%",
              padding: "12px",
              borderRadius: 14,
              border: `1px solid ${T.hairlineStrong}`,
              background: "transparent",
              color: T.text,
              fontFamily: "Alexandria",
              fontWeight: 600,
              fontSize: 13,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: 8,
            }}
          >
            <Icon name="compass" size={16} color={T.text} />{" "}
            {rtl ? "تصفّح كضيف" : "Continue as guest"}
          </button>

          <p
            style={{
              margin: "24px 0 0",
              fontFamily: "Alexandria",
              fontSize: 11.5,
              color: T.textFaint,
              textAlign: "center",
              lineHeight: 1.55,
            }}
          >
            {rtl
              ? "بالمتابعة، أنت توافق على الشروط وسياسة الخصوصية"
              : "By continuing you agree to the Terms & Privacy Policy"}
          </p>
        </div>

        <div
          style={{
            marginTop: 16,
            textAlign: "center",
            fontFamily: "Alexandria",
            fontSize: 12.5,
            color: T.textMuted,
          }}
        >
          {rtl ? "مزوّد خدمة؟ " : "A service provider? "}
          <a
            onClick={() => setPage("become-provider")}
            style={{ color: T.primary, fontWeight: 600, cursor: "pointer" }}
          >
            {rtl ? "سجّل هنا" : "Sign up here"}
          </a>
        </div>
      </div>
    </div>
  );
}

function WebProviderMeetingPointsPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb(),
    token = localStorage.getItem("duyuf_provider_session");
  const [items, setItems] = React.useState([]),
    [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  const [form, setForm] = React.useState({
    city: "جدة",
    name: "",
    address: "",
    latitude: 0,
    longitude: 0,
    departureTime: "08:00",
    arrivalTime: "10:00",
    hotelDepartureTime: "14:00",
    returnArrivalTime: "18:00",
  });
  const load = () =>
    fetch(`${window.DUYUF_API_URL}/v1/provider/meeting-points`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => (r.ok ? r.json() : Promise.reject()))
      .then((b) =>
        setItems(Array.isArray(b.meetingPoints) ? b.meetingPoints : []),
      )
      .catch(() =>
        setMessage(
          rtl
            ? "تعذر تحميل النقاط المحفوظة، ويمكنك إضافة نقطة جديدة الآن."
            : "Saved points could not be loaded; you can add a new point now.",
        ),
      );
  React.useEffect(() => {
    load();
  }, []);
  const edit = (p) => {
    setForm({
      city: p.city,
      name: p.name,
      address: p.address,
      latitude: Number(p.latitude) || 0,
      longitude: Number(p.longitude) || 0,
      departureTime: p.departure_time || "08:00",
      arrivalTime: p.arrival_time || "10:00",
      hotelDepartureTime: p.hotel_departure_time || "14:00",
      returnArrivalTime: p.return_arrival_time || "18:00",
    });
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const save = async (e) => {
    e.preventDefault();
    setBusy(true);
    setMessage("");
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/provider/meeting-points`,
        {
          method: "POST",
          headers: {
            "content-type": "application/json",
            authorization: `Bearer ${token}`,
          },
          body: JSON.stringify(form),
        },
      );
      if (r.ok) {
        setMessage(
          rtl
            ? "تم حفظ نقطة التجمع لهذه المدينة."
            : "Meeting point saved for this city.",
        );
        load();
      } else
        setMessage(
          rtl
            ? "أكمل المدينة واسم النقطة والعنوان ووقت المغادرة."
            : "Complete the city, point name, address, and departure time.",
        );
    } catch (_) {
      setMessage(
        rtl
          ? "تعذر الاتصال مؤقتًا. حاول مرة أخرى."
          : "Connection failed. Please try again.",
      );
    } finally {
      setBusy(false);
    }
  };
  const field = (key, label, type = "text") => (
    <label
      style={{
        display: "grid",
        gap: 6,
        color: T.textMuted,
        font: "600 12px Alexandria",
      }}
    >
      {label}
      <input
        required
        type={type}
        value={form[key]}
        onChange={(e) => setForm({ ...form, [key]: e.target.value })}
        style={{
          height: 48,
          border: `1px solid ${T.hairlineStrong}`,
          borderRadius: 11,
          padding: "0 12px",
          background: T.bg,
          color: T.text,
          font: "500 16px Alexandria",
        }}
      />
    </label>
  );
  return (
    <div
      style={{ minHeight: 680, padding: "28px 14px 90px", background: T.bg }}
    >
      <main style={{ maxWidth: 900, margin: "0 auto" }}>
        <button
          onClick={() => setPage("provider-dashboard")}
          style={{ border: 0, background: "transparent", color: T.textMuted }}
        >
          → {rtl ? "لوحة التحكم" : "Dashboard"}
        </button>
        <h1
          style={{ color: T.text, font: "700 clamp(25px,6vw,34px) Alexandria" }}
        >
          {rtl ? "نقاط التجمع" : "Meeting points"}
        </h1>
        <p style={{ color: T.textMuted, font: "500 13px/1.8 Alexandria" }}>
          {rtl
            ? "حدد نقطة تجمع واحدة لكل مدينة ووقت المغادرة. الوقت الافتراضي 08:00 ويمكنك تغييره."
            : "Set one meeting point per city and its departure time. The default is 08:00 and can be changed."}
        </p>
        <form
          onSubmit={save}
          style={{
            padding: "clamp(16px,4vw,26px)",
            background: T.surface,
            border: `1px solid ${T.hairline}`,
            borderRadius: 18,
          }}
        >
          <div
            style={{
              display: "grid",
              gridTemplateColumns:
                "repeat(auto-fit,minmax(min(100%,220px),1fr))",
              gap: 12,
            }}
          >
            {field("city", rtl ? "المدينة" : "City")}
            {field("name", rtl ? "اسم نقطة التجمع" : "Meeting point name")}
            {field(
              "departureTime",
              rtl ? "ساعة المغادرة" : "Departure time",
              "time",
            )}
          </div>
          <div style={{ marginTop: 12 }}>
            {field(
              "address",
              rtl ? "عنوان نقطة التجمع" : "Meeting point address",
            )}
          </div>
          {message && (
            <p style={{ color: T.primary, font: "600 12px Alexandria" }}>
              {message}
            </p>
          )}
          <button
            disabled={busy}
            style={{
              width: "100%",
              minHeight: 50,
              marginTop: 14,
              border: 0,
              borderRadius: 12,
              background: T.primary,
              color: "#fff",
              font: "700 14px Alexandria",
            }}
          >
            {busy
              ? rtl
                ? "جارٍ الحفظ…"
                : "Saving…"
              : rtl
                ? "حفظ نقطة التجمع"
                : "Save meeting point"}
          </button>
        </form>
        <h2
          style={{ color: T.text, font: "700 20px Alexandria", marginTop: 28 }}
        >
          {rtl ? "النقاط المحفوظة" : "Saved points"}
        </h2>
        <div style={{ display: "grid", gap: 10 }}>
          {items.length ? (
            items.map((p) => (
              <article
                key={p.id}
                style={{
                  padding: 16,
                  borderRadius: 14,
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  display: "flex",
                  justifyContent: "space-between",
                  gap: 12,
                  alignItems: "center",
                  flexWrap: "wrap",
                }}
              >
                <div>
                  <strong
                    style={{ color: T.text, font: "700 15px Alexandria" }}
                  >
                    {p.city} — {p.name}
                  </strong>
                  <div
                    style={{
                      color: T.textMuted,
                      font: "500 12px/1.8 Alexandria",
                    }}
                  >
                    {p.address}
                    <br />
                    {rtl ? "ساعة المغادرة" : "Departure time"}:{" "}
                    {p.departure_time || "08:00"}
                  </div>
                </div>
                <button
                  onClick={() => edit(p)}
                  style={{
                    padding: "9px 13px",
                    border: `1px solid ${T.primary}`,
                    borderRadius: 9,
                    background: "transparent",
                    color: T.primary,
                    font: "600 11px Alexandria",
                  }}
                >
                  {rtl ? "تعديل" : "Edit"}
                </button>
              </article>
            ))
          ) : (
            <p style={{ color: T.textMuted }}>
              {rtl ? "لم تضف نقاط تجمع بعد." : "No meeting points yet."}
            </p>
          )}
        </div>
      </main>
    </div>
  );
}

function WebProviderBusinessProfilePage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb(),
    token = localStorage.getItem("duyuf_provider_session");
  const [data, setData] = React.useState(null),
    [form, setForm] = React.useState({
      email: "",
      commercialRegistration: "",
      tourismLicense: "",
    }),
    [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  const load = () =>
    fetch(`${window.DUYUF_API_URL}/v1/provider/business-profile`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((b) => {
        if (!b.ok) throw new Error();
        setData(b);
        setForm({
          email: b.profile.email || "",
          commercialRegistration: b.profile.commercial_registration || "",
          tourismLicense: b.profile.tourism_license || "",
        });
      })
      .catch(() =>
        setMessage(
          rtl
            ? "تعذر تحميل الملف التجاري."
            : "Could not load business profile.",
        ),
      );
  React.useEffect(load, []);
  const docs = data?.documents || [],
    has = (type) => docs.some((d) => d.document_type === type),
    status = data?.profile?.status || "incomplete",
    complete = Math.round(
      ([
        form.email,
        form.commercialRegistration,
        form.tourismLicense,
        has("commercial_registration"),
        has("tourism_license"),
        has("brand_logo"),
      ].filter(Boolean).length /
        6) *
        100,
    );
  const upload = async (type, file) => {
    if (!file) return;
    setBusy(true);
    setMessage("");
    const fd = new FormData();
    fd.append("type", type);
    fd.append("file", file);
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/provider/business-profile/documents`,
        {
          method: "POST",
          headers: { authorization: `Bearer ${token}` },
          body: fd,
        },
      );
      if (!r.ok) throw new Error();
      setMessage(rtl ? "تم رفع الوثيقة." : "Document uploaded.");
      load();
    } catch (_) {
      setMessage(
        rtl
          ? "تعذر رفع الوثيقة. استخدم PDF أو صورة بحجم أقل من 5MB."
          : "Upload failed. Use a PDF or image under 5MB.",
      );
    } finally {
      setBusy(false);
    }
  };
  const save = async (submit) => {
    setBusy(true);
    setMessage("");
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/provider/business-profile`,
        {
          method: "POST",
          headers: {
            "content-type": "application/json",
            authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({ ...form, submit }),
        },
      );
      const b = await r.json();
      if (!r.ok) throw new Error(b.error);
      setMessage(
        submit
          ? rtl
            ? "تم إرسال الملف لاعتماد الأدمن."
            : "Profile submitted for admin approval."
          : rtl
            ? "تم حفظ البيانات."
            : "Profile saved.",
      );
      load();
    } catch (e) {
      setMessage(
        e.message === "documents_required"
          ? rtl
            ? "ارفع السجل التجاري وترخيص النشاط أولًا."
            : "Upload both required documents first."
          : rtl
            ? "أكمل جميع البيانات المطلوبة."
            : "Complete all required fields.",
      );
    } finally {
      setBusy(false);
    }
  };
  const input = (key, label, type = "text") => (
    <label
      style={{
        display: "grid",
        gap: 6,
        color: T.textMuted,
        font: "600 12px Alexandria",
      }}
    >
      {label}
      <input
        type={type}
        value={form[key]}
        onChange={(e) => setForm({ ...form, [key]: e.target.value })}
        style={{
          height: 48,
          border: `1px solid ${T.hairlineStrong}`,
          borderRadius: 11,
          padding: "0 12px",
          background: T.bg,
          color: T.text,
          font: "500 16px Alexandria",
        }}
      />
    </label>
  );
  const oneDoc = (type, label) => (
    <div
      style={{
        padding: 14,
        border: `1px solid ${has(type) ? "#66a77c" : T.hairlineStrong}`,
        borderRadius: 13,
        background: T.bg,
      }}
    >
      <strong
        style={{ display: "block", color: T.text, font: "700 13px Alexandria" }}
      >
        {label}
      </strong>
      <small style={{ color: has(type) ? "#237a43" : T.textMuted }}>
        {has(type)
          ? rtl
            ? "تم الرفع ✓"
            : "Uploaded ✓"
          : rtl
            ? "PDF أو صورة — حتى 5MB"
            : "PDF or image — up to 5MB"}
      </small>
      <label
        style={{
          display: "inline-block",
          marginTop: 10,
          padding: "8px 12px",
          borderRadius: 9,
          background: T.primary,
          color: "#fff",
          font: "700 11px Alexandria",
          cursor: "pointer",
        }}
      >
        {has(type)
          ? rtl
            ? "استبدال"
            : "Replace"
          : rtl
            ? "رفع الملف"
            : "Upload"}
        <input
          hidden
          type="file"
          accept={
            type === "brand_logo"
              ? "image/jpeg,image/png,image/webp"
              : "application/pdf,image/jpeg,image/png,image/webp"
          }
          onChange={(e) => upload(type, e.target.files?.[0])}
        />
      </label>
    </div>
  );
  const doc = (type, label) =>
    type === "tourism_license" ? (
      <>
        {oneDoc(type, label)}
        {oneDoc(
          "brand_logo",
          rtl ? "شعار العلامة التجارية (إلزامي)" : "Brand logo (required)",
        )}
      </>
    ) : (
      oneDoc(type, label)
    );
  const statusText =
    status === "approved"
      ? rtl
        ? "معتمد — الملف مكتمل 100%"
        : "Approved — profile 100% complete"
      : status === "pending"
        ? rtl
          ? "بانتظار اعتماد الأدمن"
          : "Awaiting admin approval"
        : status === "rejected"
          ? rtl
            ? "يحتاج تعديل وإعادة إرسال"
            : "Needs changes and resubmission"
          : rtl
            ? "غير مكتمل"
            : "Incomplete";
  return (
    <div
      style={{ minHeight: 700, padding: "28px 14px 100px", background: T.bg }}
    >
      <main style={{ maxWidth: 900, margin: "0 auto" }}>
        <button
          onClick={() => setPage("provider-dashboard")}
          style={{ border: 0, background: "transparent", color: T.textMuted }}
        >
          → {rtl ? "لوحة التحكم" : "Dashboard"}
        </button>
        <h1
          style={{ color: T.text, font: "700 clamp(25px,6vw,34px) Alexandria" }}
        >
          {rtl ? "الملف التجاري" : "Business profile"}
        </h1>
        <section
          style={{
            padding: "clamp(16px,4vw,26px)",
            background: T.surface,
            border: `1px solid ${T.hairline}`,
            borderRadius: 18,
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              gap: 12,
              flexWrap: "wrap",
            }}
          >
            <div>
              <strong style={{ color: T.text, font: "700 17px Alexandria" }}>
                {data?.provider?.businessName || "—"}
              </strong>
              <div style={{ color: T.textMuted, font: "500 12px Alexandria" }}>
                {data?.provider?.phone || "—"}
              </div>
            </div>
            <span
              style={{
                padding: "8px 12px",
                borderRadius: 99,
                background: status === "approved" ? "#e5f4ea" : T.camelMist,
                color: status === "approved" ? "#237a43" : T.primary,
                font: "700 11px Alexandria",
              }}
            >
              {statusText}
            </span>
          </div>
          <div
            style={{
              height: 10,
              margin: "18px 0 6px",
              borderRadius: 99,
              overflow: "hidden",
              background: T.surfaceAlt,
            }}
          >
            <span
              style={{
                display: "block",
                height: "100%",
                width: `${status === "approved" ? 100 : complete}%`,
                background: status === "approved" ? "#238753" : T.primary,
              }}
            />
          </div>
          <small style={{ color: T.textMuted }}>
            {status === "approved" ? 100 : complete}%
          </small>
          <div
            style={{
              display: "grid",
              gridTemplateColumns:
                "repeat(auto-fit,minmax(min(100%,220px),1fr))",
              gap: 12,
              marginTop: 20,
            }}
          >
            {input("email", rtl ? "البريد الإلكتروني" : "Email", "email")}
            {input(
              "commercialRegistration",
              rtl ? "رقم السجل التجاري" : "Commercial registration number",
            )}
            {input(
              "tourismLicense",
              rtl ? "رقم ترخيص النشاط" : "Tourism activity license",
            )}
          </div>
          <h2
            style={{
              color: T.text,
              font: "700 18px Alexandria",
              marginTop: 26,
            }}
          >
            {rtl ? "الوثائق المطلوبة" : "Required documents"}
          </h2>
          <div
            style={{
              display: "grid",
              gridTemplateColumns:
                "repeat(auto-fit,minmax(min(100%,260px),1fr))",
              gap: 12,
            }}
          >
            {doc(
              "commercial_registration",
              rtl ? "صورة السجل التجاري" : "Commercial registration",
            )}
            {doc(
              "tourism_license",
              rtl ? "صورة ترخيص النشاط" : "Tourism license",
            )}
          </div>
          {data?.profile?.rejection_reason && (
            <p
              style={{
                padding: 12,
                borderRadius: 10,
                background: "#fff0ee",
                color: "#b42318",
              }}
            >
              {data.profile.rejection_reason}
            </p>
          )}
          {message && (
            <p style={{ color: T.primary, font: "600 12px Alexandria" }}>
              {message}
            </p>
          )}
          <div
            style={{ display: "flex", gap: 9, marginTop: 20, flexWrap: "wrap" }}
          >
            <button
              disabled={busy || status === "approved"}
              onClick={() => save(false)}
              style={{
                padding: "12px 20px",
                border: `1px solid ${T.primary}`,
                borderRadius: 11,
                background: "transparent",
                color: T.primary,
                font: "700 12px Alexandria",
              }}
            >
              {rtl ? "حفظ" : "Save"}
            </button>
            <button
              disabled={busy || status === "approved" || complete < 100}
              onClick={() => save(true)}
              style={{
                padding: "12px 20px",
                border: 0,
                borderRadius: 11,
                background: T.primary,
                color: "#fff",
                font: "700 12px Alexandria",
                opacity:
                  busy || status === "approved" || complete < 100 ? 0.55 : 1,
              }}
            >
              {rtl ? "إرسال للاعتماد" : "Submit for approval"}
            </button>
          </div>
        </section>
      </main>
    </div>
  );
}

function WebProviderDashboardPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage, setPkg } = useWeb();
  const [data, setData] = React.useState({ provider: null, packages: [] });
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    const token = localStorage.getItem("duyuf_provider_session");
    if (!token) return setPage("signin");
    fetch(`${window.DUYUF_API_URL}/v1/provider/packages`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json().then((body) => ({ ok: r.ok, body })))
      .then(({ ok, body }) => {
        if (!ok) throw new Error();
        setData(body);
        if (body.provider) {
          localStorage.setItem("duyuf_provider", JSON.stringify(body.provider));
          window.dispatchEvent(new Event("duyuf-provider-updated"));
        }
      })
      .catch(() => {
        localStorage.removeItem("duyuf_provider_session");
        setPage("signin");
      })
      .finally(() => setLoading(false));
  }, []);
  const provider =
    data.provider ||
    JSON.parse(localStorage.getItem("duyuf_provider") || "null");
  return (
    <div
      style={{
        minHeight: 650,
        background: T.bg,
        padding: "28px clamp(16px,4vw,40px) 70px",
      }}
    >
      <div style={{ maxWidth: 1100, margin: "0 auto" }}>
        <div
          style={{
            display: "flex",
            flexWrap: "wrap",
            gap: 14,
            alignItems: "center",
            justifyContent: "space-between",
          }}
        >
          <div>
            <div
              style={{
                color: T.textMuted,
                fontFamily: "Alexandria",
                fontSize: 12,
              }}
            >
              {rtl ? "لوحة المزود" : "Provider dashboard"}
            </div>
            <h1
              style={{
                margin: "4px 0 0",
                color: T.text,
                fontFamily: "Alexandria",
                fontSize: "clamp(22px,5vw,32px)",
              }}
            >
              {rtl ? "أهلاً بك، " : "Welcome, "}
              {provider?.businessName || (rtl ? "مزود ضيوف" : "Duyuf provider")}
            </h1>
          </div>
          <button
            onClick={() => setPage("provider-add-package")}
            style={{
              border: 0,
              borderRadius: 13,
              background: T.primary,
              color: "#fff",
              padding: "13px 20px",
              fontFamily: "Alexandria",
              fontWeight: 700,
              cursor: "pointer",
            }}
          >
            ＋ {rtl ? "إضافة باقة" : "Add package"}
          </button>
        </div>
        {provider && !provider.profileComplete && (
          <div
            style={{
              marginTop: 20,
              padding: 16,
              borderRadius: 14,
              background: T.camelMist,
              color: T.text,
              fontFamily: "Alexandria",
              lineHeight: 1.7,
            }}
          >
            <strong>
              {rtl ? "ملفك غير مكتمل" : "Your profile is incomplete"}
            </strong>
            <div style={{ fontSize: 12, color: T.textMuted }}>
              {rtl
                ? "أكمل السجل التجاري والترخيص والبريد والوثائق. يمكنك إضافة باقاتك الآن."
                : "Complete registration, license, email and documents. You can add packages now."}
            </div>
          </div>
        )}
        <h2
          style={{
            margin: "30px 0 14px",
            color: T.text,
            fontFamily: "Alexandria",
            fontSize: 19,
          }}
        >
          {rtl ? "باقاتي" : "My packages"}
        </h2>
        {loading ? (
          <div style={{ color: T.textMuted }}>
            {rtl ? "جارٍ التحميل…" : "Loading…"}
          </div>
        ) : data.packages.length === 0 ? (
          <div
            style={{
              textAlign: "center",
              padding: "50px 20px",
              border: `1px dashed ${T.hairlineStrong}`,
              borderRadius: 18,
              background: T.surface,
              fontFamily: "Alexandria",
              color: T.textMuted,
            }}
          >
            <Icon name="kaaba" size={34} color={T.primary} />
            <h3 style={{ color: T.text }}>
              {rtl ? "لا توجد باقات بعد" : "No packages yet"}
            </h3>
            <p>
              {rtl
                ? "أضف أول باقة عمرة خلال أقل من دقيقة."
                : "Add your first Umrah package in under a minute."}
            </p>
            <button
              onClick={() => setPage("provider-add-package")}
              style={{
                border: 0,
                borderRadius: 12,
                background: T.primary,
                color: "#fff",
                padding: "12px 18px",
                fontFamily: "Alexandria",
                fontWeight: 700,
              }}
            >
              {rtl ? "إضافة أول باقة" : "Add first package"}
            </button>
          </div>
        ) : (
          <div
            style={{
              display: "grid",
              gridTemplateColumns:
                "repeat(auto-fit,minmax(min(100%,300px),1fr))",
              gap: 14,
            }}
          >
            {data.packages.map((p) => (
              <div
                key={p.id}
                style={{
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 16,
                  padding: 18,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    gap: 10,
                  }}
                >
                  <strong style={{ color: T.text, fontFamily: "Alexandria" }}>
                    {p.title}
                  </strong>
                  <Badge
                    tone={p.status === "active" ? "green" : "warn"}
                    theme={T}
                  >
                    {p.status === "active"
                      ? rtl
                        ? "نشطة"
                        : "Active"
                      : p.status === "rejected"
                        ? rtl
                          ? "مرفوضة"
                          : "Rejected"
                        : rtl
                          ? "بانتظار الاعتماد"
                          : "Pending approval"}
                  </Badge>
                </div>
                <div
                  style={{
                    marginTop: 9,
                    color: T.textMuted,
                    fontFamily: "Alexandria",
                    fontSize: 12,
                    lineHeight: 1.8,
                  }}
                >
                  {p.hotel_name}
                  <br />
                  {p.duration_days} {rtl ? "أيام" : "days"} · {p.available_from}{" "}
                  — {p.available_to}
                  <br />
                  {rtl ? "السعة" : "Capacity"}: {p.seats} ·{" "}
                  {rtl ? "المحجوز" : "Booked"}: {p.booked || 0} ·{" "}
                  {rtl ? "دخل" : "Checked in"}: {p.checked_in || 0}
                  <br />
                  {rtl ? "الصور" : "Images"}: {p.image_count || 0}
                </div>
                <div
                  style={{
                    marginTop: 12,
                    color: T.primary,
                    fontFamily: "Alexandria",
                    fontWeight: 700,
                    fontSize: 20,
                  }}
                >
                  {Number(p.price_per_person).toLocaleString()}{" "}
                  {rtl ? "ر.س / فرد" : "SAR / person"}
                </div>
                <div
                  style={{
                    display: "flex",
                    gap: 8,
                    marginTop: 14,
                    flexWrap: "wrap",
                  }}
                >
                  <button
                    onClick={() => {
                      setPkg(p);
                      setPage("provider-edit-package");
                    }}
                    style={{
                      padding: "9px 13px",
                      border: 0,
                      borderRadius: 10,
                      background: T.primary,
                      color: "#fff",
                      font: "700 12px Alexandria",
                    }}
                  >
                    {rtl ? "تعديل وإضافة صور" : "Edit & images"}
                  </button>
                  <button
                    onClick={() => {
                      setPkg(p);
                      setPage("provider-package-bookings");
                    }}
                    style={{
                      padding: "9px 13px",
                      border: `1px solid ${T.hairlineStrong}`,
                      borderRadius: 10,
                      background: T.surface,
                      color: T.text,
                      font: "700 12px Alexandria",
                    }}
                  >
                    {rtl ? "الطلبات والوصول" : "Bookings & arrivals"}
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

const BEDBANK_CITY_NAMES = {
  "مكة المكرمة": "Makkah",
  مكة: "Makkah",
  "المدينة المنورة": "Madinah",
  المدينة: "Madinah",
  جدة: "Jeddah",
  الرياض: "Riyadh",
  الدمام: "Dammam",
  Makkah: "Makkah",
  Madinah: "Madinah",
  Jeddah: "Jeddah",
  Riyadh: "Riyadh",
  Dammam: "Dammam",
};

function ProviderHotelPicker({ theme, lang, form, setForm }) {
  const T = theme,
    rtl = isRTL(lang),
    [hotels, setHotels] = React.useState([]),
    [query, setQuery] = React.useState(""),
    [busy, setBusy] = React.useState(false),
    [detailsBusy, setDetailsBusy] = React.useState(false),
    [error, setError] = React.useState("");
  const destination =
    BEDBANK_CITY_NAMES[form.destinationCity] ||
    form.destinationCity ||
    "Makkah";
  React.useEffect(() => {
    let live = true;
    setBusy(true);
    setError("");
    setHotels([]);
    Promise.resolve()
      .then(async () => {
        if (!window.hotelApi) throw new Error("hotel_api_missing");
        const cityBody = await window.hotelApi("cities", { countryCode: "SA" }),
          cities = cityBody.cities || [];
        const wanted = String(destination).toLowerCase(),
          city =
            cities.find(
              (x) => String(x.cityName || "").toLowerCase() === wanted,
            ) ||
            cities.find((x) =>
              String(x.cityName || "")
                .toLowerCase()
                .includes(wanted),
            );
        if (!city) throw new Error("city_not_found");
        const body = await window.hotelApi("hotels", { cityId: city.cityId });
        if (live) setHotels(body.hotels || []);
      })
      .catch(
        () =>
          live &&
          setError(
            rtl
              ? "تعذر تحميل قائمة الفنادق الآن. حاول مرة أخرى."
              : "Could not load the hotel catalog. Please retry.",
          ),
      )
      .finally(() => live && setBusy(false));
    return () => {
      live = false;
    };
  }, [destination]);
  const pick = async (hotel) => {
    const id = String(hotel.hotelId || hotel.id || hotel.hotelCode || "");
    const catalogImages = (
      Array.isArray(hotel.images)
        ? hotel.images
        : [hotel.imageUrl || hotel.image || hotel.thumbnailUrl]
    )
      .map((image) =>
        typeof image === "string"
          ? image
          : image?.url || image?.imageUrl || image?.path,
      )
      .filter(Boolean)
      .slice(0, 12);
    setForm((v) => ({
      ...v,
      hotelName: hotel.hotelName || hotel.name,
      hotelExternalId: id,
      hotelSource: "bedbank",
      hotelAddress: hotel.address || "",
      hotelStarRating: Number(hotel.starRating) || 0,
      hotelImages: catalogImages,
      hotelRoomOptions: [],
    }));
    // Hotel identity and static content are independent of the package dates.
    // Prefer catalog imagery whenever the supplier exposes it. The current
    // BedBank catalog response contains identity/address only, so live details
    // remain a best-effort fallback until a content endpoint is provided.
    setDetailsBusy(true);
    setError("");
    try {
      const rooms = [{ adults: 2, childrenAges: [] }],
        base = {
          destination,
          countryCode: "SA",
          checkInDate: form.departureAt,
          checkOutDate: form.returnAt,
          nationality: "SA",
          residency: "SA",
          rooms,
          hotelIds: [Number(id) || id],
        },
        search = await window.hotelApi("search", base),
        found =
          (search.hotels || []).find(
            (x) => String(x.hotelCode || x.hotelId || x.id) === id,
          ) || (search.hotels || [])[0];
      if (!found) throw new Error("not_available");
      const detail = await window.hotelApi("details", {
        token: found.token,
        hotelCode: found.hotelCode,
        countryCode: "SA",
        destination,
        checkInDate: form.departureAt,
        checkOutDate: form.returnAt,
        nationality: "SA",
        residency: "SA",
        rooms,
      });
      const images = (
        detail.images?.length
          ? detail.images
          : [detail.imageUrl || found.imageUrl]
      )
        .filter(Boolean)
        .slice(0, 12);
      setForm((v) => ({
        ...v,
        hotelName: detail.hotelName || found.hotelName || v.hotelName,
        hotelExternalId: id,
        hotelSource: "bedbank",
        hotelAddress: detail.address || found.address || v.hotelAddress,
        hotelStarRating:
          Number(detail.starRating || found.starRating) || v.hotelStarRating,
        hotelImages: images.length ? images : v.hotelImages,
        hotelRoomOptions: (detail.rooms?.length?detail.rooms:found.rooms||[]).map(room=>({name:room.roomName||room.name||"",boardType:room.boardType||"",price:Number(room.price)||0,isRefundable:Boolean(room.isRefundable)})).filter(room=>room.name).slice(0,30),
      }));
    } catch (_) {
      setError(
        rtl
          ? "تم اختيار الفندق. مصدر HotelBeds الحالي لم يرسل صور المحتوى الثابت لهذا الفندق."
          : "Hotel selected. The current HotelBeds source did not return static property images.",
      );
    } finally {
      setDetailsBusy(false);
    }
  };
  const shown = hotels
    .filter((h) =>
      String(h.hotelName || h.name || "")
        .toLowerCase()
        .includes(query.toLowerCase()),
    )
    .slice(0, 30);
  return (
    <div style={{ gridColumn: "1 / -1" }}>
      <label
        style={{
          display: "grid",
          gap: 7,
          color: T.textMuted,
          font: "600 12px Alexandria",
        }}
      >
        {rtl ? "اختر الفندق من قائمة HotelBeds" : "Choose a HotelBeds property"}
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder={rtl ? "ابحث باسم الفندق…" : "Search hotel name…"}
          style={{
            boxSizing: "border-box",
            width: "100%",
            height: 50,
            borderRadius: 13,
            border: `1px solid ${T.hairlineStrong}`,
            background: T.bg,
            color: T.text,
            padding: "0 13px",
            font: "500 14px Alexandria",
          }}
        />
      </label>
      {busy ? (
        <p style={{ color: T.textMuted, font: "500 12px Alexandria" }}>
          {rtl ? "جارٍ تحميل فنادق الوجهة…" : "Loading destination hotels…"}
        </p>
      ) : (
        <div
          style={{
            display: "grid",
            gap: 7,
            maxHeight: 260,
            overflowY: "auto",
            marginTop: 9,
          }}
        >
          {shown.map((h) => {
            const id = String(h.hotelId || h.id || h.hotelCode || ""),
              selected = id === String(form.hotelExternalId);
            return (
              <button
                type="button"
                key={id || h.hotelName || h.name}
                onClick={() => pick(h)}
                style={{
                  padding: "11px 12px",
                  textAlign: "start",
                  border: `1px solid ${selected ? T.primary : T.hairline}`,
                  borderRadius: 11,
                  background: selected ? T.camelMist : T.surface,
                  color: T.text,
                  font: "600 12px Alexandria",
                  cursor: "pointer",
                }}
              >
                <strong>{h.hotelName || h.name}</strong>
                {h.address && (
                  <small
                    style={{
                      display: "block",
                      marginTop: 4,
                      color: T.textMuted,
                    }}
                  >
                    {h.address}
                  </small>
                )}
              </button>
            );
          })}
        </div>
      )}
      {form.hotelName && (
        <div
          style={{
            marginTop: 12,
            padding: 13,
            borderRadius: 12,
            background: T.camelMist,
            color: T.text,
            font: "600 12px/1.7 Alexandria",
          }}
        >
          <strong>✓ {form.hotelName}</strong>
          <br />
          <small>
            {detailsBusy
              ? rtl
                ? "جارٍ جلب الصور والتفاصيل…"
                : "Loading images and details…"
              : form.hotelImages?.length
                ? rtl
                  ? `تم جلب ${form.hotelImages.length} صور تلقائياً.`
                  : `${form.hotelImages.length} images imported automatically.`
                : rtl
                  ? "تم ربط الفندق بقائمة HotelBeds."
                  : "Property linked to HotelBeds."}
          </small>
          {form.hotelImages?.length > 0 && (
            <div
              style={{
                display: "flex",
                gap: 6,
                overflowX: "auto",
                marginTop: 9,
              }}
            >
              {form.hotelImages.slice(0, 5).map((src) => (
                <img
                  key={src}
                  src={src}
                  alt=""
                  style={{
                    width: 92,
                    height: 66,
                    objectFit: "cover",
                    borderRadius: 8,
                  }}
                />
              ))}
            </div>
          )}
        </div>
      )}
      {error && (
        <p
          role="alert"
          style={{ color: "#b42318", font: "600 11px/1.7 Alexandria" }}
        >
          {error}
        </p>
      )}
    </div>
  );
}

function PackageCommercialFields({ theme, lang, form, setForm, inputStyle }) {
  const T = theme,
    rtl = isRTL(lang),
    price = (key, label) => (
      <label
        style={{
          display: "grid",
          gap: 7,
          color: T.textMuted,
          font: "600 12px Alexandria",
        }}
      >
        {label}
        <input
          type="number"
          min="1"
          value={form[key]}
          onChange={(e) =>
            setForm((v) => ({
              ...v,
              [key]: e.target.value,
              ...(key === "doublePrice"
                ? { pricePerPerson: e.target.value }
                : {}),
            }))
          }
          style={inputStyle}
        />
      </label>
    );
  return (
    <div style={{ gridColumn: "1 / -1", display: "grid", gap: 16 }}>
      <section>
        <strong
          style={{
            display: "block",
            marginBottom: 10,
            color: T.text,
            font: "700 14px Alexandria",
          }}
        >
          {rtl ? "أسعار الإشغال للغرفة" : "Room occupancy pricing"}
        </strong>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,160px),1fr))",
            gap: 10,
          }}
        >
          {price("singlePrice", rtl ? "غرفة مفردة" : "Single")}
          {price("doublePrice", rtl ? "غرفة ثنائية" : "Double")}
          {price("triplePrice", rtl ? "غرفة ثلاثية" : "Triple")}
          {price("quadPrice", rtl ? "غرفة رباعية" : "Quad")}
        </div>
      </section>
      <label
        style={{
          display: "grid",
          gap: 7,
          color: T.textMuted,
          font: "600 12px Alexandria",
        }}
      >
        {rtl ? "سياسة إلغاء الباقة" : "Package cancellation policy"}
        <textarea
          rows="4"
          value={form.cancellationPolicy}
          onChange={(e) =>
            setForm((v) => ({ ...v, cancellationPolicy: e.target.value }))
          }
          style={{
            ...inputStyle,
            height: "auto",
            padding: 12,
            resize: "vertical",
          }}
        />
      </label>
      <section>
        <strong
          style={{
            display: "block",
            marginBottom: 9,
            color: T.text,
            font: "700 14px Alexandria",
          }}
        >
          {rtl ? "سياسة تأكيد الحجز والسداد" : "Booking confirmation and payment"}
        </strong>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          {[
            ["pay_on_arrival", rtl?"تأكيد الحجز والدفع عند الوصول":"Confirm now, pay on arrival"],
            ["prepay_required", rtl?"الدفع مسبقًا لتأكيد الحجز":"Prepayment required to confirm"],
          ].map(([value, label]) => (
            <label
              key={value}
              style={{
                display: "flex",
                alignItems: "center",
                gap: 8,
                padding: "11px 14px",
                border: `1px solid ${form.paymentConfirmationMode===value ? T.primary : T.hairlineStrong}`,
                borderRadius: 11,
                background: form.paymentConfirmationMode===value ? T.camelMist : T.bg,
                color: T.text,
                font: "700 12px Alexandria",
              }}
            >
              <input
                type="radio"
                name="paymentConfirmationMode"
                checked={form.paymentConfirmationMode===value}
                onChange={() => setForm((v) => ({ ...v, paymentConfirmationMode:value }))}
              />
              {label}
            </label>
          ))}
        </div>
      </section>
    </div>
  );
}

function WebProviderAddPackagePage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb();
  const iso = (date) => date.toISOString().slice(0, 10),
    today = new Date(),
    after30 = new Date(Date.now() + 30 * 86400000);
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    travelMode: "flight",
    title: "",
    originCity: "الرياض",
    destinationCity: "مكة المكرمة",
    departureAt: iso(today),
    returnAt: iso(new Date(Date.now() + 7 * 86400000)),
    busType: "فاخرة",
    airline: "",
    flightNumber: "",
    flightDepartureTime: "08:00",
    flightArrivalTime: "09:30",
    flightArrivalCity: "جدة",
    airportTransferType: "نقل خاص",
    airportTransferTime: "10:00",
    returnOriginCity: "جدة",
    returnDestinationCity: "الرياض",
    returnAirline: "",
    returnFlightNumber: "",
    returnDepartureTime: "20:00",
    returnArrivalTime: "21:30",
    hotelName: "",
    hotelExternalId: "",
    hotelSource: "bedbank",
    hotelAddress: "",
    hotelStarRating: 0,
    hotelImages: [],
    hotelRoomOptions: [],
    roomType: "غرفة مزدوجة",
    mealPlan: "إفطار",
    durationDays: 7,
    pricePerPerson: "",
    singlePrice: "",
    doublePrice: "",
    triplePrice: "",
    quadPrice: "",
    cancellationPolicy:
      "استرداد كامل قبل 7 أيام من موعد الانطلاق، وبعد ذلك تطبق رسوم الإلغاء الموضحة في شروط الباقة.",
    paymentConfirmationMode: "pay_on_arrival",
    supportsTabby: false,
    supportsTamara: false,
    childPrice: "",
    infantPrice: 0,
    availableFrom: iso(today),
    availableTo: iso(after30),
    seats: 1,
    bookingClosesHours: 72,
  });
  const [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  const nights = Math.max(
      1,
      Math.round(
        (new Date(`${form.returnAt}T12:00:00`) -
          new Date(`${form.departureAt}T12:00:00`)) /
          86400000,
      ) || 1,
    ),
    durationDays = nights + 1;
  const steps = rtl
    ? ["الأساسيات", "المسار والموعد", "الفندق", "السعة والسعر"]
    : ["Basics", "Route & dates", "Hotel", "Capacity & pricing"];
  const inputStyle = {
    boxSizing: "border-box",
    width: "100%",
    height: 50,
    borderRadius: 13,
    border: `1px solid ${T.hairlineStrong}`,
    background: T.bg,
    color: T.text,
    padding: "0 13px",
    fontFamily: "Alexandria",
    fontSize: 14,
    outline: "none",
  };
  const adjustTime = (key, minutes) => {
    const [hours, mins] = String(form[key] || "00:00").split(":").map(Number);
    const total = (hours * 60 + mins + minutes + 1440) % 1440;
    setForm({ ...form, [key]:`${String(Math.floor(total/60)).padStart(2,"0")}:${String(total%60).padStart(2,"0")}` });
  };
  const field = (key, label, type = "text", options) =>
    key === "hotelName" ? (
      <ProviderHotelPicker
        theme={T}
        lang={lang}
        form={form}
        setForm={setForm}
      />
    ) : key === "pricePerPerson" ? (
      <PackageCommercialFields
        theme={T}
        lang={lang}
        form={form}
        setForm={setForm}
        inputStyle={inputStyle}
      />
    ) : (
      <label
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 7,
          color: T.textMuted,
          fontFamily: "Alexandria",
          fontSize: 12,
          fontWeight: 600,
        }}
      >
        {label}
        {options ? (
          <select
            value={form[key]}
            onChange={(e) => {
              const value = e.target.value;
              if (key === "travelMode") {
                setForm({
                  ...form,
                  travelMode: value,
                  destinationCity: "مكة المكرمة",
                  returnOriginCity: value === "flight" ? "جدة" : "",
                  returnDestinationCity:
                    value === "flight" ? form.originCity : "",
                });
              } else {
                setForm({ ...form, [key]: value });
              }
            }}
            style={inputStyle}
          >
            {options.map((item) => {
              const pair = Array.isArray(item) ? item : [item, item];
              return (
                <option key={pair[0]} value={pair[0]}>
                  {pair[1]}
                </option>
              );
            })}
          </select>
        ) : type === "time" ? (
          <div dir="ltr" style={{display:"grid",gridTemplateColumns:"48px minmax(0,1fr) 48px",height:52,border:`1px solid ${T.hairlineStrong}`,borderRadius:13,overflow:"hidden",background:T.bg}}><button type="button" aria-label={rtl?`تقليل ${label} 15 دقيقة`:`Decrease ${label} 15 minutes`} onClick={()=>adjustTime(key,-15)} style={{border:0,background:T.surface,color:T.text,fontSize:22}}>−</button><input type="time" step="900" value={form[key]} onChange={(e)=>setForm({...form,[key]:e.target.value})} style={{width:"100%",minWidth:0,border:0,borderInline:`1px solid ${T.hairline}`,background:"transparent",color:T.text,textAlign:"center",font:"700 16px Alexandria",padding:"0 6px"}}/><button type="button" aria-label={rtl?`زيادة ${label} 15 دقيقة`:`Increase ${label} 15 minutes`} onClick={()=>adjustTime(key,15)} style={{border:0,background:T.primary,color:"#fff",fontSize:22}}>+</button></div>
        ) : (
          <input
            type={type}
            value={form[key]}
            onChange={(e) => setForm({ ...form, [key]: e.target.value })}
            style={inputStyle}
          />
        )}
      </label>
    );
  const stepper = (key, label, min, max) => {
    const value = Number(form[key]) || min;
    const update = (next) =>
      setForm({ ...form, [key]: Math.min(max, Math.max(min, next)) });
    return (
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          gap: 7,
          color: T.textMuted,
          fontFamily: "Alexandria",
          fontSize: 12,
          fontWeight: 600,
        }}
      >
        <span>{label}</span>
        <div
          dir="ltr"
          style={{
            height: 52,
            borderRadius: 13,
            border: `1px solid ${T.hairlineStrong}`,
            background: T.bg,
            display: "flex",
            alignItems: "stretch",
            overflow: "hidden",
          }}
        >
          <button
            type="button"
            aria-label={rtl ? `تقليل ${label}` : `Decrease ${label}`}
            onClick={() => update(value - 1)}
            disabled={value <= min}
            style={{
              flex: "0 0 56px",
              width: 56,
              minWidth: 56,
              height: "100%",
              border: 0,
              borderRight: `1px solid ${T.hairline}`,
              background: "transparent",
              color: T.text,
              fontSize: 26,
              lineHeight: 1,
              cursor: "pointer",
              opacity: value <= min ? 0.35 : 1,
            }}
          >
            −
          </button>
          <input
            type="number"
            min={min}
            max={max}
            value={value}
            onChange={(e) => update(Number(e.target.value))}
            style={{
              display: "block",
              flex: "1 1 auto",
              width: 0,
              minWidth: 0,
              height: "100%",
              padding: 0,
              border: 0,
              outline: 0,
              background: "transparent",
              color: T.text,
              textAlign: "center",
              fontFamily: "Alexandria",
              fontSize: 17,
              fontWeight: 700,
              MozAppearance: "textfield",
            }}
          />
          <button
            type="button"
            aria-label={rtl ? `زيادة ${label}` : `Increase ${label}`}
            onClick={() => update(value + 1)}
            disabled={value >= max}
            style={{
              flex: "0 0 56px",
              width: 56,
              minWidth: 56,
              height: "100%",
              border: 0,
              borderLeft: `1px solid ${T.hairline}`,
              background: T.primary,
              color: "#fff",
              fontSize: 24,
              lineHeight: 1,
              cursor: "pointer",
              opacity: value >= max ? 0.35 : 1,
            }}
          >
            +
          </button>
        </div>
      </div>
    );
  };
  const validate = () => {
    const required =
      step === 0
        ? ["travelMode", "title"]
        : step === 1
          ? ["originCity", "departureAt", "returnAt"]
          : step === 2
            ? ["hotelName", "roomType", "mealPlan"]
            : ["pricePerPerson"];
    const missing = required.filter((k) => !String(form[k] ?? "").trim());
    if (step === 1 && form.travelMode === "flight") {
      [
        "airline",
        "flightNumber",
        "flightDepartureTime",
        "flightArrivalTime",
        "flightArrivalCity",
        "airportTransferType",
        "airportTransferTime",
        "returnOriginCity",
        "returnDestinationCity",
        "returnAirline",
        "returnFlightNumber",
        "returnDepartureTime",
        "returnArrivalTime",
      ].forEach((key) => {
        if (!String(form[key] ?? "").trim() && !missing.includes(key)) missing.push(key);
      });
    }
    if (missing.length) {
      setMessage(
        rtl
          ? "أكمل الحقول المطلوبة للمتابعة."
          : "Complete the required fields.",
      );
      return false;
    }
    if (step === 1 && form.returnAt < form.departureAt) {
      setMessage(
        rtl
          ? "تاريخ العودة يجب أن يكون بعد تاريخ الانطلاق."
          : "Return must be after departure.",
      );
      return false;
    }
    setMessage("");
    return true;
  };
  const save = async (e) => {
    e.preventDefault();
    if (step < 3) {
      if (validate()) setStep(step + 1);
      return;
    }
    if (!validate()) return;
    setBusy(true);
    setMessage("");
    try {
      const token = localStorage.getItem("duyuf_provider_session");
      const occupancyPrices = {
        single: Number(form.singlePrice) || 0,
        double: Number(form.doublePrice || form.pricePerPerson) || 0,
        triple: Number(form.triplePrice) || 0,
        quad: Number(form.quadPrice) || 0,
      };
      const payload = {
        title: form.title.trim() || `باقة ${form.hotelName.trim()}`,
        hotelName: form.hotelName,
        hotelExternalId: form.hotelExternalId,
        hotelSource: form.hotelSource,
        hotelAddress: form.hotelAddress,
        hotelStarRating: form.hotelStarRating,
        hotelImages: form.hotelImages,
        hotelRoomOptions: form.hotelRoomOptions,
        occupancyPrices,
        cancellationPolicy: form.cancellationPolicy,
        paymentConfirmationMode: form.paymentConfirmationMode,
        supportsTabby: form.supportsTabby,
        supportsTamara: form.supportsTamara,
        durationDays,
        pricePerPerson: Number(form.doublePrice || form.pricePerPerson),
        availableFrom: form.availableFrom,
        availableTo: form.availableTo,
        seats: Number(form.seats),
        journey: {
          travelMode: form.travelMode,
          originCity: form.originCity,
          destinationCity: form.destinationCity,
          departureAt:
            form.travelMode === "flight"
              ? `${form.departureAt}T${form.flightDepartureTime}:00`
              : form.departureAt,
          returnAt: form.returnAt,
          busType: form.travelMode === "bus" ? form.busType : "",
          airline: form.travelMode === "flight" ? form.airline : "",
          flightNumber: form.travelMode === "flight" ? form.flightNumber : "",
          arrivalAt:
            form.travelMode === "flight"
              ? `${form.departureAt}T${form.flightArrivalTime}:00`
              : "",
          flightArrivalCity:
            form.travelMode === "flight" ? form.flightArrivalCity : "",
          airportTransferType:
            form.travelMode === "flight" ? form.airportTransferType : "",
          airportTransferAt:
            form.travelMode === "flight"
              ? `${form.departureAt}T${form.airportTransferTime}:00`
              : "",
          returnOriginCity:
            form.travelMode === "flight" ? form.returnOriginCity : "",
          returnDestinationCity:
            form.travelMode === "flight" ? form.returnDestinationCity : "",
          returnDepartureAt:
            form.travelMode === "flight"
              ? `${form.returnAt}T${form.returnDepartureTime}:00`
              : "",
          returnAirline:
            form.travelMode === "flight" ? form.returnAirline : "",
          returnFlightNumber:
            form.travelMode === "flight" ? form.returnFlightNumber : "",
          returnArrivalAt:
            form.travelMode === "flight"
              ? `${form.returnAt}T${form.returnArrivalTime}:00`
              : "",
          roomType: form.roomType,
          mealPlan: form.mealPlan,
          childPrice: Number(
            form.childPrice || form.doublePrice || form.pricePerPerson,
          ),
          infantPrice: Number(form.infantPrice || 0),
          bookingClosesHours: Number(form.bookingClosesHours),
        },
      };
      const r = await fetch(`${window.DUYUF_API_URL}/v1/provider/packages`, {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(payload),
      });
      const b = await r.json();
      if (r.status === 401) {
        localStorage.removeItem("duyuf_provider_session");
        setPage("signin");
        return;
      }
      if (!r.ok || !b.ok)
        throw new Error(
          (b.fields || []).join("، ") || b.error || "save_failed",
        );
      setPage("provider-dashboard");
    } catch (error) {
      setMessage(
        rtl
          ? "تعذر حفظ الباقة. راجع جميع البيانات."
          : "Could not save the package. Check all fields.",
      );
    } finally {
      setBusy(false);
    }
  };
  const grid = (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,230px),1fr))",
        gap: 14,
      }}
    >
      {step === 0 && (
        <>
          {field("title", rtl ? "اسم الباقة" : "Package title")}
          {field("travelMode", rtl ? "نوع العمرة" : "Umrah type", "text", [
            ["flight", rtl ? "عمرة بالطائرة" : "Umrah by flight"],
            ["bus", rtl ? "عمرة بالحافلة" : "Umrah by bus"],
          ])}
        </>
      )}
      {step === 1 && (
        <>
          {field(
            "originCity",
            rtl ? "مدينة الانطلاق" : "Departure city",
            "text",
            rtl
              ? [
                  "جدة",
                  "الرياض",
                  "المدينة المنورة",
                  "الدمام",
                  "القاهرة",
                  "دبي",
                  "كراتشي",
                  "إسطنبول",
                ]
              : [
                  "Jeddah",
                  "Riyadh",
                  "Madinah",
                  "Dammam",
                  "Cairo",
                  "Dubai",
                  "Karachi",
                  "Istanbul",
                ],
          )}
          {field("destinationCity", rtl ? "الوجهة" : "Destination")}
          {field(
            "departureAt",
            rtl ? "موعد الانطلاق" : "Departure date",
            "date",
          )}
          {field("returnAt", rtl ? "موعد العودة" : "Return date", "date")}
          {form.travelMode === "bus" ? (
            field(
              "busType",
              rtl ? "نوع الحافلة" : "Bus type",
              "text",
              rtl ? ["عادية", "فاخرة"] : ["Regular", "Luxury"],
            )
          ) : (
            <>
              <div style={{ gridColumn:"1 / -1",padding:"12px 15px",borderRadius:12,background:T.camelMist,color:T.primary,font:"700 14px Alexandria" }}>{rtl?"1. رحلة الذهاب":"1. Outbound flight"}</div>
              {field("airline", rtl ? "شركة الطيران" : "Airline")}
              {field(
                "flightNumber",
                rtl ? "رقم الرحلة" : "Flight number",
              )}
              {field(
                "flightDepartureTime",
                rtl ? "وقت الإقلاع" : "Departure time",
                "time",
              )}
              {field(
                "flightArrivalTime",
                rtl ? "وقت الوصول" : "Arrival time",
                "time",
              )}
              {field(
                "flightArrivalCity",
                rtl ? "مدينة وصول رحلة الذهاب" : "Outbound arrival city",
              )}
              <div style={{ gridColumn:"1 / -1",padding:"12px 15px",borderRadius:12,background:T.camelMist,color:T.primary,font:"700 14px Alexandria" }}>{rtl?"2. الانتقال من المطار إلى الفندق":"2. Airport to hotel"}</div>
              {field(
                "airportTransferType",
                rtl ? "النقل من المطار إلى الفندق" : "Airport to hotel transfer",
                "text",
                rtl
                  ? ["نقل خاص", "قطار", "حافلة", "سيارة أجرة", "بدون نقل"]
                  : ["Private transfer", "Train", "Bus", "Taxi", "No transfer"],
              )}
              {field(
                "airportTransferTime",
                rtl ? "موعد التحرك من المطار" : "Airport transfer time",
                "time",
              )}
              <div style={{ gridColumn:"1 / -1",padding:"12px 15px",borderRadius:12,background:T.camelMist,color:T.primary,font:"700 14px Alexandria" }}>{rtl?"3. رحلة العودة":"3. Return flight"}</div>
              {field(
                "returnOriginCity",
                rtl ? "مدينة انطلاق رحلة العودة" : "Return departure city",
              )}
              {field(
                "returnDestinationCity",
                rtl ? "مدينة وصول رحلة العودة" : "Return arrival city",
              )}
              {field(
                "returnAirline",
                rtl ? "الناقل الجوي لرحلة العودة" : "Return airline",
              )}
              {field(
                "returnFlightNumber",
                rtl ? "رقم رحلة العودة" : "Return flight number",
              )}
              {field(
                "returnDepartureTime",
                rtl ? "وقت إقلاع رحلة العودة" : "Return departure time",
                "time",
              )}
              {field(
                "returnArrivalTime",
                rtl ? "وقت وصول رحلة العودة" : "Return arrival time",
                "time",
              )}
            </>
          )}
        </>
      )}
      {step === 2 && (
        <>
          {field("hotelName", rtl ? "اسم الفندق" : "Hotel name")}
          {field(
            "roomType",
            rtl ? "نوع الغرفة" : "Room type",
            "text",
            rtl
              ? ["مفردة", "مزدوجة", "ثلاثية", "رباعية"]
              : ["Single", "Double", "Triple", "Quad"],
          )}
          {field(
            "mealPlan",
            rtl ? "الإعاشة" : "Meal plan",
            "text",
            rtl
              ? ["بدون وجبات", "إفطار", "إفطار وعشاء", "ثلاث وجبات"]
              : ["Room only", "Breakfast", "Half board", "Full board"],
          )}
          <div
            style={{
              gridColumn: "1 / -1",
              padding: "14px 16px",
              borderRadius: 13,
              background: T.camelMist,
              color: T.text,
              font: "600 13px Alexandria",
            }}
          >
            {rtl
              ? `مدة الرحلة محسوبة تلقائياً: ${durationDays} أيام / ${nights} ليالٍ`
              : `Calculated trip duration: ${durationDays} days / ${nights} nights`}
          </div>
        </>
      )}
      {step === 3 && (
        <>
          {stepper(
            "seats",
            rtl ? "السعة بالأشخاص" : "Capacity (people)",
            1,
            999,
          )}
          {field(
            "pricePerPerson",
            rtl ? "سعر البالغ بالريال" : "Adult price",
            "number",
          )}
          {field(
            "childPrice",
            rtl ? "سعر الطفل بالريال" : "Child price",
            "number",
          )}
          {field(
            "infantPrice",
            rtl ? "سعر الرضيع بالريال" : "Infant price",
            "number",
          )}
          {field(
            "availableFrom",
            rtl ? "إتاحة الحجز من" : "Booking available from",
            "date",
          )}
          {field(
            "availableTo",
            rtl ? "إتاحة الحجز إلى" : "Booking available to",
            "date",
          )}
          {field(
            "bookingClosesHours",
            rtl
              ? "إغلاق الحجز قبل المغادرة (ساعة)"
              : "Booking closes before (hours)",
            "number",
          )}
        </>
      )}
    </div>
  );
  return (
    <div
      style={{ minHeight: 650, background: T.bg, padding: "28px 12px 70px" }}
    >
      <form
        onSubmit={save}
        style={{
          maxWidth: 760,
          margin: "0 auto",
          background: T.surface,
          border: `1px solid ${T.hairline}`,
          borderRadius: 22,
          padding: "clamp(18px,5vw,32px)",
          boxShadow: T.cardShadow,
        }}
      >
        <button
          type="button"
          onClick={() =>
            step ? setStep(step - 1) : setPage("provider-dashboard")
          }
          style={{
            border: 0,
            background: "transparent",
            color: T.textMuted,
            cursor: "pointer",
            fontFamily: "Alexandria",
          }}
        >
          →{" "}
          {step
            ? rtl
              ? "رجوع"
              : "Back"
            : rtl
              ? "العودة إلى باقاتي"
              : "Back to packages"}
        </button>
        <div style={{ margin: "18px 0 24px" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
            {steps.map((s, i) => (
              <React.Fragment key={s}>
                <div
                  style={{
                    width: 30,
                    height: 30,
                    borderRadius: 99,
                    display: "grid",
                    placeItems: "center",
                    background:
                      i < step
                        ? "#238753"
                        : i === step
                          ? T.primary
                          : T.surfaceAlt,
                    color: i <= step ? "#fff" : T.textMuted,
                    font: "700 12px Alexandria",
                  }}
                >
                  {i < step ? "✓" : i + 1}
                </div>
                {i < 3 && (
                  <div
                    style={{
                      height: 2,
                      flex: 1,
                      background: i < step ? "#238753" : T.hairlineStrong,
                    }}
                  />
                )}
              </React.Fragment>
            ))}
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(4,1fr)",
              gap: 4,
              marginTop: 8,
            }}
          >
            {steps.map((s, i) => (
              <span
                key={s}
                style={{
                  textAlign: "center",
                  color: i === step ? T.primary : T.textMuted,
                  font: "600 10px Alexandria",
                }}
              >
                {s}
              </span>
            ))}
          </div>
        </div>
        <h1
          style={{
            color: T.text,
            font: "700 25px Alexandria",
            marginBottom: 6,
          }}
        >
          {steps[step]}
        </h1>
        <p
          style={{
            color: T.textMuted,
            font: "400 12px/1.7 Alexandria",
            marginBottom: 22,
          }}
        >
          {rtl
            ? "أدخل بيانات الرحلة كما ستظهر للعميل في مسار حجز العمرة."
            : "Enter the journey details exactly as customers will see them."}
        </p>
        {grid}
        {message && (
          <p style={{ color: "#b42318", font: "600 12px Alexandria" }}>
            {message}
          </p>
        )}
        <button
          disabled={busy}
          type="submit"
          style={{
            width: "100%",
            minHeight: 52,
            marginTop: 24,
            border: 0,
            borderRadius: 13,
            background: T.primary,
            color: "#fff",
            font: "700 14px Alexandria",
            opacity: busy ? 0.6 : 1,
          }}
        >
          {busy
            ? rtl
              ? "جارٍ الحفظ…"
              : "Saving…"
            : step < 3
              ? rtl
                ? "متابعة"
                : "Continue"
              : rtl
                ? "مراجعة وإرسال للاعتماد"
                : "Review and submit"}
        </button>
      </form>
    </div>
  );
}

const PACKAGE_FEATURES_AR = [
  "إفطار يومي",
  "عشاء يومي",
  "نقل من المطار",
  "نقل إلى المطار",
  "مرشد ميداني",
  "تأمين سفر",
  "تأشيرة العمرة",
  "تذكرة طيران ذهاب وعودة",
  "مواصلات بين مكة والمدينة",
  "زيارات المزارات",
  "مياه زمزم",
  "رسوم إضافية",
];

function WebProviderEditPackagePage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { pkg, setPage } = useWeb(),
    token = localStorage.getItem("duyuf_provider_session");
  const [form, setForm] = React.useState(null),
    [images, setImages] = React.useState([]),
    [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  React.useEffect(() => {
    if (!pkg?.id) return setPage("provider-dashboard");
    fetch(`${window.DUYUF_API_URL}/v1/provider/packages/${pkg.id}`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((b) => {
        const p = b.package,
          occupancy = JSON.parse(p.occupancy_prices_json || "{}");
        setForm({
          title: p.title,
          hotelName: p.hotel_name,
          durationDays: p.duration_days,
          pricePerPerson: p.price_per_person,
          singlePrice: occupancy.single || "",
          doublePrice: occupancy.double || p.price_per_person,
          triplePrice: occupancy.triple || "",
          quadPrice: occupancy.quad || "",
          cancellationPolicy: p.cancellation_policy || "",
          paymentConfirmationMode: p.payment_confirmation_mode || "pay_on_arrival",
          supportsTabby: Boolean(p.supports_tabby),
          supportsTamara: Boolean(p.supports_tamara),
          availableFrom: p.available_from,
          availableTo: p.available_to,
          seats: p.seats,
          inclusions: JSON.parse(p.inclusions || "[]"),
          exclusions: JSON.parse(p.exclusions || "[]"),
          notes: p.notes || "",
        });
        setImages(b.images || []);
      })
      .catch(() =>
        setMessage(rtl ? "تعذر تحميل الباقة." : "Could not load package."),
      );
  }, []);
  const setFeature = (name, state) =>
    setForm((v) => ({
      ...v,
      inclusions:
        state === "in"
          ? [...new Set([...v.inclusions, name])]
          : v.inclusions.filter((x) => x !== name),
      exclusions:
        state === "out"
          ? [...new Set([...v.exclusions, name])]
          : v.exclusions.filter((x) => x !== name),
    }));
  const upload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setBusy(true);
    setMessage("");
    const fd = new FormData();
    fd.append("image", file);
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/provider/packages/${pkg.id}/images`,
        {
          method: "POST",
          headers: { authorization: `Bearer ${token}` },
          body: fd,
        },
      );
      const b = await r.json();
      if (!r.ok) throw new Error(b.error);
      setImages((v) => [...v, { id: b.image.id, storage_key: b.image.key }]);
      setMessage(rtl ? "تم رفع الصورة." : "Image uploaded.");
    } catch (e) {
      setMessage(
        rtl
          ? "تعذر رفع الصورة. استخدم JPG أو PNG أو WebP بحجم أقل من 3MB."
          : "Upload failed. Use JPG, PNG or WebP under 3MB.",
      );
    } finally {
      setBusy(false);
      e.target.value = "";
    }
  };
  const save = async (e) => {
    e.preventDefault();
    setBusy(true);
    setMessage("");
    try {
      const occupancyPrices = {
        single: Number(form.singlePrice) || 0,
        double: Number(form.doublePrice) || 0,
        triple: Number(form.triplePrice) || 0,
        quad: Number(form.quadPrice) || 0,
      };
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/provider/packages/${pkg.id}`,
        {
          method: "POST",
          headers: {
            "content-type": "application/json",
            authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({
            ...form,
            occupancyPrices,
            durationDays: Number(form.durationDays),
            pricePerPerson: Number(form.doublePrice || form.pricePerPerson),
            seats: Number(form.seats),
          }),
        },
      );
      const b = await r.json();
      if (!r.ok) throw new Error(b.error);
      setMessage(
        b.status === "pending"
          ? rtl
            ? "تم الحفظ وأُعيد إرسال التعديلات للاعتماد."
            : "Saved and resubmitted for approval."
          : rtl
            ? "تم حفظ التعديلات."
            : "Changes saved.",
      );
    } catch (e) {
      setMessage(
        rtl ? "تعذر حفظ التعديلات. راجع البيانات." : "Could not save changes.",
      );
    } finally {
      setBusy(false);
    }
  };
  if (!form)
    return (
      <div
        style={{
          minHeight: 600,
          padding: 40,
          background: T.bg,
          color: T.textMuted,
        }}
      >
        {message || (rtl ? "جارٍ التحميل…" : "Loading…")}
      </div>
    );
  const input = (key, label, type = "text") => (
    <label
      style={{
        display: "grid",
        gap: 6,
        color: T.textMuted,
        font: "500 12px Alexandria",
      }}
    >
      {label}
      <input
        type={type}
        value={form[key]}
        onChange={(e) => setForm({ ...form, [key]: e.target.value })}
        style={{
          height: 46,
          border: `1px solid ${T.hairlineStrong}`,
          borderRadius: 11,
          padding: "0 12px",
          background: T.bg,
          color: T.text,
          font: "500 14px Alexandria",
        }}
      />
    </label>
  );
  return (
    <div
      style={{ minHeight: 700, padding: "26px 16px 70px", background: T.bg }}
    >
      <form
        onSubmit={save}
        style={{
          maxWidth: 900,
          margin: "0 auto",
          padding: "clamp(18px,4vw,32px)",
          background: T.surface,
          border: `1px solid ${T.hairline}`,
          borderRadius: 20,
        }}
      >
        <button
          type="button"
          onClick={() => setPage("provider-dashboard")}
          style={{ border: 0, background: "transparent", color: T.textMuted }}
        >
          → {rtl ? "باقاتي" : "My packages"}
        </button>
        <h1 style={{ color: T.text, font: "700 27px Alexandria" }}>
          {rtl ? "تعديل الباقة والصور" : "Edit package & images"}
        </h1>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,220px),1fr))",
            gap: 14,
          }}
        >
          {input("title", rtl ? "اسم الباقة" : "Package title")}
          {input("hotelName", rtl ? "الفندق" : "Hotel")}
          {input("durationDays", rtl ? "عدد الأيام" : "Days", "number")}
          {input(
            "pricePerPerson",
            rtl ? "سعر الفرد" : "Price per person",
            "number",
          )}
          {input("availableFrom", rtl ? "متاحة من" : "Available from", "date")}
          {input("availableTo", rtl ? "متاحة إلى" : "Available to", "date")}
          {input("seats", rtl ? "السعة بالأشخاص" : "Capacity", "number")}
        </div>
        <h2
          style={{ color: T.text, font: "700 18px Alexandria", marginTop: 28 }}
        >
          {rtl ? "صور الباقة" : "Package images"}
        </h2>
        <p style={{ color: T.textMuted, font: "400 12px Alexandria" }}>
          {rtl
            ? "ارفع حتى 8 صور أصلية. الصورة الأولى ستكون صورة الغلاف."
            : "Upload up to 8 original images. The first image is the cover."}
        </p>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
          {images.map((img) => (
            <img
              key={img.id}
              src={`${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(img.storage_key)}`}
              alt=""
              style={{
                width: 120,
                height: 90,
                objectFit: "cover",
                borderRadius: 10,
                border: `1px solid ${T.hairline}`,
              }}
            />
          ))}
          <label
            style={{
              width: 120,
              height: 90,
              display: "grid",
              placeItems: "center",
              border: `1px dashed ${T.primary}`,
              borderRadius: 10,
              color: T.primary,
              font: "700 12px Alexandria",
              cursor: "pointer",
            }}
          >
            ＋ {rtl ? "رفع صورة" : "Upload"}
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp"
              onChange={upload}
              hidden
            />
          </label>
        </div>
        <h2
          style={{ color: T.text, font: "700 18px Alexandria", marginTop: 28 }}
        >
          {rtl ? "ما تشمله وما لا تشمله الباقة" : "Included and excluded"}
        </h2>
        <p style={{ color: T.textMuted, font: "400 12px/1.7 Alexandria" }}>
          {rtl
            ? "اختر لكل عنصر: تشمل، لا تشمل، أو اتركه بدون تحديد. عدد الليالي يُعرض تلقائيًا من مدة الباقة."
            : "Mark each item included, excluded, or leave it unset. Nights come automatically from duration."}
        </p>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,260px),1fr))",
            gap: 10,
          }}
        >
          {PACKAGE_FEATURES_AR.map((name) => {
            const state = form.inclusions.includes(name)
              ? "in"
              : form.exclusions.includes(name)
                ? "out"
                : "";
            return (
              <div
                key={name}
                style={{
                  padding: 12,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 12,
                }}
              >
                <div
                  style={{
                    color: T.text,
                    font: "600 12px Alexandria",
                    marginBottom: 8,
                  }}
                >
                  {name}
                </div>
                <div
                  style={{
                    display: "grid",
                    gridTemplateColumns: "1fr 1fr 1fr",
                    gap: 5,
                  }}
                >
                  {[
                    ["in", rtl ? "تشمل" : "Included"],
                    ["out", rtl ? "لا تشمل" : "Excluded"],
                    ["", rtl ? "بدون" : "Unset"],
                  ].map(([v, label]) => (
                    <button
                      type="button"
                      key={v}
                      onClick={() => setFeature(name, v)}
                      style={{
                        padding: "7px 5px",
                        border: `1px solid ${state === v ? T.primary : T.hairline}`,
                        borderRadius: 8,
                        background: state === v ? T.camelMist : "transparent",
                        color: state === v ? T.primary : T.textMuted,
                        font: "600 10px Alexandria",
                      }}
                    >
                      {label}
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
        <label
          style={{
            display: "grid",
            gap: 7,
            marginTop: 20,
            color: T.textMuted,
            font: "500 12px Alexandria",
          }}
        >
          {rtl ? "ملاحظات إضافية" : "Additional notes"}
          <textarea
            value={form.notes}
            onChange={(e) => setForm({ ...form, notes: e.target.value })}
            rows="4"
            style={{
              resize: "vertical",
              border: `1px solid ${T.hairlineStrong}`,
              borderRadius: 11,
              padding: 12,
              background: T.bg,
              color: T.text,
              font: "500 13px Alexandria",
            }}
          />
        </label>
        {message && (
          <p style={{ color: T.primary, font: "600 12px Alexandria" }}>
            {message}
          </p>
        )}
        <button
          disabled={busy}
          type="submit"
          style={{
            width: "100%",
            minHeight: 52,
            marginTop: 20,
            border: 0,
            borderRadius: 13,
            background: T.primary,
            color: "#fff",
            font: "700 14px Alexandria",
            opacity: busy ? 0.6 : 1,
          }}
        >
          {busy
            ? rtl
              ? "جارٍ الحفظ…"
              : "Saving…"
            : rtl
              ? "حفظ التعديلات"
              : "Save changes"}
        </button>
      </form>
    </div>
  );
}

function WebProviderBookingsPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { pkg, setPage } = useWeb(),
    token = localStorage.getItem("duyuf_provider_session");
  const [items, setItems] = React.useState([]),
    [loading, setLoading] = React.useState(true),
    [message, setMessage] = React.useState(""),
    [details, setDetails] = React.useState(null),
    [showPackage,setShowPackage]=React.useState(false),
    [detailsBusy, setDetailsBusy] = React.useState(false);
  const load = () => {
    if (!pkg?.id) return setPage("provider-dashboard");
    fetch(`${window.DUYUF_API_URL}/v1/provider/packages/${pkg.id}/bookings`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((b) => {setItems(b.bookings || []);setDetails(b.package||null);})
      .catch(() =>
        setMessage(rtl ? "تعذر تحميل الطلبات." : "Could not load bookings."),
      )
      .finally(() => setLoading(false));
  };
  React.useEffect(load, []);
  const status = async (id, next, reason="") => {
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/provider/bookings/${id}/status`,
      {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status: next,reason }),
      },
    );
    const body=await r.json().catch(()=>({}));
    if (r.ok){setMessage(rtl?"تم تحديث الحجز وسيظهر التحديث للعميل.":"Booking updated and visible to the customer.");load();}
    else setMessage(body.error==="reason_required"?(rtl?"سبب الإلغاء مطلوب.":"A reason is required."):(rtl?"تعذر تحديث الحالة.":"Could not update status."));
  };
  const cancel=(booking,next)=>{const reason=window.prompt(next==="cancelled"?(rtl?"اكتب سبب الإلغاء الذي سيظهر للعميل":"Enter the cancellation reason shown to the customer"):(rtl?"اكتب ملاحظة عدم الحضور":"Enter the no-show note"));if(reason?.trim())status(booking.id,next,reason.trim());};
  return (
    <div
      style={{ minHeight: 650, padding: "28px 16px 70px", background: T.bg }}
    >
      <div style={{ maxWidth: 1000, margin: "0 auto" }}>
        <button
          onClick={() => setPage("provider-dashboard")}
          style={{ border: 0, background: "transparent", color: T.textMuted }}
        >
          → {rtl ? "باقاتي" : "My packages"}
        </button>
        <h1 style={{ color: T.text, font: "700 27px Alexandria" }}>
          {rtl ? "طلبات الباقة ومواعيد الوصول" : "Package bookings & arrivals"}
        </h1>
        <p style={{ color: T.textMuted, font: "400 13px Alexandria" }}>
          {pkg?.title}
        </p>
        <div style={{display:"flex",gap:9,flexWrap:"wrap",marginBottom:18}}><button onClick={()=>setShowPackage(v=>!v)} style={{padding:"10px 14px",border:`1px solid ${T.hairlineStrong}`,borderRadius:10,background:T.surface,color:T.text}}>{showPackage?(rtl?"إخفاء تفاصيل الباقة":"Hide package"):(rtl?"استعراض الباقة":"View package")}</button><button onClick={()=>setPage("provider-edit-package")} style={{padding:"10px 14px",border:0,borderRadius:10,background:T.primary,color:"#fff"}}>{rtl?"تعديل الباقة والسعة":"Edit package & capacity"}</button></div>
        {showPackage&&details&&<section style={{padding:18,marginBottom:18,borderRadius:15,background:T.surface,border:`1px solid ${T.hairline}`,display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(170px,1fr))",gap:14}}><div><small>{rtl?"الفندق":"Hotel"}</small><strong style={{display:"block"}}>{details.hotel_name}</strong></div><div><small>{rtl?"نوع الرحلة":"Travel mode"}</small><strong style={{display:"block"}}>{details.travel_mode}</strong></div><div><small>{rtl?"المسار":"Route"}</small><strong style={{display:"block"}}>{details.origin_city} - {details.destination_city}</strong></div><div><small>{rtl?"السعة":"Capacity"}</small><strong style={{display:"block"}}>{details.seats}</strong></div><div><small>{rtl?"السداد":"Payment"}</small><strong style={{display:"block"}}>{details.payment_confirmation_mode==="prepay_required"?(rtl?"دفع مسبق":"Prepayment"):(rtl?"عند الوصول":"On arrival")}</strong></div><div><small>{rtl?"سياسة الإلغاء":"Cancellation policy"}</small><strong style={{display:"block"}}>{details.cancellation_policy||"—"}</strong></div></section>}
        {message && <p style={{ color: "#b42318" }}>{message}</p>}
        {loading ? (
          <p>{rtl ? "جارٍ التحميل…" : "Loading…"}</p>
        ) : items.length === 0 ? (
          <div
            style={{
              padding: 45,
              textAlign: "center",
              background: T.surface,
              border: `1px dashed ${T.hairlineStrong}`,
              borderRadius: 17,
              color: T.textMuted,
              font: "500 13px Alexandria",
            }}
          >
            {rtl
              ? "لا توجد حجوزات على هذه الباقة بعد. ستظهر هنا تلقائيًا بعد بدء الحجوزات."
              : "No bookings yet. They will appear here automatically."}
          </div>
        ) : (
          <div style={{ display: "grid", gap: 12 }}>
            {items.map((b) => (
              <article
                key={b.id}
                style={{
                  padding: 18,
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 15,
                  display: "grid",
                  gridTemplateColumns: "minmax(0,1fr) auto",
                  gap: 14,
                }}
              >
                <div>
                  <strong
                    style={{ color: T.text, font: "700 15px Alexandria" }}
                  >
                    {b.customer_name}
                  </strong>
                  <div
                    style={{
                      color: T.textMuted,
                      font: "400 12px/1.8 Alexandria",
                    }}
                  >
                    {b.customer_phone} · {b.travelers}{" "}
                    {rtl ? "أشخاص" : "people"}
                    <br />
                    {rtl ? "الوصول" : "Arrival"}: {b.arrival_at || "—"} ·{" "}
                    {rtl ? "المغادرة" : "Departure"}: {b.departure_at || "—"}
                    <br />
                    {rtl ? "الحالة" : "Status"}: {b.status}
                    <br />{rtl?"رقم الحجز":"Reference"}: <b dir="ltr">{b.booking_reference||"—"}</b>
                    <br />{rtl?"تفاصيل النزلاء":"Guests"}: {b.adults||0} {rtl?"بالغ":"adults"} · {b.children||0} {rtl?"طفل":"children"} · {b.infants||0} {rtl?"رضيع":"infants"}
                    <br />{rtl?"الغرف":"Rooms"}: {(b.rooms||[]).map(r=>`${r.count}× ${{single:rtl?"مفردة":"single",double:rtl?"مزدوجة":"double",triple:rtl?"ثلاثية":"triple",quad:rtl?"رباعية":"quad"}[r.type]||r.type}`).join(" · ")||"—"}
                    <br />{rtl?"القيمة والسداد":"Amount & payment"}: {Number(b.total_amount||0).toLocaleString()} {b.currency||"SAR"} · {b.payment_method==="pay_on_arrival"?(rtl?"الدفع عند الوصول":"Pay on arrival"):b.payment_status}
                    {b.customer_email&&<><br />{rtl?"البريد":"Email"}: {b.customer_email}</>}
                    {b.cancellation_reason&&<><br />{rtl?"سبب الإلغاء/عدم الحضور":"Cancellation / no-show reason"}: {b.cancellation_reason}</>}
                  </div>
                </div>
                <div
                  style={{
                    display: "flex",
                    gap: 7,
                    alignItems: "center",
                    flexWrap: "wrap",
                  }}
                >
                  {b.status === "confirmed" && (
                    <>
                    <button
                      onClick={() => status(b.id, "checked_in")}
                      style={{
                        padding: "9px 12px",
                        border: 0,
                        borderRadius: 9,
                        background: "#238753",
                        color: "#fff",
                        font: "700 11px Alexandria",
                      }}
                    >
                      {rtl ? "تسجيل دخول" : "Check-in"}
                    </button>
                    <button onClick={()=>cancel(b,"no_show")} style={{padding:"9px 12px",border:`1px solid #c47a15`,borderRadius:9,background:"#fff8eb",color:"#9a5b08",font:"700 11px Alexandria"}}>{rtl?"لم يحضر":"No-show"}</button>
                    <button onClick={()=>cancel(b,"cancelled")} style={{padding:"9px 12px",border:`1px solid #c93c37`,borderRadius:9,background:"#fff",color:"#b42318",font:"700 11px Alexandria"}}>{rtl?"إلغاء من المزود":"Cancel booking"}</button>
                    </>
                  )}
                  {b.status === "checked_in" && (
                    <button
                      onClick={() => status(b.id, "checked_out")}
                      style={{
                        padding: "9px 12px",
                        border: 0,
                        borderRadius: 9,
                        background: T.primary,
                        color: "#fff",
                        font: "700 11px Alexandria",
                      }}
                    >
                      {rtl ? "تسجيل خروج" : "Check-out"}
                    </button>
                  )}
                </div>
              </article>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function WebAdminLoginPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb();
  const [phone, setPhone] = React.useState(""),
    [otp, setOtp] = React.useState(""),
    [step, setStep] = React.useState("phone"),
    [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  const verifying = React.useRef(false);
  React.useEffect(() => {
    if (localStorage.getItem("duyuf_admin_session")) setPage("admin-dashboard");
  }, []);
  const normalized = () => {
    const d = phone.replace(/\D/g, "");
    if (/^05\d{8}$/.test(d)) return `+966${d.slice(1)}`;
    if (/^5\d{8}$/.test(d)) return `+966${d}`;
    return "";
  };
  const send = async () => {
    const mobile = normalized();
    if (!mobile)
      return setMessage(
        rtl ? "أدخل رقم جوال سعودي صحيح." : "Enter a valid Saudi mobile.",
      );
    setBusy(true);
    setMessage("");
    try {
      if (window.duyufAdminRecaptcha) window.duyufAdminRecaptcha.clear();
      window.duyufAdminRecaptcha = new firebase.auth.RecaptchaVerifier(
        "duyuf-admin-recaptcha",
        { size: "invisible" },
      );
      window.duyufAdminConfirmation = await firebase
        .auth()
        .signInWithPhoneNumber(mobile, window.duyufAdminRecaptcha);
      setStep("otp");
      setMessage(
        rtl ? "أرسلنا رمز التحقق إلى جوالك." : "Verification code sent.",
      );
    } catch (e) {
      console.error(e);
      setMessage(rtl ? "تعذر إرسال الرمز." : "Could not send the code.");
    } finally {
      setBusy(false);
    }
  };
  const verify = async (value) => {
    const code = value || otp;
    if (!/^\d{6}$/.test(code) || verifying.current) return;
    verifying.current = true;
    setBusy(true);
    setMessage("");
    try {
      const credential = await window.duyufAdminConfirmation.confirm(code);
      const idToken = await credential.user.getIdToken(true);
      const response = await fetch(
        `${window.DUYUF_API_URL}/v1/auth/firebase-admin`,
        {
          method: "POST",
          headers: { "content-type": "application/json" },
          body: JSON.stringify({ idToken }),
        },
      );
      const body = await response.json();
      if (!response.ok) throw new Error(body.error || "login_failed");
      localStorage.setItem("duyuf_admin_session", body.sessionToken);
      localStorage.setItem("duyuf_admin", JSON.stringify(body.admin));
      setPage("admin-dashboard");
    } catch (e) {
      console.error(e);
      setMessage(
        e.message === "not_admin"
          ? rtl
            ? "هذا الرقم غير مصرح له كأدمن."
            : "This number is not an admin."
          : rtl
            ? "تعذر الدخول أو رمز التحقق غير صحيح."
            : "Sign-in failed or the code is invalid.",
      );
    } finally {
      setBusy(false);
      verifying.current = false;
    }
  };
  return (
    <div style={{ minHeight: 620, padding: "50px 16px", background: T.bg }}>
      <div
        style={{
          maxWidth: 460,
          margin: "0 auto",
          padding: "clamp(22px,6vw,36px)",
          background: T.surface,
          border: `1px solid ${T.hairline}`,
          borderRadius: 22,
          boxShadow: T.cardShadow,
        }}
      >
        <div style={{ textAlign: "center" }}>
          <DuyufMark size={44} color={T.primary} />
          <h1 style={{ font: "700 25px Alexandria", color: T.text }}>
            {rtl ? "دخول إدارة ضيوف" : "Duyuf admin sign-in"}
          </h1>
          <p style={{ font: "400 13px Alexandria", color: T.textMuted }}>
            {rtl
              ? "الدخول متاح لأرقام الأدمن المعتمدة فقط."
              : "Only approved admin numbers can sign in."}
          </p>
        </div>
        {step === "phone" ? (
          <div
            dir="ltr"
            style={{
              display: "flex",
              height: 52,
              border: `1.5px solid ${T.primary}`,
              borderRadius: 14,
              overflow: "hidden",
            }}
          >
            <span
              style={{
                display: "flex",
                alignItems: "center",
                padding: "0 12px",
                borderRight: `1px solid ${T.hairline}`,
                color: T.text,
              }}
            >
              🇸🇦 +966
            </span>
            <input
              value={phone}
              onChange={(e) =>
                setPhone(e.target.value.replace(/\D/g, "").slice(0, 10))
              }
              inputMode="numeric"
              placeholder="5xxxxxxxx"
              style={{
                minWidth: 0,
                flex: 1,
                border: 0,
                outline: 0,
                padding: "0 12px",
                background: "transparent",
                color: T.text,
                font: "500 16px Alexandria",
              }}
            />
          </div>
        ) : (
          <input
            value={otp}
            onChange={(e) => {
              const v = e.target.value.replace(/\D/g, "").slice(0, 6);
              setOtp(v);
              if (v.length === 6) setTimeout(() => verify(v), 0);
            }}
            inputMode="numeric"
            autoComplete="one-time-code"
            dir="ltr"
            placeholder="••••••"
            style={{
              width: "100%",
              height: 52,
              boxSizing: "border-box",
              border: `1.5px solid ${T.primary}`,
              borderRadius: 14,
              background: T.bg,
              color: T.text,
              textAlign: "center",
              letterSpacing: 8,
              fontSize: 22,
            }}
          />
        )}
        <div id="duyuf-admin-recaptcha"></div>
        {message && (
          <p style={{ color: "#b42318", font: "500 12px/1.6 Alexandria" }}>
            {message}
          </p>
        )}
        <button
          disabled={busy}
          onClick={step === "phone" ? send : () => verify()}
          style={{
            width: "100%",
            minHeight: 52,
            marginTop: 18,
            border: 0,
            borderRadius: 14,
            background: T.primary,
            color: "#fff",
            font: "700 15px Alexandria",
            opacity: busy ? 0.6 : 1,
          }}
        >
          {busy
            ? rtl
              ? "جارٍ التنفيذ…"
              : "Please wait…"
            : step === "phone"
              ? rtl
                ? "إرسال رمز التحقق"
                : "Send verification code"
              : rtl
                ? "تحقق وادخل"
                : "Verify and sign in"}
        </button>
      </div>
    </div>
  );
}

function WebAdminDashboardPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb();
  const [items, setItems] = React.useState([]),
    [loading, setLoading] = React.useState(true),
    [message, setMessage] = React.useState("");
  const load = () => {
    const token = localStorage.getItem("duyuf_admin_session");
    if (!token) {
      setPage("admin-login");
      return;
    }
    setLoading(true);
    fetch(`${window.DUYUF_API_URL}/v1/admin/packages?status=pending`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then(async (r) => {
        const b = await r.json();
        if (!r.ok) throw new Error(b.error);
        setItems(b.packages || []);
      })
      .catch(() => {
        localStorage.removeItem("duyuf_admin_session");
        setPage("admin-login");
      })
      .finally(() => setLoading(false));
  };
  React.useEffect(load, []);
  const view = async (id) => {
    setDetailsBusy(true);
    setMessage("");
    try {
      const token = localStorage.getItem("duyuf_admin_session");
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(id)}`,
        { headers: { authorization: `Bearer ${token}` } },
      );
      const b = await r.json();
      if (!r.ok) throw new Error(b.error);
      setDetails(b);
    } catch (_) {
      setMessage(
        rtl ? "تعذر تحميل تفاصيل الباقة." : "Could not load package details.",
      );
    } finally {
      setDetailsBusy(false);
    }
  };
  const review = async (id, decision) => {
    setMessage("");
    const token = localStorage.getItem("duyuf_admin_session");
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(id)}/review`,
      {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ decision }),
      },
    );
    if (r.ok) {
      setItems((v) => v.filter((x) => x.id !== id));
      setMessage(
        decision === "approve"
          ? rtl
            ? "تم اعتماد الباقة ونشرها."
            : "Package approved."
          : rtl
            ? "تم رفض الباقة."
            : "Package rejected.",
      );
    } else
      setMessage(rtl ? "تعذر تنفيذ القرار." : "Could not complete the action.");
  };
  const parse = (value) => {
    try {
      return JSON.parse(value || "[]");
    } catch (_) {
      return [];
    }
  };
  const detailPanel =
    details &&
    (() => {
      const p = details.package,
        inc = parse(p.inclusions),
        exc = parse(p.exclusions);
      const rows = [
        [rtl ? "المزود" : "Provider", `${p.business_name} · ${p.phone}`],
        [
          rtl ? "نوع العمرة" : "Umrah type",
          p.travel_mode === "bus"
            ? rtl
              ? "بالحافلة"
              : "Bus"
            : rtl
              ? "بالطائرة"
              : "Flight",
        ],
        [
          rtl ? "المسار" : "Route",
          `${p.origin_city || "—"} ← ${p.destination_city || "—"}`,
        ],
        [
          rtl ? "الموعد" : "Schedule",
          `${p.departure_at || "—"} — ${p.return_at || "—"}`,
        ],
        [
          rtl ? "النقل" : "Transport",
          p.travel_mode === "bus"
            ? p.bus_type || "—"
            : [p.airline, p.flight_number].filter(Boolean).join(" · ") || "—",
        ],
        ...(p.travel_mode === "flight"
          ? [
              [
                rtl ? "رحلة الذهاب" : "Outbound flight",
                `${p.origin_city || "—"} ← ${p.flight_arrival_city || "—"} · ${p.departure_at || "—"} · ${[p.airline, p.flight_number].filter(Boolean).join(" · ")}`,
              ],
              [
                rtl ? "النقل من المطار" : "Airport transfer",
                [p.airport_transfer_at, p.airport_transfer_type]
                  .filter(Boolean)
                  .join(" · ") || "—",
              ],
              [
                rtl ? "رحلة العودة" : "Return flight",
                `${p.return_origin_city || "—"} ← ${p.return_destination_city || "—"} · ${p.return_departure_at || "—"} · ${[p.return_airline, p.return_flight_number].filter(Boolean).join(" · ")}`,
              ],
            ]
          : []),
        [
          rtl ? "الفندق والغرفة" : "Hotel & room",
          `${p.hotel_name} · ${p.room_type || "—"} · ${p.meal_plan || "—"}`,
        ],
        [
          rtl ? "المدة" : "Duration",
          `${p.duration_days} ${rtl ? "أيام" : "days"}`,
        ],
        [rtl ? "السعة" : "Capacity", `${p.seats} ${rtl ? "شخص" : "people"}`],
        [
          rtl ? "الأسعار" : "Prices",
          `${rtl ? "بالغ" : "Adult"} ${Number(p.adult_price || p.price_per_person).toLocaleString()} · ${rtl ? "طفل" : "Child"} ${Number(p.child_price || 0).toLocaleString()} · ${rtl ? "رضيع" : "Infant"} ${Number(p.infant_price || 0).toLocaleString()} ${rtl ? "ر.س" : "SAR"}`,
        ],
        [
          rtl ? "إتاحة الحجز" : "Booking window",
          `${p.available_from} — ${p.available_to}`,
        ],
        [
          rtl ? "إغلاق الحجز" : "Booking closes",
          `${p.booking_closes_hours || 72} ${rtl ? "ساعة قبل المغادرة" : "hours before departure"}`,
        ],
      ];
      return (
        <section
          style={{
            marginTop: 22,
            padding: "clamp(16px,4vw,26px)",
            background: T.surface,
            border: `2px solid ${T.primary}`,
            borderRadius: 20,
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              gap: 12,
            }}
          >
            <div>
              <span style={{ color: T.primary, font: "600 11px Alexandria" }}>
                {rtl
                  ? "مراجعة كاملة قبل الاعتماد"
                  : "Full review before approval"}
              </span>
              <h2
                style={{
                  color: T.text,
                  font: "700 23px Alexandria",
                  margin: "5px 0",
                }}
              >
                {p.title}
              </h2>
            </div>
            <button
              onClick={() => setDetails(null)}
              style={{
                width: 40,
                height: 40,
                border: 0,
                borderRadius: 99,
                background: T.bg,
                color: T.text,
                fontSize: 24,
              }}
            >
              ×
            </button>
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns:
                "repeat(auto-fit,minmax(min(100%,240px),1fr))",
              gap: 9,
              marginTop: 18,
            }}
          >
            {rows.map(([k, v]) => (
              <div
                key={k}
                style={{ padding: 12, borderRadius: 11, background: T.bg }}
              >
                <small
                  style={{
                    display: "block",
                    color: T.textMuted,
                    font: "500 10px Alexandria",
                    marginBottom: 5,
                  }}
                >
                  {k}
                </small>
                <strong
                  style={{ color: T.text, font: "600 12px/1.7 Alexandria" }}
                >
                  {v}
                </strong>
              </div>
            ))}
          </div>
          <p
            style={{
              padding: 12,
              borderRadius: 10,
              background: T.camelMist,
              color: T.textMuted,
              font: "600 12px/1.8 Alexandria",
            }}
          >
            {rtl
              ? "أوقات البرنامج ونقطة التجمع يحددها المزود من إعدادات كل مدينة؛ الأدمن يراجعها فقط."
              : "The provider sets itinerary times and meeting point per city; admin review is read-only."}
          </p>
          <h3 style={{ color: T.text, font: "700 15px Alexandria" }}>
            {rtl ? "الصور المرفقة" : "Attached images"}
          </h3>
          <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
            {details.images.length ? (
              details.images.map((img) => (
                <img
                  key={img.id}
                  src={`${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(img.storage_key)}`}
                  alt=""
                  style={{
                    width: 150,
                    height: 105,
                    objectFit: "cover",
                    borderRadius: 11,
                    border: `1px solid ${T.hairline}`,
                  }}
                />
              ))
            ) : (
              <span style={{ color: T.textMuted, font: "500 12px Alexandria" }}>
                {rtl ? "لا توجد صور مرفقة." : "No images attached."}
              </span>
            )}
          </div>
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 12,
              marginTop: 18,
            }}
          >
            <div>
              <h3 style={{ color: "#238753", font: "700 14px Alexandria" }}>
                {rtl ? "تشمل الباقة" : "Included"}
              </h3>
              <ul
                style={{
                  color: T.text,
                  font: "500 12px/1.9 Alexandria",
                  paddingInlineStart: 20,
                }}
              >
                {inc.length ? (
                  inc.map((x) => <li key={x}>{x}</li>)
                ) : (
                  <li>{rtl ? "لم يحدد المزود عناصر." : "Not specified."}</li>
                )}
              </ul>
            </div>
            <div>
              <h3 style={{ color: "#b42318", font: "700 14px Alexandria" }}>
                {rtl ? "لا تشمل الباقة" : "Excluded"}
              </h3>
              <ul
                style={{
                  color: T.text,
                  font: "500 12px/1.9 Alexandria",
                  paddingInlineStart: 20,
                }}
              >
                {exc.length ? (
                  exc.map((x) => <li key={x}>{x}</li>)
                ) : (
                  <li>{rtl ? "لم يحدد المزود عناصر." : "Not specified."}</li>
                )}
              </ul>
            </div>
          </div>
          {p.notes && (
            <p
              style={{
                padding: 12,
                background: T.bg,
                borderRadius: 11,
                color: T.text,
                font: "500 12px/1.8 Alexandria",
              }}
            >
              {p.notes}
            </p>
          )}
          <div
            style={{ display: "flex", gap: 9, marginTop: 18, flexWrap: "wrap" }}
          >
            <button
              onClick={() => {
                review(p.id, "approve");
                setDetails(null);
              }}
              style={{
                padding: "12px 22px",
                border: 0,
                borderRadius: 11,
                background: "#238753",
                color: "#fff",
                font: "700 13px Alexandria",
              }}
            >
              {rtl ? "اعتماد ونشر" : "Approve & publish"}
            </button>
            <button
              onClick={() => {
                review(p.id, "reject");
                setDetails(null);
              }}
              style={{
                padding: "12px 22px",
                border: "1px solid #b42318",
                borderRadius: 11,
                background: "transparent",
                color: "#b42318",
                font: "700 13px Alexandria",
              }}
            >
              {rtl ? "رفض" : "Reject"}
            </button>
          </div>
        </section>
      );
    })();
  return (
    <div
      style={{ minHeight: 650, padding: "30px 16px 70px", background: T.bg }}
    >
      <div style={{ maxWidth: 1050, margin: "0 auto" }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            gap: 12,
            flexWrap: "wrap",
          }}
        >
          <div>
            <span style={{ color: T.primary, font: "600 12px Alexandria" }}>
              {rtl ? "إدارة ضيوف" : "Duyuf administration"}
            </span>
            <h1
              style={{
                color: T.text,
                font: "700 30px Alexandria",
                margin: "5px 0",
              }}
            >
              {rtl ? "طلبات اعتماد الباقات" : "Package approval requests"}
            </h1>
          </div>
          <button
            onClick={() => {
              localStorage.removeItem("duyuf_admin_session");
              setPage("admin-login");
            }}
            style={{
              padding: "10px 16px",
              border: `1px solid ${T.hairlineStrong}`,
              borderRadius: 11,
              background: T.surface,
              color: T.text,
              font: "600 12px Alexandria",
            }}
          >
            {rtl ? "تسجيل الخروج" : "Sign out"}
          </button>
        </div>
        {message && (
          <p
            style={{
              padding: 12,
              borderRadius: 10,
              background: T.surfaceAlt,
              color: T.text,
              font: "600 12px Alexandria",
            }}
          >
            {message}
          </p>
        )}
        {loading ? (
          <p style={{ color: T.textMuted }}>
            {rtl ? "جارٍ التحميل…" : "Loading…"}
          </p>
        ) : items.length === 0 ? (
          <div
            style={{
              marginTop: 24,
              padding: 45,
              textAlign: "center",
              background: T.surface,
              border: `1px dashed ${T.hairlineStrong}`,
              borderRadius: 18,
              color: T.textMuted,
              font: "500 14px Alexandria",
            }}
          >
            {rtl
              ? "لا توجد باقات بانتظار الاعتماد."
              : "No packages are awaiting approval."}
          </div>
        ) : (
          <div style={{ display: "grid", gap: 14, marginTop: 24 }}>
            {items.map((p) => (
              <article
                key={p.id}
                style={{
                  display: "grid",
                  gridTemplateColumns: "minmax(0,1fr) auto",
                  gap: 20,
                  padding: 22,
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 17,
                }}
              >
                <div>
                  <span
                    style={{ color: T.primary, font: "600 11px Alexandria" }}
                  >
                    {p.business_name} · {p.phone}
                  </span>
                  <h2
                    style={{
                      color: T.text,
                      font: "700 19px Alexandria",
                      margin: "7px 0",
                    }}
                  >
                    {p.title}
                  </h2>
                  <p
                    style={{
                      color: T.textMuted,
                      font: "400 12px/1.8 Alexandria",
                      margin: 0,
                    }}
                  >
                    {p.hotel_name} · {p.duration_days} {rtl ? "أيام" : "days"} ·{" "}
                    {p.seats} {rtl ? "شخص" : "people"}
                    <br />
                    {p.available_from} — {p.available_to}
                  </p>
                  <strong
                    style={{
                      display: "block",
                      marginTop: 8,
                      color: T.primary,
                      font: "700 20px Alexandria",
                    }}
                  >
                    {Number(p.price_per_person).toLocaleString()}{" "}
                    {rtl ? "ر.س / فرد" : "SAR / person"}
                  </strong>
                </div>
                <div
                  style={{
                    display: "flex",
                    gap: 9,
                    alignItems: "center",
                    flexWrap: "wrap",
                  }}
                >
                  <button
                    onClick={() => review(p.id, "approve")}
                    style={{
                      padding: "12px 18px",
                      border: 0,
                      borderRadius: 11,
                      background: "#238753",
                      color: "#fff",
                      font: "700 13px Alexandria",
                    }}
                  >
                    {rtl ? "اعتماد" : "Approve"}
                  </button>
                  <button
                    onClick={() => review(p.id, "reject")}
                    style={{
                      padding: "12px 18px",
                      border: "1px solid #b42318",
                      borderRadius: 11,
                      background: "transparent",
                      color: "#b42318",
                      font: "700 13px Alexandria",
                    }}
                  >
                    {rtl ? "رفض" : "Reject"}
                  </button>
                </div>
              </article>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function WebUmrahJourneyPage({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage, setPkg, umrahSearch } = useWeb();
  const [step, setStep] = React.useState(0),
    [mode, setMode] = React.useState(""),
    [origin, setOrigin] = React.useState(umrahSearch?.origin || ""),
    [destination, setDestination] = React.useState(
      umrahSearch?.destination || "",
    ),
    [departure, setDeparture] = React.useState(umrahSearch?.date || ""),
    [travelers, setTravelers] = React.useState({
      adult: Number(umrahSearch?.travelers || 1),
      child: 0,
      infant: 0,
    }),
    [packages, setPackages] = React.useState([]),
    [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    fetch(`${window.DUYUF_API_URL}/v1/public/packages`)
      .then((r) => r.json())
      .then((b) => setPackages(b.packages || []))
      .finally(() => setLoading(false));
  }, []);
  const modePackages = packages.filter((p) => p.travel_mode === mode),
    origins = [
      ...new Set(modePackages.map((p) => p.origin_city).filter(Boolean)),
    ],
    destinations = [
      ...new Set(
        modePackages
          .filter((p) => !origin || p.origin_city === origin)
          .map((p) => p.destination_city)
          .filter(Boolean),
      ),
    ],
    routePackages = modePackages.filter(
      (p) =>
        (!origin || p.origin_city === origin) &&
        (!destination || p.destination_city === destination),
    ),
    dates = [
      ...new Set(routePackages.map((p) => p.departure_at).filter(Boolean)),
    ],
    total = travelers.adult + travelers.child + travelers.infant,
    results = routePackages.filter(
      (p) =>
        (!departure || p.departure_at === departure) &&
        Number(p.seats) >= total,
    );
  const choose = (p) => {
    setPkg({
      id: p.id,
      hotel: p.hotel_name,
      title: p.title,
      dist: rtl
        ? `${p.origin_city} إلى ${p.destination_city}`
        : `${p.origin_city} to ${p.destination_city}`,
      stars: 5,
      nights: Math.max(1, Number(p.duration_days) - 1),
      price: Number(p.price_per_person),
      seats: Number(p.seats),
      board: p.meal_plan || "",
      tone: "camel",
      provider: p.business_name,
      dates: `${p.departure_at || p.available_from} — ${p.return_at || p.available_to}`,
      imageUrl: p.cover_key
        ? `${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(p.cover_key)}`
        : "",
      inclusions: parseJson(p.inclusions),
      exclusions: parseJson(p.exclusions),
      notes: p.notes || "",
      isDynamic: true,
      travelMode: p.travel_mode,
      originCity: p.origin_city,
      destinationCity: p.destination_city,
      departureAt: p.departure_at,
      returnAt: p.return_at,
      busType: p.bus_type,
      airline: p.airline,
      flightNumber: p.flight_number,
      airportTransferType: p.airport_transfer_type,
      airportTransferAt: p.airport_transfer_at,
      flightArrivalCity: p.flight_arrival_city,
      returnOriginCity: p.return_origin_city,
      returnDestinationCity: p.return_destination_city,
      returnDepartureAt: p.return_departure_at,
      returnAirline: p.return_airline,
      returnFlightNumber: p.return_flight_number,
      roomType: p.room_type,
      mealPlan: p.meal_plan,
      meetingPoint: p.provider_meeting_name || p.meeting_point,
      meetingAddress: p.provider_meeting_address,
      meetingLatitude: p.provider_meeting_latitude,
      meetingLongitude: p.provider_meeting_longitude,
      meetingAt: p.provider_departure_time || p.meeting_at,
      boardingAt: p.boarding_at,
      arrivalAt: p.provider_arrival_time || p.arrival_at,
      hotelDepartureAt: p.provider_hotel_departure_time || p.hotel_departure_at,
      returnArrivalAt: p.provider_return_arrival_time || p.return_arrival_at,
      itineraryNotes: p.itinerary_notes,
      travelers,
    });
    setPage("detail");
  };
  const parseJson = (v) => {
    try {
      return JSON.parse(v || "[]");
    } catch (_) {
      return [];
    }
  };
  const cardStyle = (active) => ({
    padding: 18,
    borderRadius: 16,
    border: `2px solid ${active ? T.primary : T.hairline}`,
    background: active ? T.camelMist : T.surface,
    color: T.text,
    textAlign: "start",
    fontFamily: "Alexandria",
    cursor: "pointer",
  });
  const next = () => {
    if (step === 0 && mode) setStep(1);
    else if (step === 1 && origin && destination) setStep(2);
    else if (step === 2 && departure) setStep(3);
    else if (step === 3) setStep(4);
  };
  const counter = (key, label) => {
    const value = travelers[key],
      min = key === "adult" ? 1 : 0;
    return (
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          padding: 15,
          borderBottom: `1px solid ${T.hairline}`,
        }}
      >
        <div>
          <strong style={{ color: T.text, font: "700 14px Alexandria" }}>
            {label}
          </strong>
        </div>
        <div
          dir="ltr"
          style={{ display: "flex", alignItems: "center", gap: 14 }}
        >
          <button
            onClick={() =>
              setTravelers((v) => ({ ...v, [key]: Math.max(min, value - 1) }))
            }
            style={{
              width: 38,
              height: 38,
              borderRadius: 99,
              border: 0,
              background: T.surfaceAlt,
              fontSize: 22,
            }}
          >
            −
          </button>
          <b style={{ minWidth: 20, textAlign: "center" }}>{value}</b>
          <button
            onClick={() => setTravelers((v) => ({ ...v, [key]: value + 1 }))}
            style={{
              width: 38,
              height: 38,
              borderRadius: 99,
              border: 0,
              background: T.primary,
              color: "#fff",
              fontSize: 20,
            }}
          >
            +
          </button>
        </div>
      </div>
    );
  };
  const titles = rtl
    ? [
        "اختر نوع العمرة",
        "اختر المسار",
        "موعد الرحلة",
        "المسافرون",
        "الباقات المتاحة",
      ]
    : [
        "Choose Umrah type",
        "Choose route",
        "Trip date",
        "Travelers",
        "Available packages",
      ];
  return (
    <div
      style={{ minHeight: 680, padding: "30px 14px 80px", background: T.bg }}
    >
      <main style={{ maxWidth: 760, margin: "0 auto" }}>
        <button
          disabled={step === 0}
          onClick={() => setStep(Math.max(0, step - 1))}
          style={{
            border: 0,
            background: "transparent",
            color: T.textMuted,
            font: "600 12px Alexandria",
            opacity: step === 0 ? 0.35 : 1,
          }}
        >
          → {rtl ? "رجوع" : "Back"}
        </button>
        <div style={{ display: "flex", gap: 5, margin: "18px 0" }}>
          {titles.map((_, i) => (
            <span
              key={i}
              style={{
                height: 4,
                flex: 1,
                borderRadius: 99,
                background: i <= step ? T.primary : T.hairlineStrong,
              }}
            />
          ))}
        </div>
        <span style={{ color: T.primary, font: "600 11px Alexandria" }}>
          {rtl ? `الخطوة ${step + 1} من 5` : `Step ${step + 1} of 5`}
        </span>
        <h1
          style={{
            color: T.text,
            font: "700 clamp(26px,7vw,38px) Alexandria",
            margin: "7px 0 22px",
          }}
        >
          {titles[step]}
        </h1>
        {loading ? (
          <p>{rtl ? "جارٍ تحميل الرحلات…" : "Loading trips…"}</p>
        ) : (
          <>
            {step === 0 && (
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))",
                  gap: 14,
                }}
              >
                <button
                  onClick={() => setMode("flight")}
                  style={cardStyle(mode === "flight")}
                >
                  <Icon name="plane" size={25} color={T.primary} />
                  <h2>{rtl ? "عمرة بالطائرة" : "Umrah by flight"}</h2>
                  <p style={{ color: T.textMuted }}>
                    {rtl
                      ? "رحلات مجدولة شاملة الطيران والإقامة"
                      : "Scheduled flight and stay packages"}
                  </p>
                </button>
                <button
                  onClick={() => setMode("bus")}
                  style={cardStyle(mode === "bus")}
                >
                  <Icon name="bus" size={25} color={T.primary} />
                  <h2>{rtl ? "عمرة بالحافلة" : "Umrah by bus"}</h2>
                  <p style={{ color: T.textMuted }}>
                    {rtl
                      ? "اختر المسار ونوع الحافلة والفندق"
                      : "Choose route, bus type and hotel"}
                  </p>
                </button>
              </div>
            )}
            {step === 1 && (
              <div style={{ display: "grid", gap: 10 }}>
                {origin && (
                  <label style={{ display: "grid", gap: 7, color: T.textMuted, font: "600 12px Alexandria" }}>
                    {rtl ? "إلى — الوجهة" : "To — destination"}
                    <select
                      value={destination}
                      onChange={(e) => { setDestination(e.target.value); setDeparture(""); }}
                      style={{ height: 54, padding: "0 14px", border: `1px solid ${T.hairlineStrong}`, borderRadius: 13, background: T.surface, color: T.text, font: "700 14px Alexandria" }}
                    >
                      <option value="">{rtl ? "اختر الوجهة" : "Select destination"}</option>
                      {destinations.map((city) => <option key={city} value={city}>{city}</option>)}
                    </select>
                  </label>
                )}
                {origins.length ? (
                  origins.map((city) => (
                    <button
                      key={city}
                      onClick={() => { setOrigin(city); setDestination(""); setDeparture(""); }}
                      style={cardStyle(origin === city)}
                    >
                      <strong>{city}</strong>
                      <span
                        style={{
                          display: "block",
                          marginTop: 5,
                          color: T.textMuted,
                          fontSize: 12,
                        }}
                      >
                        {
                          modePackages.filter((p) => p.origin_city === city)
                            .length
                        }{" "}
                        {rtl ? "رحلات متاحة" : "available trips"}
                      </span>
                    </button>
                  ))
                ) : (
                  <p style={{ color: T.textMuted }}>
                    {rtl
                      ? "لا توجد مدن انطلاق متاحة لهذا النوع حالياً."
                      : "No departure cities available."}
                  </p>
                )}
              </div>
            )}
            {step === 2 && (
              <div style={{ display: "grid", gap: 10 }}>
                {dates.map((date) => (
                  <button
                    key={date}
                    onClick={() => setDeparture(date)}
                    style={cardStyle(departure === date)}
                  >
                    <Icon name="calendar" size={18} color={T.primary} />{" "}
                    <strong style={{ marginInlineStart: 8 }}>{date}</strong>
                  </button>
                ))}
              </div>
            )}
            {step === 3 && (
              <div
                style={{
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  borderRadius: 16,
                }}
              >
                {counter("adult", rtl ? "بالغ" : "Adult")}
                {counter("child", rtl ? "طفل" : "Child")}
                {counter("infant", rtl ? "رضيع" : "Infant")}
                <p
                  style={{
                    padding: "0 15px",
                    color: T.textMuted,
                    font: "500 11px Alexandria",
                  }}
                >
                  {rtl
                    ? `الإجمالي: ${total} مسافرين`
                    : `Total: ${total} travelers`}
                </p>
              </div>
            )}
            {step === 4 && (
              <div style={{ display: "grid", gap: 13 }}>
                {results.length ? (
                  results.map((p) => (
                    <article
                      key={p.id}
                      style={{
                        padding: 18,
                        borderRadius: 17,
                        background: T.surface,
                        border: `1px solid ${T.hairline}`,
                      }}
                    >
                      <small
                        style={{
                          color: T.primary,
                          font: "600 11px Alexandria",
                        }}
                      >
                        {p.travel_mode === "bus"
                          ? p.bus_type || (rtl ? "حافلة" : "Bus")
                          : [p.airline, p.flight_number].filter(Boolean).join(" · ") ||
                            (rtl ? "طيران" : "Flight")}{" "}
                        · {p.business_name}
                      </small>
                      <h2
                        style={{
                          color: T.text,
                          font: "700 19px Alexandria",
                          margin: "7px 0",
                        }}
                      >
                        {p.title}
                      </h2>
                      <p
                        style={{
                          color: T.textMuted,
                          font: "500 12px/1.8 Alexandria",
                        }}
                      >
                        {p.origin_city} ← {p.destination_city}
                        <br />
                        {p.departure_at} — {p.return_at}
                        <br />
                        {p.hotel_name} · {p.room_type || ""} ·{" "}
                        {p.meal_plan || ""}
                      </p>
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "center",
                          gap: 10,
                          flexWrap: "wrap",
                        }}
                      >
                        <strong
                          style={{
                            color: T.primary,
                            font: "700 21px Alexandria",
                          }}
                        >
                          {Number(p.price_per_person).toLocaleString()}{" "}
                          {rtl ? "ر.س / بالغ" : "SAR / adult"}
                        </strong>
                        <button
                          onClick={() => choose(p)}
                          style={{
                            padding: "11px 17px",
                            border: 0,
                            borderRadius: 11,
                            background: T.primary,
                            color: "#fff",
                            font: "700 12px Alexandria",
                          }}
                        >
                          {rtl
                            ? "عرض الباقة والبرنامج"
                            : "View package & itinerary"}
                        </button>
                      </div>
                    </article>
                  ))
                ) : (
                  <p style={{ color: T.textMuted }}>
                    {rtl
                      ? "لا توجد باقات تستوعب العدد المحدد في هذا الموعد."
                      : "No packages fit this party size."}
                  </p>
                )}
              </div>
            )}
          </>
        )}
        {step < 4 && (
          <button
            disabled={
              (step === 0 && !mode) ||
              (step === 1 && (!origin || !destination)) ||
              (step === 2 && !departure)
            }
            onClick={next}
            style={{
              width: "100%",
              minHeight: 54,
              marginTop: 24,
              border: 0,
              borderRadius: 13,
              background: T.primary,
              color: "#fff",
              font: "700 15px Alexandria",
              opacity:
                (step === 0 && !mode) ||
                (step === 1 && (!origin || !destination)) ||
                (step === 2 && !departure)
                  ? 0.45
                  : 1,
            }}
          >
            {rtl ? "متابعة" : "Continue"}
          </button>
        )}
      </main>
    </div>
  );
}

function WebItineraryTimeline({ theme, lang, pkg }) {
  if (!pkg?.isDynamic) return null;
  const T = theme,
    rtl = isRTL(lang),
    bus = pkg.travelMode === "bus";
  const busMilestones = [
      {
        t: rtl ? "التجمع" : "Meeting",
        d: [
          pkg.meetingAt || pkg.departureAt,
          pkg.meetingPoint || pkg.originCity,
        ]
          .filter(Boolean)
          .join(" · "),
      },
      {
        t: rtl
          ? bus
            ? "ركوب الحافلة والانطلاق"
            : "التوجه للمطار والانطلاق"
          : bus
            ? "Board bus & depart"
            : "Airport & departure",
        d:
          [
            pkg.boardingAt,
            bus
              ? pkg.busType
              : [pkg.airline, pkg.flightNumber].filter(Boolean).join(" · "),
          ]
            .filter(Boolean)
            .join(" · ") || "—",
      },
      {
        t: rtl ? "الوصول إلى مكة" : "Arrive in Makkah",
        d: [pkg.arrivalAt, pkg.destinationCity].filter(Boolean).join(" · "),
      },
      {
        t: rtl ? "الإقامة وأداء العمرة" : "Stay & perform Umrah",
        d: `${pkg.hotel} · ${pkg.nights} ${rtl ? "ليالٍ" : "nights"}`,
      },
      {
        t: rtl ? "المغادرة من الفندق" : "Hotel departure",
        d: pkg.hotelDepartureAt || pkg.returnAt || "—",
      },
      {
        t: rtl ? "الوصول إلى نقطة التجمع" : "Return to meeting point",
        d: [pkg.returnArrivalAt, pkg.meetingPoint || pkg.originCity]
          .filter(Boolean)
          .join(" · "),
      },
    ];
  const flightMilestones = [
    {
      t: rtl ? "رحلة الذهاب" : "Outbound flight",
      d: [
        rtl ? `من ${pkg.originCity || "—"} إلى ${pkg.flightArrivalCity || "—"}` : `From ${pkg.originCity || "—"} to ${pkg.flightArrivalCity || "—"}`,
        pkg.departureAt,
        [pkg.airline, pkg.flightNumber].filter(Boolean).join(" · "),
      ]
        .filter(Boolean)
        .join(" · "),
    },
    {
      t: rtl
        ? `الوصول إلى ${pkg.flightArrivalCity || "مدينة الوصول"}`
        : `Arrive in ${pkg.flightArrivalCity || "destination"}`,
      d: pkg.arrivalAt || "—",
    },
    {
      t: rtl ? "الانتقال من المطار إلى الفندق" : "Airport to hotel transfer",
      d:
        [pkg.airportTransferAt, pkg.airportTransferType]
          .filter(Boolean)
          .join(" · ") || "—",
    },
    {
      t: rtl ? "الإقامة وأداء العمرة" : "Stay & perform Umrah",
      d: `${pkg.hotel} · ${pkg.nights} ${rtl ? "ليالٍ" : "nights"}`,
    },
    {
      t: rtl ? "المغادرة من الفندق" : "Hotel departure",
      d: pkg.hotelDepartureAt || pkg.returnDepartureAt || "—",
    },
    {
      t: rtl ? "رحلة العودة" : "Return flight",
      d: [
        rtl ? `من ${pkg.returnOriginCity || pkg.flightArrivalCity || "—"} إلى ${pkg.returnDestinationCity || pkg.originCity || "—"}` : `From ${pkg.returnOriginCity || pkg.flightArrivalCity || "—"} to ${pkg.returnDestinationCity || pkg.originCity || "—"}`,
        pkg.returnDepartureAt || pkg.returnAt,
        [pkg.returnAirline, pkg.returnFlightNumber]
          .filter(Boolean)
          .join(" · "),
      ]
        .filter(Boolean)
        .join(" · "),
    },
    {
      t: rtl
        ? `الوصول إلى ${pkg.returnDestinationCity || pkg.originCity || "مدينة الوصول"}`
        : `Arrive in ${pkg.returnDestinationCity || pkg.originCity || "destination"}`,
      d: pkg.returnArrivalAt || "—",
    },
  ];
  const milestones = bus ? busMilestones : flightMilestones;
  return (
    <section style={{ marginTop: 32 }}>
      <h2 style={{ color: T.text, font: "700 20px Alexandria" }}>
        {rtl ? "برنامج الرحلة" : "Trip itinerary"}
      </h2>
      <div style={{ position: "relative", paddingInlineStart: 28 }}>
        <div
          style={{
            position: "absolute",
            insetInlineStart: 8,
            top: 10,
            bottom: 10,
            width: 2,
            background: T.hairlineStrong,
          }}
        />
        {milestones.map((m, i) => (
          <div
            key={i}
            style={{ position: "relative", padding: "0 0 20px 8px" }}
          >
            <span
              style={{
                position: "absolute",
                insetInlineStart: -25,
                top: 4,
                width: 16,
                height: 16,
                borderRadius: 99,
                background: i === 0 ? T.primary : T.surface,
                border: `3px solid ${T.primary}`,
              }}
            />
            <strong
              style={{
                display: "block",
                color: T.text,
                font: "700 13px Alexandria",
              }}
            >
              {m.t}
            </strong>
            <span
              style={{ color: T.textMuted, font: "500 12px/1.7 Alexandria" }}
            >
              {m.d}
            </span>
          </div>
        ))}
      </div>
    </section>
  );
}

function AdminItineraryEditor({ theme, lang, data, onChange, token }) {
  const T = theme,
    rtl = isRTL(lang),
    p = data.package;
  const keys = [
    [
      "boarding_at",
      rtl ? "وقت الركوب والانطلاق" : "Boarding time",
      "datetime-local",
    ],
    [
      "arrival_at",
      rtl ? "وقت الوصول المتوقع" : "Expected arrival",
      "datetime-local",
    ],
    [
      "hotel_departure_at",
      rtl ? "وقت المغادرة من الفندق" : "Hotel departure",
      "datetime-local",
    ],
    [
      "return_arrival_at",
      rtl ? "وقت العودة لنقطة التجمع" : "Return arrival",
      "datetime-local",
    ],
  ];
  const [busy, setBusy] = React.useState(false),
    [saved, setSaved] = React.useState(false);
  const set = (key, value) =>
    onChange({ ...data, package: { ...p, [key]: value } });
  const save = async () => {
    setBusy(true);
    setSaved(false);
    const body = {
      meetingPoint: p.meeting_point,
      meetingAt: p.meeting_at,
      boardingAt: p.boarding_at,
      arrivalAt: p.provider_arrival_time || p.arrival_at,
      hotelDepartureAt: p.provider_hotel_departure_time || p.hotel_departure_at,
      returnArrivalAt: p.provider_return_arrival_time || p.return_arrival_at,
      itineraryNotes: p.itinerary_notes,
    };
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(p.id)}/itinerary`,
      {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(body),
      },
    );
    setBusy(false);
    setSaved(r.ok);
  };
  return (
    <section
      style={{
        marginTop: 20,
        padding: 16,
        borderRadius: 15,
        background: T.camelMist,
      }}
    >
      <h3 style={{ marginTop: 0, color: T.text, font: "700 16px Alexandria" }}>
        {rtl ? "برنامج الرحلة ونقاط التجمع" : "Itinerary & meeting points"}
      </h3>
      <p style={{ color: T.textMuted, font: "500 11px/1.7 Alexandria" }}>
        {rtl
          ? "أدخل هذه البيانات قبل الاعتماد؛ ستظهر للعميل كخط زمني داخل تفاصيل الباقة."
          : "Set these before approval; customers will see them as a timeline."}
      </p>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,220px),1fr))",
          gap: 10,
        }}
      >
        {keys.map(([key, label, type]) => (
          <label
            key={key}
            style={{
              display: "grid",
              gap: 6,
              color: T.textMuted,
              font: "600 11px Alexandria",
            }}
          >
            {label}
            <input
              type={type}
              value={p[key] || ""}
              onChange={(e) => set(key, e.target.value)}
              style={{
                width: "100%",
                height: 46,
                border: `1px solid ${T.hairlineStrong}`,
                borderRadius: 10,
                padding: "0 11px",
                background: T.surface,
                color: T.text,
                font: "500 16px Alexandria",
              }}
            />
          </label>
        ))}
      </div>
      <label
        style={{
          display: "grid",
          gap: 6,
          marginTop: 10,
          color: T.textMuted,
          font: "600 11px Alexandria",
        }}
      >
        {rtl ? "ملاحظات برنامج الرحلة" : "Itinerary notes"}
        <textarea
          value={p.itinerary_notes || ""}
          onChange={(e) => set("itinerary_notes", e.target.value)}
          rows="3"
          style={{
            border: `1px solid ${T.hairlineStrong}`,
            borderRadius: 10,
            padding: 11,
            background: T.surface,
            color: T.text,
            font: "500 16px Alexandria",
          }}
        />
      </label>
      <button
        disabled={busy}
        onClick={save}
        style={{
          marginTop: 12,
          padding: "10px 16px",
          border: 0,
          borderRadius: 10,
          background: T.primary,
          color: "#fff",
          font: "700 12px Alexandria",
        }}
      >
        {busy
          ? rtl
            ? "جارٍ الحفظ…"
            : "Saving…"
          : saved
            ? rtl
              ? "تم حفظ البرنامج ✓"
              : "Saved ✓"
            : rtl
              ? "حفظ برنامج الرحلة"
              : "Save itinerary"}
      </button>
    </section>
  );
}

function WebAdminDashboardPageV2({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    { setPage } = useWeb(),
    token = localStorage.getItem("duyuf_admin_session");
  const [items, setItems] = React.useState([]),
    [selected, setSelected] = React.useState(null),
    [busy, setBusy] = React.useState(true),
    [message, setMessage] = React.useState("");
  const parse = (v) => {
    try {
      return JSON.parse(v || "[]");
    } catch (_) {
      return [];
    }
  };
  const load = () => {
    if (!token) return setPage("admin-login");
    setBusy(true);
    fetch(`${window.DUYUF_API_URL}/v1/admin/packages?status=pending`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json().then((body) => ({ ok: r.ok, body })))
      .then(({ ok, body }) => {
        if (!ok) throw new Error();
        setItems(body.packages || []);
      })
      .catch(() => {
        localStorage.removeItem("duyuf_admin_session");
        setPage(
          localStorage.getItem("duyuf_provider_session")
            ? "provider-dashboard"
            : "admin-login",
        );
      })
      .finally(() => setBusy(false));
  };
  React.useEffect(load, []);
  const view = async (id) => {
    setBusy(true);
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(id)}`,
      { headers: { authorization: `Bearer ${token}` } },
    );
    const b = await r.json();
    setBusy(false);
    if (r.ok) setSelected(b);
    else setMessage(rtl ? "تعذر تحميل التفاصيل." : "Could not load details.");
  };
  const review = async (decision) => {
    const id = selected?.package?.id;
    if (!id) return;
    setBusy(true);
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(id)}/review`,
      {
        method: "POST",
        headers: {
          "content-type": "application/json",
          authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ decision }),
      },
    );
    setBusy(false);
    if (r.ok) {
      setItems((v) => v.filter((x) => x.id !== id));
      setSelected(null);
      setMessage(
        decision === "approve"
          ? rtl
            ? "تم اعتماد الباقة ونشرها."
            : "Package approved and published."
          : rtl
            ? "تم رفض الباقة."
            : "Package rejected.",
      );
    } else
      setMessage(rtl ? "تعذر تنفيذ القرار." : "Could not complete the action.");
  };
  const signOut = () => {
    localStorage.removeItem("duyuf_admin_session");
    localStorage.removeItem("duyuf_admin");
    setPage(
      localStorage.getItem("duyuf_provider_session")
        ? "provider-dashboard"
        : "admin-login",
    );
  };
  const p = selected?.package,
    inc = p ? parse(p.inclusions) : [],
    exc = p ? parse(p.exclusions) : [];
  const facts = p
    ? [
        [rtl ? "المزود" : "Provider", `${p.business_name} · ${p.phone}`],
        [
          rtl ? "نوع العمرة" : "Umrah type",
          p.travel_mode === "bus"
            ? rtl
              ? "بالحافلة"
              : "Bus"
            : rtl
              ? "بالطائرة"
              : "Flight",
        ],
        [
          rtl ? "المسار" : "Route",
          `${p.origin_city || "—"} ← ${p.destination_city || "—"}`,
        ],
        [
          rtl ? "موعد الرحلة" : "Schedule",
          `${p.departure_at || "—"} — ${p.return_at || "—"}`,
        ],
        [
          rtl ? "وسيلة النقل" : "Transport",
          p.travel_mode === "bus"
            ? p.bus_type || "—"
            : [p.airline, p.flight_number].filter(Boolean).join(" · ") || "—",
        ],
        [
          rtl ? "الفندق" : "Hotel",
          `${p.hotel_name} · ${p.room_type || "—"} · ${p.meal_plan || "—"}`,
        ],
        [
          rtl ? "المدة والسعة" : "Duration & capacity",
          `${p.duration_days} ${rtl ? "أيام" : "days"} · ${p.seats} ${rtl ? "شخص" : "people"}`,
        ],
        [
          rtl ? "الأسعار" : "Prices",
          `${rtl ? "بالغ" : "Adult"} ${Number(p.adult_price || p.price_per_person).toLocaleString()} · ${rtl ? "طفل" : "Child"} ${Number(p.child_price || 0).toLocaleString()} · ${rtl ? "رضيع" : "Infant"} ${Number(p.infant_price || 0).toLocaleString()} ${rtl ? "ر.س" : "SAR"}`,
        ],
        [
          rtl ? "فترة الحجز" : "Booking window",
          `${p.available_from} — ${p.available_to}`,
        ],
        [
          rtl ? "إغلاق الحجز" : "Booking closes",
          `${p.booking_closes_hours || 72} ${rtl ? "ساعة قبل المغادرة" : "hours before departure"}`,
        ],
      ]
    : [];
  return (
    <div
      style={{ minHeight: 650, padding: "28px 14px 70px", background: T.bg }}
    >
      <main style={{ maxWidth: 1050, margin: "0 auto" }}>
        <header
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            gap: 12,
            flexWrap: "wrap",
          }}
        >
          <div>
            <span style={{ color: T.primary, font: "600 12px Alexandria" }}>
              {rtl ? "إدارة ضيوف" : "Duyuf administration"}
            </span>
            <h1
              style={{
                color: T.text,
                font: "700 clamp(23px,6vw,31px) Alexandria",
                margin: "5px 0",
              }}
            >
              {rtl ? "طلبات اعتماد الباقات" : "Package approvals"}
            </h1>
          </div>
          <button
            onClick={signOut}
            style={{
              padding: "10px 14px",
              border: `1px solid ${T.hairlineStrong}`,
              borderRadius: 11,
              background: T.surface,
              color: T.text,
              font: "600 12px Alexandria",
            }}
          >
            {rtl ? "الخروج من وضع الأدمن" : "Exit admin mode"}
          </button>
        </header>
        {message && (
          <p
            style={{
              padding: 12,
              borderRadius: 10,
              background: T.surfaceAlt,
              color: T.text,
              font: "600 12px Alexandria",
            }}
          >
            {message}
          </p>
        )}
        {p && (
          <section
            style={{
              marginTop: 20,
              padding: "clamp(16px,4vw,26px)",
              background: T.surface,
              border: `2px solid ${T.primary}`,
              borderRadius: 20,
            }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                gap: 10,
              }}
            >
              <div>
                <small
                  style={{ color: T.primary, font: "600 11px Alexandria" }}
                >
                  {rtl
                    ? "التفاصيل الكاملة قبل الاعتماد"
                    : "Full details before approval"}
                </small>
                <h2
                  style={{
                    color: T.text,
                    font: "700 22px Alexandria",
                    margin: "5px 0",
                  }}
                >
                  {p.title}
                </h2>
              </div>
              <button
                onClick={() => setSelected(null)}
                style={{
                  width: 40,
                  height: 40,
                  border: 0,
                  borderRadius: 99,
                  background: T.bg,
                  color: T.text,
                  fontSize: 24,
                }}
              >
                ×
              </button>
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns:
                  "repeat(auto-fit,minmax(min(100%,230px),1fr))",
                gap: 9,
                marginTop: 16,
              }}
            >
              {facts.map(([k, v]) => (
                <div
                  key={k}
                  style={{ padding: 12, borderRadius: 11, background: T.bg }}
                >
                  <small
                    style={{
                      display: "block",
                      color: T.textMuted,
                      font: "500 10px Alexandria",
                      marginBottom: 5,
                    }}
                  >
                    {k}
                  </small>
                  <strong
                    style={{ color: T.text, font: "600 12px/1.7 Alexandria" }}
                  >
                    {v}
                  </strong>
                </div>
              ))}
            </div>
            <p
              style={{
                padding: 12,
                borderRadius: 10,
                background: T.camelMist,
                color: T.textMuted,
                font: "600 12px/1.8 Alexandria",
              }}
            >
              {rtl
                ? "أوقات البرنامج ونقطة التجمع يحددها المزود من إعدادات كل مدينة؛ الأدمن يراجعها فقط."
                : "The provider sets itinerary times and meeting point per city; admin review is read-only."}
            </p>
            <h3 style={{ color: T.text, font: "700 15px Alexandria" }}>
              {rtl ? "الصور المرفقة" : "Attached images"}
            </h3>
            <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
              {selected.images?.length ? (
                selected.images.map((img) => (
                  <img
                    key={img.id}
                    src={`${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(img.storage_key)}`}
                    alt=""
                    style={{
                      width: 150,
                      height: 105,
                      objectFit: "cover",
                      borderRadius: 11,
                    }}
                  />
                ))
              ) : (
                <span
                  style={{ color: T.textMuted, font: "500 12px Alexandria" }}
                >
                  {rtl ? "لا توجد صور مرفقة." : "No images attached."}
                </span>
              )}
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fit,minmax(210px,1fr))",
                gap: 12,
                marginTop: 16,
              }}
            >
              <div>
                <h3 style={{ color: "#238753", font: "700 14px Alexandria" }}>
                  {rtl ? "تشمل الباقة" : "Included"}
                </h3>
                <ul style={{ color: T.text, font: "500 12px/1.9 Alexandria" }}>
                  {inc.length ? (
                    inc.map((x) => <li key={x}>{x}</li>)
                  ) : (
                    <li>{rtl ? "غير محدد" : "Not specified"}</li>
                  )}
                </ul>
              </div>
              <div>
                <h3 style={{ color: "#b42318", font: "700 14px Alexandria" }}>
                  {rtl ? "لا تشمل الباقة" : "Excluded"}
                </h3>
                <ul style={{ color: T.text, font: "500 12px/1.9 Alexandria" }}>
                  {exc.length ? (
                    exc.map((x) => <li key={x}>{x}</li>)
                  ) : (
                    <li>{rtl ? "غير محدد" : "Not specified"}</li>
                  )}
                </ul>
              </div>
            </div>
            {p.notes && (
              <p
                style={{
                  padding: 12,
                  borderRadius: 10,
                  background: T.bg,
                  color: T.text,
                  font: "500 12px/1.8 Alexandria",
                }}
              >
                {p.notes}
              </p>
            )}
            <div
              style={{
                display: "flex",
                gap: 9,
                flexWrap: "wrap",
                marginTop: 16,
              }}
            >
              <button
                disabled={busy}
                onClick={() => review("approve")}
                style={{
                  padding: "12px 22px",
                  border: 0,
                  borderRadius: 11,
                  background: "#238753",
                  color: "#fff",
                  font: "700 13px Alexandria",
                }}
              >
                {rtl ? "اعتماد ونشر" : "Approve & publish"}
              </button>
              <button
                disabled={busy}
                onClick={() => review("reject")}
                style={{
                  padding: "12px 22px",
                  border: "1px solid #b42318",
                  borderRadius: 11,
                  background: "transparent",
                  color: "#b42318",
                  font: "700 13px Alexandria",
                }}
              >
                {rtl ? "رفض" : "Reject"}
              </button>
            </div>
          </section>
        )}
        {busy && !p ? (
          <p style={{ color: T.textMuted }}>
            {rtl ? "جارٍ التحميل…" : "Loading…"}
          </p>
        ) : !p && items.length === 0 ? (
          <div
            style={{
              marginTop: 22,
              padding: 45,
              textAlign: "center",
              background: T.surface,
              border: `1px dashed ${T.hairlineStrong}`,
              borderRadius: 18,
              color: T.textMuted,
              font: "500 13px Alexandria",
            }}
          >
            {rtl
              ? "لا توجد باقات بانتظار الاعتماد."
              : "No packages await approval."}
          </div>
        ) : (
          !p && (
            <div style={{ display: "grid", gap: 12, marginTop: 22 }}>
              {items.map((item) => (
                <article
                  key={item.id}
                  style={{
                    padding: 18,
                    background: T.surface,
                    border: `1px solid ${T.hairline}`,
                    borderRadius: 16,
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                    gap: 14,
                    flexWrap: "wrap",
                  }}
                >
                  <div>
                    <small
                      style={{ color: T.primary, font: "600 11px Alexandria" }}
                    >
                      {item.business_name} · {item.phone}
                    </small>
                    <h2
                      style={{
                        color: T.text,
                        font: "700 18px Alexandria",
                        margin: "7px 0",
                      }}
                    >
                      {item.title}
                    </h2>
                    <span
                      style={{
                        color: T.textMuted,
                        font: "500 12px Alexandria",
                      }}
                    >
                      {item.hotel_name} · {item.duration_days}{" "}
                      {rtl ? "أيام" : "days"} ·{" "}
                      {Number(item.price_per_person).toLocaleString()}{" "}
                      {rtl ? "ر.س" : "SAR"}
                    </span>
                  </div>
                  <button
                    disabled={busy}
                    onClick={() => view(item.id)}
                    style={{
                      padding: "11px 17px",
                      border: 0,
                      borderRadius: 11,
                      background: T.primary,
                      color: "#fff",
                      font: "700 12px Alexandria",
                    }}
                  >
                    {rtl ? "استعراض التفاصيل" : "View details"}
                  </button>
                </article>
              ))}
            </div>
          )
        )}
      </main>
    </div>
  );
}

WebBrowsePage = WebUmrahJourneyPage;
function WebAdminProvidersPanel({ theme, lang, providers, onRefresh }) {
  const T = theme,
    rtl = isRTL(lang),
    token = localStorage.getItem("duyuf_admin_session"),
    [selected, setSelected] = React.useState(null),
    [editing, setEditing] = React.useState(false),
    [editName, setEditName] = React.useState(""),
    [editPhone, setEditPhone] = React.useState(""),
    [busy, setBusy] = React.useState(false),
    [message, setMessage] = React.useState("");
  const view = async (id) => {
    setBusy(true);
    setMessage("");
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/admin/providers/${encodeURIComponent(id)}`,
        { headers: { authorization: `Bearer ${token}` } },
      );
      const b = await r.json();
      if (!r.ok) throw new Error();
      setSelected(b);
      setEditName(b.provider.business_name || "");
      setEditPhone(b.provider.phone || "");
      setEditing(false);
    } catch (_) {
      setMessage(
        rtl ? "تعذر فتح ملف المزود." : "Could not open provider profile.",
      );
    } finally {
      setBusy(false);
    }
  };
  const saveProvider = async () => {
    if (!selected) return;
    setBusy(true); setMessage("");
    try {
      const r = await fetch(`${window.DUYUF_API_URL}/v1/admin/providers/${encodeURIComponent(selected.provider.id)}`, {
        method: "PATCH",
        headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
        body: JSON.stringify({ businessName: editName, phone: editPhone }),
      });
      const b = await r.json();
      if (!r.ok) throw new Error(b.error || "update_failed");
      setSelected((current) => ({ ...current, provider: { ...current.provider, ...b.provider } }));
      setEditing(false);
      setMessage(rtl ? "تم تحديث اسم المزود ورقم الجوال." : "Provider name and phone updated.");
      onRefresh?.();
    } catch (error) {
      setMessage(error.message === "phone_already_used" ? (rtl ? "رقم الجوال مستخدم لمزود آخر." : "Phone is already used by another provider.") : (rtl ? "تحقق من الاسم ورقم سعودي صحيح يبدأ بـ 05 أو +9665." : "Check the name and Saudi phone number."));
    } finally { setBusy(false); }
  };
  const review = async (decision) => {
    if (!selected) return;
    setBusy(true);
    try {
      const r = await fetch(
        `${window.DUYUF_API_URL}/v1/admin/providers/${encodeURIComponent(selected.provider.id)}/review`,
        {
          method: "POST",
          headers: {
            "content-type": "application/json",
            authorization: `Bearer ${token}`,
          },
          body: JSON.stringify({ decision }),
        },
      );
      if (!r.ok) throw new Error();
      setMessage(
        decision === "approve"
          ? rtl
            ? "تم اعتماد المزود وبلغ اكتمال ملفه 100%."
            : "Provider approved; profile is now 100% complete."
          : rtl
            ? "تم رفض الملف لإعادة استكماله."
            : "Profile rejected for resubmission.",
      );
      setSelected(null);
      onRefresh?.();
    } catch (_) {
      setMessage(rtl ? "تعذر تنفيذ القرار." : "Could not complete the review.");
    } finally {
      setBusy(false);
    }
  };
  const status = (p) =>
    p.profile_status === "approved"
      ? rtl
        ? "معتمد"
        : "Approved"
      : p.profile_status === "pending"
        ? rtl
          ? "بانتظار الاعتماد"
          : "Awaiting approval"
        : p.profile_status === "rejected"
          ? rtl
            ? "مرفوض"
            : "Rejected"
          : rtl
            ? "غير مكتمل"
            : "Incomplete";
  if (selected) {
    const p = selected.provider;
    return (
      <section
        style={{
          padding: "clamp(16px,4vw,25px)",
          borderRadius: 18,
          background: T.surface,
          border: `2px solid ${T.primary}`,
        }}
      >
        <div
          style={{ display: "flex", justifyContent: "space-between", gap: 10 }}
        >
          <div>
            <small style={{ color: T.primary, font: "600 11px Alexandria" }}>
              {rtl ? "تفاصيل المزود" : "Provider details"}
            </small>
            <h2
              style={{
                color: T.text,
                font: "700 22px Alexandria",
                margin: "5px 0",
              }}
            >
              {p.business_name}
            </h2>
            {!editing && <button onClick={() => setEditing(true)} style={{ marginTop: 8, padding: "8px 12px", border: `1px solid ${T.primary}`, borderRadius: 9, background: "transparent", color: T.primary, font: "700 11px Alexandria" }}>{rtl ? "تعديل بيانات المزود" : "Edit provider"}</button>}
          </div>
          <button
            onClick={() => setSelected(null)}
            style={{
              width: 40,
              height: 40,
              border: 0,
              borderRadius: 99,
              background: T.bg,
              fontSize: 23,
            }}
          >
            ×
          </button>
        </div>
        {editing && <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))", gap: 10, marginTop: 15, padding: 15, borderRadius: 14, background: T.bg }}>
          <label style={{ display: "grid", gap: 6, color: T.textMuted, font: "600 11px Alexandria" }}>{rtl ? "اسم المزود" : "Provider name"}<input value={editName} onChange={(e) => setEditName(e.target.value)} style={{ padding: 11, borderRadius: 9, border: `1px solid ${T.hairlineStrong}`, background: T.surface, color: T.text, font: "600 12px Alexandria" }} /></label>
          <label style={{ display: "grid", gap: 6, color: T.textMuted, font: "600 11px Alexandria" }}>{rtl ? "رقم الجوال" : "Phone"}<input dir="ltr" value={editPhone} onChange={(e) => setEditPhone(e.target.value)} placeholder="+9665XXXXXXXX" style={{ padding: 11, borderRadius: 9, border: `1px solid ${T.hairlineStrong}`, background: T.surface, color: T.text, font: "600 12px Alexandria" }} /></label>
          <div style={{ display: "flex", gap: 8, alignItems: "end" }}><button disabled={busy} onClick={saveProvider} style={{ padding: "11px 16px", border: 0, borderRadius: 9, background: T.primary, color: "#fff", font: "700 11px Alexandria" }}>{rtl ? "حفظ التعديلات" : "Save changes"}</button><button onClick={() => setEditing(false)} style={{ padding: "11px 16px", border: `1px solid ${T.hairlineStrong}`, borderRadius: 9, background: T.surface, color: T.text, font: "700 11px Alexandria" }}>{rtl ? "إلغاء" : "Cancel"}</button></div>
        </div>}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit,minmax(min(100%,210px),1fr))",
            gap: 9,
            marginTop: 15,
          }}
        >
          {[
            [rtl ? "الجوال" : "Phone", p.phone],
            [rtl ? "البريد" : "Email", p.email || "—"],
            [
              rtl ? "السجل التجاري" : "Commercial registration",
              p.commercial_registration || "—",
            ],
            [
              rtl ? "ترخيص النشاط" : "Tourism license",
              p.tourism_license || "—",
            ],
            [rtl ? "الحالة" : "Status", status(p)],
          ].map(([k, v]) => (
            <div
              key={k}
              style={{ padding: 12, borderRadius: 11, background: T.bg }}
            >
              <small style={{ display: "block", color: T.textMuted }}>
                {k}
              </small>
              <strong style={{ color: T.text }}>{v}</strong>
            </div>
          ))}
        </div>
        <h3 style={{ color: T.text, font: "700 16px Alexandria" }}>
          {rtl ? "الوثائق المرفقة" : "Attached documents"}
        </h3>
        <div style={{ display: "grid", gap: 9 }}>
          {selected.documents.length ? (
            selected.documents.map((d) => (
              <a
                key={d.id}
                target="_blank"
                rel="noreferrer"
                href={`${window.DUYUF_API_URL}/v1/provider/documents/${encodeURIComponent(d.storage_key)}?admin=1`}
                onClick={(e) => {
                  e.preventDefault();
                  fetch(e.currentTarget.href, {
                    headers: { authorization: `Bearer ${token}` },
                  })
                    .then((r) => r.blob())
                    .then((b) => window.open(URL.createObjectURL(b), "_blank"));
                }}
                style={{
                  padding: 12,
                  border: `1px solid ${T.hairlineStrong}`,
                  borderRadius: 10,
                  color: T.primary,
                  font: "700 12px Alexandria",
                  textDecoration: "none",
                }}
              >
                {d.document_type === "commercial_registration"
                  ? rtl
                    ? "السجل التجاري"
                    : "Commercial registration"
                  : rtl
                    ? "ترخيص النشاط"
                    : "Tourism license"}{" "}
                — {d.file_name}
              </a>
            ))
          ) : (
            <p style={{ color: T.textMuted }}>
              {rtl ? "لا توجد وثائق." : "No documents."}
            </p>
          )}
        </div>
        <div style={{ display: "flex", gap: 9, marginTop: 18 }}>
          <button
            disabled={busy}
            onClick={() => review("approve")}
            style={{
              padding: "11px 18px",
              border: 0,
              borderRadius: 10,
              background: "#238753",
              color: "#fff",
              font: "700 12px Alexandria",
            }}
          >
            {rtl ? "اعتماد المزود" : "Approve provider"}
          </button>
          <button
            disabled={busy}
            onClick={() => review("reject")}
            style={{
              padding: "11px 18px",
              border: "1px solid #b42318",
              borderRadius: 10,
              background: "transparent",
              color: "#b42318",
              font: "700 12px Alexandria",
            }}
          >
            {rtl ? "رفض" : "Reject"}
          </button>
        </div>
      </section>
    );
  }
  return (
    <>
      {message && (
        <p
          style={{
            padding: 12,
            borderRadius: 10,
            background: T.surface,
            color: T.text,
          }}
        >
          {message}
        </p>
      )}
      <div style={{ display: "grid", gap: 10 }}>
        {providers.map((p) => (
          <article
            key={p.id}
            style={{
              padding: 16,
              borderRadius: 14,
              background: T.surface,
              border: `1px solid ${T.hairline}`,
              display: "grid",
              gridTemplateColumns: "minmax(0,1fr) auto",
              gap: 12,
            }}
          >
            <div>
              <strong style={{ color: T.text, font: "700 14px Alexandria" }}>
                {p.business_name}
              </strong>
              <div
                style={{ color: T.textMuted, font: "500 11px/1.8 Alexandria" }}
              >
                {p.phone}
                <br />
                {rtl ? "الباقات" : "Packages"}: {p.package_count || 0} ·{" "}
                {rtl ? "الحجوزات" : "Bookings"}: {p.booking_count || 0}
                <br />
                {status(p)}
              </div>
            </div>
            <button
              disabled={busy}
              onClick={() => view(p.id)}
              style={{
                alignSelf: "center",
                padding: "9px 12px",
                border: 0,
                borderRadius: 9,
                background: T.primary,
                color: "#fff",
                font: "700 10px Alexandria",
              }}
            >
              {rtl ? "استعراض الملف" : "View profile"}
            </button>
          </article>
        ))}
      </div>
    </>
  );
}

function WebAdminDashboardPageV3({ theme, lang }) {
  const T = theme,
    rtl = isRTL(lang),
    token = localStorage.getItem("duyuf_admin_session");
  const [data, setData] = React.useState(null),
    [tab, setTab] = React.useState("overview"),
    [selected, setSelected] = React.useState(null),
    [detailBusy, setDetailBusy] = React.useState(false),
    [providerFilter, setProviderFilter] = React.useState("all"),
    [travelFilter, setTravelFilter] = React.useState("all"),
    [statusBusy, setStatusBusy] = React.useState(""),
    [statusMessage, setStatusMessage] = React.useState(""),
    [pushData, setPushData] = React.useState(null),
    [pushBusy, setPushBusy] = React.useState(false),
    [pushError, setPushError] = React.useState("");
  const load = () =>
    fetch(`${window.DUYUF_API_URL}/v1/admin/overview`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((b) => {
        if (b.ok) setData(b);
      })
      .catch(() => {});
  React.useEffect(load, []);
  const loadPushAnalytics = () => {
    setPushBusy(true);
    setPushError("");
    fetch(`${window.DUYUF_API_URL}/v1/admin/pushwoosh-analytics`, {
      headers: { authorization: `Bearer ${token}` },
    })
      .then(async (response) => {
        const body = await response.json();
        if (!response.ok || !body.ok) throw new Error(body.error || "request_failed");
        setPushData(body);
      })
      .catch(() => setPushError(rtl ? "تعذر تحميل بيانات Pushwoosh." : "Could not load Pushwoosh analytics."))
      .finally(() => setPushBusy(false));
  };
  React.useEffect(() => {
    if (tab === "notifications" && !pushData && !pushBusy) loadPushAnalytics();
  }, [tab]);
  const m = data?.metrics || {},
    statusLabel = (s) =>
      ({
        active: rtl ? "نشطة" : "Active",
        paused: rtl ? "موقوفة" : "Paused",
        pending: rtl ? "بانتظار الاعتماد" : "Pending",
        rejected: rtl ? "مرفوضة" : "Rejected",
      })[s] || s;
  const filteredPackages = (data?.packages || []).filter(
    (item) =>
      (providerFilter === "all" || item.provider_id === providerFilter) &&
      (travelFilter === "all" || item.travel_mode === travelFilter || (travelFilter === "unspecified" && !item.travel_mode)),
  );
  const changePackageStatus = async (item, action) => {
    setStatusBusy(item.id);
    setStatusMessage("");
    try {
      const response = await fetch(
        `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(item.id)}/status`,
        {
          method: "POST",
          headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
          body: JSON.stringify({ action }),
        },
      );
      const body = await response.json();
      if (!response.ok) throw new Error(body.error || "status_failed");
      setData((current) => ({
        ...current,
        packages: (current?.packages || []).map((pkg) =>
          pkg.id === item.id ? { ...pkg, status: body.status } : pkg,
        ),
        activity: [
          {
            id: `local-${Date.now()}`,
            package_id: item.id,
            title: item.title,
            business_name: item.business_name,
            action,
            new_status: body.status,
            created_at: Date.now(),
          },
          ...(current?.activity || []),
        ],
      }));
      setStatusMessage(action === "pause" ? (rtl ? "تم إيقاف الباقة وتسجيل العملية." : "Package paused and logged.") : (rtl ? "تم تنشيط الباقة وتسجيل العملية." : "Package activated and logged."));
    } catch (_) {
      setStatusMessage(rtl ? "تعذر تغيير حالة الباقة." : "Could not change package status.");
    } finally {
      setStatusBusy("");
    }
  };
  const metric = (label, value) => (
    <div
      style={{
        padding: 16,
        borderRadius: 15,
        background: T.surface,
        border: `1px solid ${T.hairline}`,
      }}
    >
      <strong
        style={{
          display: "block",
          color: T.primary,
          font: "700 26px Alexandria",
        }}
      >
        {Number(value || 0).toLocaleString()}
      </strong>
      <span style={{ color: T.textMuted, font: "600 11px Alexandria" }}>
        {label}
      </span>
    </div>
  );
  const view = async (id) => {
    setDetailBusy(true);
    const r = await fetch(
      `${window.DUYUF_API_URL}/v1/admin/packages/${encodeURIComponent(id)}`,
      { headers: { authorization: `Bearer ${token}` } },
    );
    const b = await r.json();
    setDetailBusy(false);
    if (r.ok) setSelected(b);
  };
  const parse = (v) => {
      try {
        const value = JSON.parse(v || "[]");
        return Array.isArray(value) ? value : [];
      } catch (_) {
        return [];
      }
    },
    p = selected?.package;
  const facts = p
    ? [
        [rtl ? "المزود" : "Provider", `${p.business_name} · ${p.phone}`],
        [rtl ? "الحالة" : "Status", statusLabel(p.status)],
        [
          rtl ? "نوع العمرة" : "Umrah type",
          p.travel_mode === "bus"
            ? rtl
              ? "بالحافلة"
              : "Bus"
            : rtl
              ? "بالطائرة"
              : "Flight",
        ],
        [
          rtl ? "المسار" : "Route",
          `${p.origin_city || "—"} ← ${p.destination_city || "—"}`,
        ],
        [
          rtl ? "موعد الرحلة" : "Schedule",
          `${p.departure_at || "—"} — ${p.return_at || "—"}`,
        ],
        [
          rtl ? "وسيلة النقل" : "Transport",
          p.travel_mode === "bus"
            ? p.bus_type || "—"
            : [p.airline, p.flight_number].filter(Boolean).join(" · ") || "—",
        ],
        [
          rtl ? "الفندق" : "Hotel",
          `${p.hotel_name} · ${p.room_type || "—"} · ${p.meal_plan || "—"}`,
        ],
        [
          rtl ? "المدة والسعة" : "Duration & capacity",
          `${p.duration_days} ${rtl ? "أيام" : "days"} · ${p.seats} ${rtl ? "شخص" : "people"}`,
        ],
        [
          rtl ? "الأسعار" : "Prices",
          `${rtl ? "بالغ" : "Adult"} ${Number(p.adult_price || p.price_per_person).toLocaleString()} · ${rtl ? "طفل" : "Child"} ${Number(p.child_price || 0).toLocaleString()} · ${rtl ? "رضيع" : "Infant"} ${Number(p.infant_price || 0).toLocaleString()} ${rtl ? "ر.س" : "SAR"}`,
        ],
        [
          rtl ? "فترة الحجز" : "Booking window",
          `${p.available_from} — ${p.available_to}`,
        ],
      ]
    : [];
  return (
    <div style={{ background: T.bg, minHeight: "calc(100vh - 180px)" }}>
      <section
        style={{
          maxWidth: 1050,
          margin: "0 auto",
          padding: "28px 14px clamp(72px,10vw,120px)",
        }}
      >
        <h1
          style={{
            color: T.text,
            font: "700 clamp(24px,6vw,33px) Alexandria",
            marginBottom: 8,
          }}
        >
          {rtl ? "نظرة عامة على المنصة" : "Platform overview"}
        </h1>
        <div
          style={{
            display: "flex",
            gap: 7,
            flexWrap: "wrap",
            margin: "14px 0 18px",
          }}
        >
          {[
            ["overview", rtl ? "المؤشرات" : "Overview"],
            ["providers", rtl ? "المزودون" : "Providers"],
            ["packages", rtl ? "جميع الباقات" : "All packages"],
            ["pending", rtl ? "طلبات الاعتماد" : "Approvals"],
            ["activity", rtl ? "سجل العمليات" : "Activity log"],
            ["notifications", rtl ? "تحليلات الإشعارات" : "Push analytics"],
          ].map(([id, label]) => (
            <button
              key={id}
              onClick={() => setTab(id)}
              style={{
                padding: "10px 14px",
                border: `1px solid ${tab === id ? T.primary : T.hairlineStrong}`,
                borderRadius: 10,
                background: tab === id ? T.camelMist : T.surface,
                color: tab === id ? T.primary : T.text,
                font: "700 11px Alexandria",
              }}
            >
              {label}
            </button>
          ))}
        </div>
        {tab === "overview" && (
          <>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fit,minmax(145px,1fr))",
                gap: 10,
              }}
            >
              {metric(rtl ? "المزودون" : "Providers", m.providers)}
              {metric(
                rtl ? "ملفات مكتملة" : "Complete profiles",
                m.complete_profiles,
              )}
              {metric(
                rtl ? "الباقات النشطة" : "Active packages",
                m.active_packages,
              )}
              {metric(rtl ? "بانتظار الاعتماد" : "Pending", m.pending_packages)}
              {metric(rtl ? "الحجوزات" : "Bookings", m.bookings)}
              {metric(rtl ? "إجمالي المسافرين" : "Travelers", m.travelers)}
            </div>
            <div
              style={{
                marginTop: 15,
                padding: 15,
                borderRadius: 14,
                background: T.surface,
                border: `1px solid ${T.hairline}`,
              }}
            >
              <strong style={{ color: T.text, font: "700 13px Alexandria" }}>
                {rtl
                  ? "اكتمال الملفات التجارية"
                  : "Business profile completion"}
              </strong>
              <div
                style={{
                  height: 10,
                  marginTop: 10,
                  borderRadius: 99,
                  overflow: "hidden",
                  background: T.surfaceAlt,
                }}
              >
                <span
                  style={{
                    display: "block",
                    height: "100%",
                    width: `${m.providers ? Math.round((Number(m.complete_profiles || 0) / Number(m.providers)) * 100) : 0}%`,
                    background: "#238753",
                  }}
                />
              </div>
              <small style={{ color: T.textMuted }}>
                {m.providers
                  ? Math.round(
                      (Number(m.complete_profiles || 0) / Number(m.providers)) *
                        100,
                    )
                  : 0}
                %
              </small>
            </div>
          </>
        )}
        {tab === "providers" && (
          <WebAdminProvidersPanel
            theme={T}
            lang={lang}
            providers={data?.providers || []}
            onRefresh={load}
          />
        )}{" "}
        {tab === "notifications" && (
          <section style={{ display: "grid", gap: 14 }}>
            <div style={{ padding: "18px clamp(16px,4vw,24px)", borderRadius: 18, background: T.surface, border: `1px solid ${T.hairline}` }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                <div>
                  <small style={{ color: T.primary, font: "700 10px Alexandria" }}>PUSHWOOSH · WEB PUSH</small>
                  <h2 style={{ margin: "5px 0 0", color: T.text, font: "700 20px Alexandria" }}>{rtl ? "أداء إشعارات ضيوف" : "Duyuf push performance"}</h2>
                  <p style={{ margin: "5px 0 0", color: T.textMuted, font: "500 11px/1.7 Alexandria" }}>{rtl ? "بيانات آخر 30 يومًا، مباشرة من Pushwoosh" : "Last 30 days, directly from Pushwoosh"}</p>
                </div>
                <button onClick={loadPushAnalytics} disabled={pushBusy} style={{ padding: "10px 14px", border: 0, borderRadius: 10, background: T.primary, color: "#fff", font: "700 11px Alexandria" }}>{pushBusy ? (rtl ? "جارٍ التحديث…" : "Refreshing…") : (rtl ? "تحديث البيانات" : "Refresh")}</button>
              </div>
            </div>
            {pushError && <div style={{ padding: 14, borderRadius: 12, background: "rgba(180,81,59,.1)", color: T.danger, font: "600 12px Alexandria" }}>{pushError}</div>}
            {pushBusy && !pushData && <div style={{ padding: 30, textAlign: "center", color: T.textMuted, font: "600 12px Alexandria" }}>{rtl ? "جارٍ جلب التحليلات…" : "Loading analytics…"}</div>}
            {pushData && <>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(145px,1fr))", gap: 10 }}>
                {metric(rtl ? "إجمالي المشتركين" : "Subscribers", pushData.subscribers)}
                {metric(rtl ? "الرسائل خلال 30 يومًا" : "Messages · 30d", pushData.messages?.count)}
                {metric(rtl ? "تم الإرسال" : "Sent", pushData.messages?.sent)}
                {metric(rtl ? "تم التسليم" : "Delivered", pushData.messages?.delivered)}
                {metric(rtl ? "مرات الفتح" : "Opened", pushData.messages?.opened)}
              </div>
              <div style={{ padding: 18, borderRadius: 16, background: T.surface, border: `1px solid ${T.hairline}` }}>
                <h3 style={{ margin: "0 0 13px", color: T.text, font: "700 15px Alexandria" }}>{rtl ? "المشتركون حسب المنصة" : "Subscribers by platform"}</h3>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(130px,1fr))", gap: 9 }}>
                  {Object.entries(pushData.platforms || {}).filter(([, value]) => Number(value) > 0).map(([platform, value]) => (
                    <div key={platform} style={{ padding: 13, borderRadius: 12, background: T.bg }}>
                      <strong style={{ display: "block", color: T.primary, font: "700 20px Alexandria" }}>{Number(value).toLocaleString()}</strong>
                      <span style={{ color: T.textMuted, font: "600 10px Alexandria" }}>{platform}</span>
                    </div>
                  ))}
                  {!Object.values(pushData.platforms || {}).some((value) => Number(value) > 0) && <span style={{ color: T.textMuted, font: "500 12px Alexandria" }}>{rtl ? "لا توجد اشتراكات مسجلة بعد." : "No subscriptions recorded yet."}</span>}
                </div>
              </div>
              <small style={{ color: T.textFaint, font: "500 10px Alexandria" }}>{rtl ? "آخر تحديث" : "Last updated"}: {new Date(pushData.updatedAt).toLocaleString(rtl ? "ar-SA" : "en-US")}</small>
            </>}
          </section>
        )}
        {tab === "packages" && p && (
          <section
            style={{
              marginBottom: 14,
              padding: "clamp(16px,4vw,25px)",
              borderRadius: 18,
              background: T.surface,
              border: `2px solid ${T.primary}`,
            }}
          >
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                gap: 10,
              }}
            >
              <div>
                <small
                  style={{ color: T.primary, font: "600 11px Alexandria" }}
                >
                  {rtl ? "التفاصيل الكاملة للباقة" : "Full package details"}
                </small>
                <h2
                  style={{
                    color: T.text,
                    font: "700 22px Alexandria",
                    margin: "5px 0",
                  }}
                >
                  {p.title}
                </h2>
              </div>
              <button
                onClick={() => setSelected(null)}
                style={{
                  width: 40,
                  height: 40,
                  border: 0,
                  borderRadius: 99,
                  background: T.bg,
                  fontSize: 23,
                }}
              >
                ×
              </button>
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns:
                  "repeat(auto-fit,minmax(min(100%,220px),1fr))",
                gap: 9,
                marginTop: 15,
              }}
            >
              {facts.map(([k, v]) => (
                <div
                  key={k}
                  style={{ padding: 12, borderRadius: 11, background: T.bg }}
                >
                  <small
                    style={{
                      display: "block",
                      color: T.textMuted,
                      font: "500 10px Alexandria",
                    }}
                  >
                    {k}
                  </small>
                  <strong
                    style={{ color: T.text, font: "600 12px/1.7 Alexandria" }}
                  >
                    {v}
                  </strong>
                </div>
              ))}
            </div>
            <h3 style={{ color: T.text, font: "700 15px Alexandria" }}>
              {rtl ? "الصور المرفقة" : "Attached images"}
            </h3>
            <div style={{ display: "flex", gap: 9, flexWrap: "wrap" }}>
              {selected.images?.length ? (
                selected.images.map((img) => (
                  <img
                    key={img.id}
                    src={`${window.DUYUF_API_URL}/v1/public/package-images/${encodeURIComponent(img.storage_key)}`}
                    style={{
                      width: 150,
                      height: 105,
                      objectFit: "cover",
                      borderRadius: 11,
                    }}
                  />
                ))
              ) : (
                <span
                  style={{ color: T.textMuted, font: "500 12px Alexandria" }}
                >
                  {rtl ? "لا توجد صور مرفقة." : "No images attached."}
                </span>
              )}
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "repeat(auto-fit,minmax(220px,1fr))",
                gap: 12,
                marginTop: 14,
              }}
            >
              <div>
                <h3 style={{ color: "#238753", font: "700 14px Alexandria" }}>
                  {rtl ? "تشمل الباقة" : "Included"}
                </h3>
                <ul style={{ color: T.text, font: "500 12px/1.9 Alexandria" }}>
                  {parse(p.inclusions).length ? (
                    parse(p.inclusions).map((x) => <li key={x}>{x}</li>)
                  ) : (
                    <li>{rtl ? "غير محدد" : "Not specified"}</li>
                  )}
                </ul>
              </div>
              <div>
                <h3 style={{ color: "#b42318", font: "700 14px Alexandria" }}>
                  {rtl ? "لا تشمل الباقة" : "Excluded"}
                </h3>
                <ul style={{ color: T.text, font: "500 12px/1.9 Alexandria" }}>
                  {parse(p.exclusions).length ? (
                    parse(p.exclusions).map((x) => <li key={x}>{x}</li>)
                  ) : (
                    <li>{rtl ? "غير محدد" : "Not specified"}</li>
                  )}
                </ul>
              </div>
            </div>
            {p.notes && (
              <p
                style={{
                  padding: 12,
                  borderRadius: 10,
                  background: T.bg,
                  color: T.text,
                  font: "500 12px/1.8 Alexandria",
                }}
              >
                {p.notes}
              </p>
            )}
          </section>
        )}
        {tab === "packages" && (
          <div style={{ display: "grid", gap: 12 }}>
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", padding: 14, borderRadius: 14, background: T.surface, border: `1px solid ${T.hairline}` }}>
              <label style={{ display: "grid", gap: 5, color: T.textMuted, font: "600 10px Alexandria" }}>
                {rtl ? "فلترة حسب المزود" : "Filter by provider"}
                <select value={providerFilter} onChange={(e) => setProviderFilter(e.target.value)} style={{ minWidth: 190, padding: "10px 12px", borderRadius: 10, border: `1px solid ${T.hairlineStrong}`, background: T.bg, color: T.text, font: "600 11px Alexandria" }}>
                  <option value="all">{rtl ? `كل المزودين (${(data?.providers || []).length})` : `All providers (${(data?.providers || []).length})`}</option>
                  {(data?.providers || []).map((provider) => <option key={provider.id} value={provider.id}>{provider.business_name}</option>)}
                </select>
              </label>
              <label style={{ display: "grid", gap: 5, color: T.textMuted, font: "600 10px Alexandria" }}>
                {rtl ? "فلترة حسب وسيلة السفر" : "Filter by travel mode"}
                <select value={travelFilter} onChange={(e) => setTravelFilter(e.target.value)} style={{ minWidth: 190, padding: "10px 12px", borderRadius: 10, border: `1px solid ${T.hairlineStrong}`, background: T.bg, color: T.text, font: "600 11px Alexandria" }}>
                  <option value="all">{rtl ? "كل وسائل السفر" : "All travel modes"}</option>
                  <option value="bus">{rtl ? "بالحافلة / النقل" : "Bus / transport"}</option>
                  <option value="flight">{rtl ? "بالطيران" : "Flight"}</option>
                  <option value="unspecified">{rtl ? "غير محدد" : "Unspecified"}</option>
                </select>
              </label>
              <strong style={{ alignSelf: "end", padding: "10px 12px", color: T.primary, font: "700 11px Alexandria" }}>{rtl ? `${filteredPackages.length} باقة` : `${filteredPackages.length} packages`}</strong>
            </div>
            {statusMessage && <div style={{ padding: 12, borderRadius: 10, background: T.camelMist, color: T.text, font: "600 11px Alexandria" }}>{statusMessage}</div>}
            {filteredPackages.map((p) => (
              <article
                key={p.id}
                onClick={() => view(p.id)}
                role="button"
                tabIndex="0"
                style={{
                  padding: 16,
                  borderRadius: 14,
                  background: T.surface,
                  border: `1px solid ${T.hairline}`,
                  cursor: "pointer",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    gap: 10,
                    flexWrap: "wrap",
                  }}
                >
                  <div>
                    <span style={{ display: "inline-flex", marginBottom: 7, padding: "6px 9px", borderRadius: 99, background: p.travel_mode === "bus" ? "#eef7f1" : p.travel_mode === "flight" ? "#eef4ff" : T.surfaceAlt, color: p.travel_mode === "bus" ? "#237a4b" : p.travel_mode === "flight" ? "#245ea8" : T.textMuted, font: "700 10px Alexandria" }}>
                      {p.travel_mode === "bus" ? (rtl ? "🚌 بالحافلة / نقل" : "🚌 Bus / transport") : p.travel_mode === "flight" ? (rtl ? "✈️ بالطيران" : "✈️ Flight") : (rtl ? "وسيلة السفر غير محددة" : "Travel mode unspecified")}
                    </span>
                    <strong
                      style={{ display: "block", color: T.text, font: "700 14px Alexandria" }}
                    >
                      {p.title}
                    </strong>
                    <div
                      style={{
                        color: T.textMuted,
                        font: "500 11px/1.8 Alexandria",
                      }}
                    >
                      {p.business_name} · {p.hotel_name}
                    </div>
                  </div>
                  <span
                    style={{ padding: "7px 10px", borderRadius: 99, alignSelf: "flex-start", background: p.status === "active" ? "#eaf7ef" : p.status === "paused" ? "#fff2e1" : T.camelMist, color: p.status === "active" ? "#237a4b" : p.status === "paused" ? "#a15c09" : T.primary, font: "700 11px Alexandria" }}
                  >
                    {statusLabel(p.status)}
                  </span>
                </div>
                <div
                  style={{
                    marginTop: 9,
                    color: T.text,
                    font: "600 11px Alexandria",
                  }}
                >
                  {rtl ? "الحجوزات" : "Bookings"}: {p.booking_count || 0} ·{" "}
                  {rtl ? "المحجوز بالأشخاص" : "Booked travelers"}:{" "}
                  {p.booked_travelers || 0}/{p.seats} ·{" "}
                  {rtl ? "تم الدخول" : "Checked in"}:{" "}
                  {p.checked_in_travelers || 0}
                </div>
                <button
                  disabled={detailBusy}
                  onClick={() => view(p.id)}
                  style={{
                    marginTop: 10,
                    padding: "9px 13px",
                    border: 0,
                    borderRadius: 9,
                    background: T.primary,
                    color: "#fff",
                    font: "700 11px Alexandria",
                  }}
                >
                  {detailBusy
                    ? rtl
                      ? "جارٍ التحميل…"
                      : "Loading…"
                    : rtl
                      ? "استعراض التفاصيل"
                      : "View details"}
                </button>
                {(p.status === "active" || p.status === "paused") && (
                  <button
                    disabled={statusBusy === p.id}
                    onClick={(event) => { event.stopPropagation(); changePackageStatus(p, p.status === "active" ? "pause" : "activate"); }}
                    style={{ marginTop: 10, marginInlineStart: 8, padding: "9px 13px", border: `1px solid ${p.status === "active" ? "#a15c09" : "#237a4b"}`, borderRadius: 9, background: "transparent", color: p.status === "active" ? "#a15c09" : "#237a4b", font: "700 11px Alexandria" }}
                  >
                    {statusBusy === p.id ? (rtl ? "جارٍ الحفظ…" : "Saving…") : p.status === "active" ? (rtl ? "إيقاف الباقة" : "Pause package") : (rtl ? "تنشيط الباقة" : "Activate package")}
                  </button>
                )}
              </article>
            ))}
            {!filteredPackages.length && <div style={{ padding: 30, textAlign: "center", color: T.textMuted, font: "600 12px Alexandria" }}>{rtl ? "لا توجد باقات مطابقة للفلاتر." : "No packages match these filters."}</div>}
          </div>
        )}
        {tab === "activity" && (
          <div style={{ display: "grid", gap: 9 }}>
            {(data?.activity || []).map((entry) => (
              <article key={entry.id} style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", padding: 14, borderRadius: 13, background: T.surface, border: `1px solid ${T.hairline}` }}>
                <div><strong style={{ display: "block", color: T.text, font: "700 12px Alexandria" }}>{entry.action === "update_provider" ? (rtl ? "تعديل بيانات مزود" : "Provider details updated") : entry.action === "pause" ? (rtl ? "إيقاف باقة" : "Package paused") : (rtl ? "تنشيط باقة" : "Package activated")}</strong><span style={{ color: T.textMuted, font: "500 11px/1.8 Alexandria" }}>{entry.title ? `${entry.title} · ` : ""}{entry.business_name}</span></div>
                <div style={{ textAlign: rtl ? "left" : "right" }}>{entry.new_status && <span style={{ display: "block", color: entry.new_status === "active" ? "#237a4b" : "#a15c09", font: "700 11px Alexandria" }}>{statusLabel(entry.new_status)}</span>}<small style={{ color: T.textMuted }}>{new Date(Number(entry.created_at)).toLocaleString(rtl ? "ar-SA" : "en-US")}</small>{entry.admin_phone && <small style={{ display: "block", color: T.textFaint }}>{entry.admin_phone}</small>}</div>
              </article>
            ))}
            {!(data?.activity || []).length && <div style={{ padding: 35, textAlign: "center", color: T.textMuted, font: "600 12px Alexandria" }}>{rtl ? "لا توجد عمليات إيقاف أو تنشيط بعد." : "No pause or activation activity yet."}</div>}
          </div>
        )}
      </section>
      {tab === "pending" && <WebAdminDashboardPageV2 theme={T} lang={lang} />}
    </div>
  );
}
WebAdminDashboardPage = WebAdminDashboardPageV3;
Object.assign(window, {
  WebContext,
  useWeb,
  WebPageHeader,
  WebBrowsePage,
  WebDetailPage,
  WebCheckoutPage,
  WebPaymentResultPage,
  WebProviderSignupPage,
  WebContactPage,
  WebSignInPage,
  WebProviderMeetingPointsPage,
  WebProviderBusinessProfilePage,
  WebProviderDashboardPage,
  WebProviderAddPackagePage,
  WebProviderEditPackagePage,
  WebProviderBookingsPage,
  WebAdminLoginPage,
  WebAdminDashboardPage,
});
