// 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 } = useWeb();
  const [filtersOpen, setFiltersOpen] = React.useState(false);

  const packages = [
    { 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' },
  ];

  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 }}>{rtl ? 'جدة → مكة' : 'Jeddah → Makkah'}</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 }}>16 Ramadan · 10 days</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 }}>{rtl ? '3 مسافرين' : '3 travelers'}</span>
            </div>
            <button 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 }}>
                  {rtl ? 'جدة → مكة · 16–25 رمضان · 3 مسافرين' : 'Jeddah → Makkah · 16–25 Ramadan · 3 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' }}>
                    <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} 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' }}>
            <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} 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: 'plane', t: rtl ? 'مع طيران' : 'Flight included', l: rtl ? 'السفر' : 'Travel' },
                { i: 'coffee', t: p.board, l: 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 }}>
              {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>

            {/* 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 }}>
              {[
                { 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>
              ))}
            </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} 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 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 ? 'مقاعد متبقية · ينتهي بعد 02:14:38' : 'seats left · closes in 02:14:38'}
                </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 }}>3 {l.persons}</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 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> {rtl ? 'استرداد كامل قبل 7 أيام، 50% بعد ذلك.' : 'Full refund up to 7 days, 50% after.'}
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function WebCheckoutPage({ theme, lang }) {
  const T = theme;
  const rtl = isRTL(lang);
  const { pkg, setPage } = useWeb();
  const [form, setForm] = React.useState({ firstName: '', lastName: '', email: '', phone: '' });
  const [busy, setBusy] = React.useState(false);
  const [message, setMessage] = React.useState('');
  const update = e => setForm(v => ({ ...v, [e.target.name]: e.target.value }));
  const submit = async e => {
    e.preventDefault(); setBusy(true); setMessage('');
    try {
      const response = await fetch(`${window.DUYUF_API_URL}/v1/payments/edfapay/create`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(form),
      });
      const body = await response.json();
      if (!response.ok || !body.redirectUrl) throw new Error(body.error || 'gateway_error');
      window.location.assign(body.redirectUrl);
    } catch (_) {
      setMessage(rtl ? 'تعذر فتح بوابة الدفع. راجع البيانات وحاول مرة أخرى.' : 'Could not open the payment gateway. Check your details and retry.');
      setBusy(false);
    }
  };
  const input = (name, label, type='text', placeholder='') => <label style={{ display:'grid', gap:7, fontFamily:'Alexandria', color:T.textMuted, fontSize:12 }}><span>{label}</span><input required name={name} type={type} value={form[name]} onChange={update} placeholder={placeholder} style={{ width:'100%', minHeight:50, border:`1px solid ${T.hairlineStrong}`, borderRadius:12, padding:'0 14px', background:T.surfaceAlt, color:T.text, font:'500 14px Alexandria' }}/></label>;
  return <div style={{ minHeight:650, background:T.bg, padding:'32px 16px 70px' }}><form onSubmit={submit} style={{ maxWidth:620, margin:'0 auto', padding:'clamp(20px,5vw,34px)', background:T.surface, border:`1px solid ${T.hairline}`, borderRadius:20, boxShadow:T.cardShadow }}><button type="button" onClick={() => setPage('detail')} style={{ border:0, background:'transparent', color:T.textMuted, cursor:'pointer' }}>→ {rtl?'العودة إلى الباقة':'Back to package'}</button><h1 style={{ font:'700 26px Alexandria', color:T.text, marginBottom:8 }}>{rtl?'تجربة السداد':'Payment test'}</h1><p style={{ color:T.textMuted, font:'400 13px/1.8 Alexandria' }}>{rtl?`سنفتح صفحة EdfaPay الرسمية لتجربة دفع 1 ر.س فقط. سعر الباقة ${Number(pkg?.price || 0).toLocaleString()} ر.س لن يُخصم في هذه التجربة.`:`We will open the official EdfaPay page for a SAR 1 test only. The package price will not be charged in this test.`}</p><div style={{ padding:14, margin:'18px 0', borderRadius:12, background:'rgba(193,152,114,.14)', color:T.text, font:'700 16px Alexandria' }}>{rtl?'المبلغ التجريبي: 1.00 ر.س':'Test amount: SAR 1.00'}</div><div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(min(100%,220px),1fr))', gap:14 }}>{input('firstName',rtl?'الاسم الأول':'First name')}{input('lastName',rtl?'اسم العائلة':'Last name')}{input('email',rtl?'البريد الإلكتروني':'Email','email','name@example.com')}{input('phone',rtl?'رقم الجوال السعودي':'Saudi mobile','tel','05xxxxxxxx')}</div>{message&&<p style={{ color:'#b42318', font:'500 12px Alexandria' }}>{message}</p>}<button disabled={busy} type="submit" style={{ width:'100%', minHeight:52, marginTop:22, border:0, borderRadius:13, background:T.primary, color:'#fff', font:'700 15px Alexandria', cursor:'pointer', opacity:busy?.65:1 }}>{busy?(rtl?'جارٍ فتح بوابة الدفع…':'Opening payment gateway…'):(rtl?'الدفع التجريبي عبر EdfaPay':'Test payment with EdfaPay')}</button></form></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.'}/>

      <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 ? .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);

  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 }}>
            <div 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 }}>
                {[
                  { l: rtl ? 'الاسم' : 'Name', v: rtl ? 'محمد الفهد' : 'Mohammed AlFahd' },
                  { l: rtl ? 'البريد' : 'Email', v: 'm.alfahd@email.com' },
                ].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>
                    <div style={{ height: 44, padding: '0 12px', borderRadius: 10, background: T.bg, border: `1px solid ${T.hairlineStrong}`, display: 'flex', alignItems: 'center', fontFamily: 'Alexandria', fontSize: 13.5, color: T.text }}>{f.v}</div>
                  </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>
                <div style={{ height: 44, padding: '0 12px', borderRadius: 10, background: T.bg, border: `1px solid ${T.hairlineStrong}`, display: 'flex', alignItems: 'center', fontFamily: 'Alexandria', fontSize: 13.5, color: T.text }}>{rtl ? 'استفسار عن حجز قائم' : 'Question about an existing booking'}</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 ? 'الرسالة' : 'Message'}</label>
                <div style={{ minHeight: 120, padding: 12, borderRadius: 10, background: T.bg, border: `1px solid ${T.hairlineStrong}`, fontFamily: 'Alexandria', fontSize: 13.5, color: T.textFaint, lineHeight: 1.6 }}>
                  {rtl ? 'اكتب رسالتك هنا…' : 'Type your message here…'}
                </div>
              </div>
              <button 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>
            </div>

            {/* 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 ? .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 WebProviderDashboardPage({ theme, lang }) {
  const T = theme, rtl = isRTL(lang), { setPage } = 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); })
      .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%,280px),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') : (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 ? 'شخص' : 'people'}</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>)}</div>}
    </div>
  </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 [form, setForm] = React.useState({ title: '', hotelName: '', durationDays: 7, pricePerPerson: '', availableFrom: iso(today), availableTo: iso(after30), seats: 1 });
  const [busy, setBusy] = React.useState(false), [message, setMessage] = React.useState('');
  const field = (key, label, type='text') => <label style={{ display: 'flex', flexDirection: 'column', gap: 6, color: T.textMuted, fontFamily: 'Alexandria', fontSize: 12 }}>{label}<input type={type} value={form[key]} onChange={e => setForm({ ...form, [key]: e.target.value })} style={{ boxSizing: 'border-box', width: '100%', height: 46, borderRadius: 11, border: `1px solid ${T.hairlineStrong}`, background: T.bg, color: T.text, padding: '0 12px', fontFamily: 'Alexandria', fontSize: 14 }}/></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:6,color:T.textMuted,fontFamily:'Alexandria',fontSize:12 }}><span>{label}</span><div dir="ltr" style={{ height:48,borderRadius:11,border:`1px solid ${T.hairlineStrong}`,background:T.bg,display:'grid',gridTemplateColumns:'52px 1fr 52px',overflow:'hidden' }}><button type="button" aria-label={rtl?`تقليل ${label}`:`Decrease ${label}`} onClick={() => update(value-1)} disabled={value<=min} style={{ border:0,borderRight:`1px solid ${T.hairline}`,background:'transparent',color:T.text,fontSize:24,cursor:'pointer',opacity:value<=min ? .35 : 1 }}>−</button><input type="number" min={min} max={max} value={value} onChange={e => update(Number(e.target.value))} style={{ width:'100%',minWidth: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={{ border:0,borderLeft:`1px solid ${T.hairline}`,background:'transparent',color:T.text,fontSize:24,cursor:'pointer',opacity:value>=max ? .35 : 1 }}>+</button></div></div>;
  };
  const save = async e => { e.preventDefault(); setBusy(true); setMessage(''); try { const token=localStorage.getItem('duyuf_provider_session'); const payload={...form,title:form.title.trim()||`باقة ${form.hotelName.trim()}`,durationDays:Number(form.durationDays),pricePerPerson:Number(form.pricePerPerson),seats:Number(form.seats)}; 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){const labels={hotelName:'اسم الفندق',durationDays:'عدد الأيام',pricePerPerson:'سعر الفرد',capacity:'السعة بالأشخاص',availableFrom:'تاريخ البداية',availableTo:'تاريخ النهاية'}; const fields=(b.fields||[]).map(x=>labels[x]||x).join('، '); throw new Error(fields||b.error||'save_failed');} setPage('provider-dashboard'); } catch(error) { setMessage(rtl?`تعذر الحفظ. راجع: ${error.message}`:`Could not save. Check: ${error.message}`); } finally { setBusy(false); } };
  return <div style={{ minHeight: 650, background: T.bg, padding: '28px 16px 70px' }}><form onSubmit={save} style={{ maxWidth: 680, margin: '0 auto', background: T.surface, border: `1px solid ${T.hairline}`, borderRadius: 20, padding: 'clamp(18px,5vw,32px)' }}><button type="button" onClick={() => setPage('provider-dashboard')} style={{ border:0,background:'transparent',color:T.textMuted,cursor:'pointer' }}>→ {rtl?'العودة إلى باقاتي':'Back to packages'}</button><h1 style={{ color:T.text,fontFamily:'Alexandria',fontSize:24 }}>{rtl?'إضافة باقة سريعة':'Quick package setup'}</h1><p style={{ color:T.textMuted,fontFamily:'Alexandria',fontSize:12,lineHeight:1.7 }}>{rtl?'أدخل الأساسيات الآن، ويمكنك إضافة التفاصيل والصور لاحقاً. اسم الباقة اختياري ويُنشأ تلقائياً من الفندق.':'Enter the essentials now; add details and photos later. Package title is generated from the hotel if left blank.'}</p><div style={{ display:'grid',gridTemplateColumns:'repeat(auto-fit,minmax(min(100%,220px),1fr))',gap:14 }}>{field('title',rtl?'اسم الباقة (اختياري)':'Package title (optional)')}{field('hotelName',rtl?'اسم الفندق':'Hotel name')}{stepper('durationDays',rtl?'عدد الأيام':'Duration (days)',1,60)}{field('pricePerPerson',rtl?'سعر الفرد بالريال':'Price per person','number')}{field('availableFrom',rtl?'متاحة من':'Available from','date')}{field('availableTo',rtl?'متاحة إلى':'Available to','date')}{stepper('seats',rtl?'السعة بالأشخاص':'Capacity (people)',1,999)}</div>{message&&<p style={{color:'#b42318',fontFamily:'Alexandria',fontSize:12}}>{message}</p>}<button disabled={busy} type="submit" style={{ width:'100%',marginTop:22,padding:14,border:0,borderRadius:13,background:T.primary,color:'#fff',fontFamily:'Alexandria',fontWeight:700,opacity:busy ? .6 : 1 }}>{busy?(rtl?'جارٍ الحفظ…':'Saving…'):(rtl?'إرسال الباقة للاعتماد':'Submit package for approval')}</button></form></div>;
}

Object.assign(window, { WebContext, useWeb, WebPageHeader, WebBrowsePage, WebDetailPage, WebCheckoutPage, WebPaymentResultPage, WebProviderSignupPage, WebContactPage, WebSignInPage, WebProviderDashboardPage, WebProviderAddPackagePage });
