const { color: BC, font: BF, r: BR, shadow: BSH } = window.RAYA;
const { LISTINGS: BL } = window.RAYA_DATA;
const BCFG = window.RAYA_CONFIG;

const coverOfItem = (item) => (item && item.images && item.images[0]) || undefined;

function BookingsScreen({ lang, currency = 'EGP', bookings, openListing, onExplore }) {
  const isAr = lang === 'ar';
  const [tab, setTab] = React.useState('upcoming');

  if (bookings.length === 0) {
    return (
      <div style={{ background: BC.paper, minHeight: '100%', direction: isAr ? 'rtl' : 'ltr' }}>
        <div style={{ padding: '62px 20px 20px' }}>
          <h1 style={{
            margin: 0,
            fontFamily: isAr ? BF.displayAr : BF.displayEn,
            fontSize: 32, fontWeight: 400, color: BC.ink,
            letterSpacing: isAr ? 0 : -0.6,
            fontStyle: isAr ? 'normal' : 'italic',
          }}>{isAr ? 'حجوزاتي' : 'Trips'}</h1>
        </div>
        <div style={{
          textAlign: 'center', padding: '60px 32px',
        }}>
          <div style={{
            width: 96, height: 96, borderRadius: BR.pill, margin: '0 auto 24px',
            background: BC.cream, display: 'grid', placeItems: 'center',
          }}>
            <RIcon name="calendar" size={42} color={BC.brand} sw={1.4}/>
          </div>
          <h2 style={{
            margin: '0 0 10px',
            fontFamily: isAr ? BF.displayAr : BF.displayEn,
            fontSize: 22, fontWeight: 500, color: BC.ink,
          }}>{isAr ? 'لسه ما بدأتش رحلتك' : 'Your journey awaits'}</h2>
          <p style={{
            margin: '0 0 24px', textWrap: 'pretty',
            fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
            fontSize: 14, color: BC.ink60, lineHeight: 1.5,
          }}>
            {isAr
              ? 'احجز أول إقامة ليك وهتلاقي تفاصيلها هنا'
              : 'Your first booking will appear here. Let\'s find a place to love.'}
          </p>
          <RButton variant="primary" size="md" lang={lang} onClick={onExplore}>
            {isAr ? 'ابدأ الاستكشاف' : 'Start exploring'}
          </RButton>
        </div>
      </div>
    );
  }

  return (
    <div style={{ background: BC.paper, minHeight: '100%', paddingBottom: 120, direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{ padding: '62px 20px 16px' }}>
        <h1 style={{
          margin: '0 0 16px',
          fontFamily: isAr ? BF.displayAr : BF.displayEn,
          fontSize: 32, fontWeight: 400, color: BC.ink,
          letterSpacing: isAr ? 0 : -0.6,
          fontStyle: isAr ? 'normal' : 'italic',
        }}>{isAr ? 'حجوزاتي' : 'Trips'}</h1>
        <div style={{ display: 'flex', gap: 2, padding: 3, background: BC.ink05, borderRadius: BR.pill, width: 'fit-content' }}>
          {['upcoming', 'past'].map(t => (
            <button key={t} onClick={() => setTab(t)} className="raya-btn" style={{
              padding: '7px 18px', borderRadius: BR.pill, border: 'none',
              background: tab === t ? BC.white : 'transparent',
              boxShadow: tab === t ? '0 1px 3px rgba(10,22,40,0.08)' : 'none',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, fontWeight: 500, color: BC.ink, cursor: 'pointer',
            }}>
              {isAr ? (t === 'upcoming' ? 'القادمة' : 'السابقة') : (t === 'upcoming' ? 'Upcoming' : 'Past')}
            </button>
          ))}
        </div>
      </div>

      <div style={{ padding: '10px 20px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {bookings.map(b => (
          <div key={b.id} onClick={() => openListing(b.item)} className="raya-card" style={{
            background: BC.white, borderRadius: BR.lg, overflow: 'hidden',
            boxShadow: BSH.card, cursor: 'pointer',
          }}>
            <div style={{ display: 'flex', gap: 0, height: 120 }}>
              <div style={{ width: 110, flexShrink: 0, position: 'relative' }}>
                <RImage tone={b.item.tone} image={coverOfItem(b.item)} rounded={0} style={{ position: 'absolute', inset: 0 }}/>
              </div>
              <div style={{ flex: 1, padding: 14 }}>
                <div style={{
                  display: 'inline-block', padding: '3px 8px', borderRadius: BR.pill,
                  background: BC.brandSoft,
                  fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                  fontSize: 10, fontWeight: 600, color: BC.brand,
                  letterSpacing: 0.5, textTransform: isAr ? 'none' : 'uppercase',
                  marginBottom: 6,
                }}>{isAr ? 'مؤكد' : 'Confirmed'}</div>
                <h3 style={{
                  margin: '0 0 4px',
                  fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                  fontSize: 15, fontWeight: 600, color: BC.ink,
                }}>{isAr ? b.item.title_ar : b.item.title_en}</h3>
                <div style={{
                  fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                  fontSize: 12, color: BC.ink60, marginBottom: 8,
                }}>
                  <RIcon name="calendar" size={11} color={BC.ink60} sw={1.6}/> {b.dates}
                </div>
                <div style={{
                  fontFamily: BF.displayEn, fontSize: 14, fontWeight: 500, color: BC.ink,
                }}>{window.RAYA_CURRENCY.formatPrice(b.total, currency)}
                  <span style={{
                    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                    fontSize: 11, color: BC.ink60, fontWeight: 400,
                    marginLeft: isAr ? 0 : 4, marginRight: isAr ? 4 : 0,
                  }}>{isAr ? 'الإجمالي' : 'total'}</span>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function FavoritesScreen({ lang, currency = 'EGP', favs, toggleFav, openListing }) {
  const isAr = lang === 'ar';
  const all = [...BL.stays, ...BL.beaches, ...BL.trips, ...BL.activities];
  const favItems = all.filter(i => favs.has(i.id));

  return (
    <div style={{ background: BC.paper, minHeight: '100%', paddingBottom: 120, direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{ padding: '62px 20px 16px' }}>
        <h1 style={{
          margin: 0,
          fontFamily: isAr ? BF.displayAr : BF.displayEn,
          fontSize: 32, fontWeight: 400, color: BC.ink,
          letterSpacing: isAr ? 0 : -0.6,
          fontStyle: isAr ? 'normal' : 'italic',
        }}>{isAr ? 'المفضلة' : 'Saved'}</h1>
        <p style={{
          margin: '6px 0 0',
          fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
          fontSize: 13, color: BC.ink60,
        }}>{favItems.length} {isAr ? (favItems.length === 1 ? 'مكان محفوظ' : favItems.length === 2 ? 'مكانين محفوظين' : 'أماكن محفوظة') : 'saved place' + (favItems.length === 1 ? '' : 's')}</p>
      </div>

      {favItems.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '50px 32px' }}>
          <div style={{
            width: 96, height: 96, borderRadius: BR.pill, margin: '0 auto 24px',
            background: BC.cream, display: 'grid', placeItems: 'center',
          }}>
            <RIcon name="heart" size={42} color={BC.brand} sw={1.4}/>
          </div>
          <h2 style={{
            margin: '0 0 10px',
            fontFamily: isAr ? BF.displayAr : BF.displayEn,
            fontSize: 22, fontWeight: 500, color: BC.ink,
          }}>{isAr ? 'احفظ اللي عاجبك' : 'Keep what you love'}</h2>
          <p style={{
            margin: 0, textWrap: 'pretty',
            fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
            fontSize: 14, color: BC.ink60,
          }}>
            {isAr ? 'دوس على القلب عشان تحفظ الأماكن والشواطئ والرحلات اللي عاجباك' : 'Tap the heart on any place to save it for later.'}
          </p>
        </div>
      ) : (
        <div style={{ display: 'grid', gap: 16, padding: '10px 20px', gridTemplateColumns: '1fr 1fr' }}>
          {favItems.map(it => (
            <ListingCard key={it.id} item={it} lang={lang} compact
              fav={true}
              onFav={() => toggleFav(it.id)}
              onOpen={() => openListing(it)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function ProfileScreen({ lang, setLang, setTab, user, onSignIn, onSignOut }) {
  const isAr = lang === 'ar';
  const items = [
    { icon: 'user', ar: 'البيانات الشخصية', en: 'Account' },
    { icon: 'wallet', ar: 'المدفوعات', en: 'Payment methods' },
    { icon: 'bell', ar: 'الإشعارات', en: 'Notifications' },
    { icon: 'shield', ar: 'الخصوصية والأمان', en: 'Privacy & security' },
    { icon: 'message', ar: 'الدعم', en: 'Help center' },
  ];

  return (
    <div style={{ background: BC.paper, minHeight: '100%', paddingBottom: 120, direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{ padding: '62px 20px 0' }}>
        <h1 style={{
          margin: '0 0 24px',
          fontFamily: isAr ? BF.displayAr : BF.displayEn,
          fontSize: 32, fontWeight: 400, color: BC.ink,
          letterSpacing: isAr ? 0 : -0.6,
          fontStyle: isAr ? 'normal' : 'italic',
        }}>{isAr ? 'حسابي' : 'Profile'}</h1>

        {user ? (
          <div style={{
            padding: 20, borderRadius: BR.lg,
            background: `linear-gradient(135deg, ${BC.ink} 0%, ${BC.ink80} 100%)`,
            marginBottom: 20, position: 'relative', overflow: 'hidden',
          }}>
            <div style={{
              position: 'absolute', top: -40, right: -40, width: 140, height: 140,
              borderRadius: BR.pill, background: BC.brand, opacity: 0.25, filter: 'blur(30px)',
            }}/>
            <div style={{ display: 'flex', gap: 14, alignItems: 'center', position: 'relative', flexDirection: isAr ? 'row-reverse' : 'row' }}>
              <div style={{
                width: 56, height: 56, borderRadius: BR.pill,
                background: `linear-gradient(135deg, ${BC.brand}, oklch(0.55 0.18 260))`,
                display: 'grid', placeItems: 'center',
                fontFamily: BF.displayEn, fontSize: 22, fontWeight: 500, color: BC.white,
              }}>{(user.name || '?').trim().charAt(0).toUpperCase()}</div>
              <div style={{ flex: 1, textAlign: isAr ? 'right' : 'left' }}>
                <div style={{
                  fontFamily: isAr ? BF.displayAr : BF.displayEn,
                  fontSize: 18, fontWeight: 500, color: BC.white,
                }}>{user.name}</div>
                <div style={{
                  fontFamily: BF.bodyEn,
                  fontSize: 12, color: 'rgba(255,255,255,0.6)', direction: 'ltr',
                }}>{user.phone || user.email}</div>
              </div>
              {user.tier && (
                <div style={{
                  padding: '3px 8px', borderRadius: BR.pill,
                  background: BC.gold,
                  fontFamily: BF.bodyEn, fontSize: 10, fontWeight: 600, color: BC.ink,
                  letterSpacing: 1, textTransform: 'uppercase',
                }}>{user.tier}</div>
              )}
            </div>
            <div style={{
              display: 'flex', gap: 0, marginTop: 20, paddingTop: 16,
              borderTop: '1px solid rgba(255,255,255,0.12)',
            }}>
              {[
                { v: user.trips ?? 0, l_ar: 'رحلات', l_en: 'Trips' },
                { v: user.saved ?? 0, l_ar: 'مفضلة', l_en: 'Saved' },
                { v: user.rating ?? 0, l_ar: 'التقييم', l_en: 'Rating' },
              ].map((s, i) => (
                <div key={i} style={{ flex: 1, textAlign: 'center', borderLeft: i > 0 ? '1px solid rgba(255,255,255,0.12)' : 'none' }}>
                  <div style={{ fontFamily: BF.displayEn, fontSize: 18, fontWeight: 500, color: BC.white }}>{s.v}</div>
                  <div style={{ fontFamily: isAr ? BF.bodyAr : BF.bodyEn, fontSize: 11, color: 'rgba(255,255,255,0.6)' }}>{isAr ? s.l_ar : s.l_en}</div>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div style={{
            padding: 22, borderRadius: BR.lg,
            background: `linear-gradient(135deg, ${BC.brand} 0%, oklch(0.42 0.16 258) 100%)`,
            marginBottom: 20, position: 'relative', overflow: 'hidden',
            color: BC.white,
          }}>
            <div style={{
              fontFamily: isAr ? BF.displayAr : BF.displayEn,
              fontSize: 20, fontWeight: 500, marginBottom: 6,
            }}>{isAr ? 'سجل دخولك' : 'Sign in to Raya'}</div>
            <div style={{
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, color: 'rgba(255,255,255,0.85)', marginBottom: 16, lineHeight: 1.5,
            }}>{isAr ? 'احفظ رحلاتك، تابع حجوزاتك، وخليك على تواصل مع فريقنا.' : 'Save trips, track bookings, and stay connected with our team.'}</div>
            <button onClick={onSignIn} className="raya-btn" style={{
              padding: '10px 18px', borderRadius: BR.pill, border: 'none',
              background: BC.white, color: BC.brand, cursor: 'pointer',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 14, fontWeight: 600,
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              {isAr ? 'سجل دخول' : 'Sign in'}
              <RIcon name={isAr ? 'arrowLeft' : 'arrowRight'} size={14} color={BC.brand} sw={2}/>
            </button>
          </div>
        )}

        {/* language toggle */}
        <div style={{
          padding: '14px 16px', borderRadius: BR.md,
          background: BC.white, border: `1px solid ${BC.ink10}`,
          display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20,
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: BR.sm,
            background: BC.brandSoft, display: 'grid', placeItems: 'center',
          }}>
            <RIcon name="language" size={18} color={BC.brand} sw={1.6}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 14, fontWeight: 600, color: BC.ink,
            }}>{isAr ? 'اللغة' : 'Language'}</div>
          </div>
          <div style={{ display: 'flex', gap: 2, padding: 3, background: BC.ink05, borderRadius: BR.pill }}>
            {[{ id: 'ar', l: 'عربي' }, { id: 'en', l: 'English' }].map(o => (
              <button key={o.id} onClick={() => setLang(o.id)} className="raya-btn" style={{
                padding: '5px 12px', borderRadius: BR.pill, border: 'none',
                background: lang === o.id ? BC.white : 'transparent',
                boxShadow: lang === o.id ? '0 1px 3px rgba(10,22,40,0.08)' : 'none',
                fontFamily: o.id === 'ar' ? BF.bodyAr : BF.bodyEn,
                fontSize: 12, fontWeight: 500, color: BC.ink, cursor: 'pointer',
              }}>{o.l}</button>
            ))}
          </div>
        </div>

        {/* menu */}
        <div style={{
          borderRadius: BR.md, overflow: 'hidden',
          background: BC.white, border: `1px solid ${BC.ink10}`,
        }}>
          {items.map((it, i) => (
            <button key={i} className="raya-tap" style={{
              width: '100%', padding: '14px 16px', background: 'transparent',
              border: 'none', borderBottom: i < items.length - 1 ? `1px solid ${BC.ink10}` : 'none',
              display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
              flexDirection: isAr ? 'row-reverse' : 'row',
              textAlign: isAr ? 'right' : 'left',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: BR.sm,
                background: BC.ink05, display: 'grid', placeItems: 'center',
              }}>
                <RIcon name={it.icon} size={17} color={BC.ink} sw={1.6}/>
              </div>
              <span style={{
                flex: 1,
                fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                fontSize: 14, fontWeight: 500, color: BC.ink,
              }}>{isAr ? it.ar : it.en}</span>
              <RIcon name={isAr ? 'chevronLeft' : 'chevronRight'} size={16} color={BC.ink40}/>
            </button>
          ))}
        </div>

        {user && (
          <button onClick={onSignOut} className="raya-btn" style={{
            width: '100%', marginTop: 20, padding: '14px', borderRadius: BR.md,
            background: 'transparent', border: `1px solid ${BC.ink10}`,
            fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
            fontSize: 14, fontWeight: 500, color: BC.danger,
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <RIcon name="logout" size={16} color={BC.danger}/>
            {isAr ? 'تسجيل الخروج' : 'Sign out'}
          </button>
        )}
      </div>
    </div>
  );
}

const BK_MONTHS_AR = ['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];
const BK_MONTHS_EN = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
const BK_DAYS_AR   = ['أحد','اثنين','ثلاثاء','أربعاء','خميس','جمعة','سبت'];
const BK_DAYS_EN   = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];

function toAr(n) { return String(n).replace(/\d/g, d => '٠١٢٣٤٥٦٧٨٩'[+d]); }

function fmtDateRange(inDate, outDate, isAr) {
  if (!inDate || !outDate) return isAr ? 'اختر التواريخ' : 'Select dates';
  const months = isAr ? BK_MONTHS_AR : BK_MONTHS_EN;
  const fmt = (d) => {
    const day = isAr ? toAr(d.getDate()) : d.getDate();
    return `${day} ${months[d.getMonth()]}`;
  };
  return `${fmt(inDate)} - ${fmt(outDate)}`;
}

function Stepper({ value, setValue, min = 0, max = 99, lang }) {
  const isAr = lang === 'ar';
  return (
    <div style={{ display: 'flex', gap: 6 }}>
      <button onClick={() => setValue(Math.max(min, value - 1))} disabled={value <= min}
        className="raya-btn" style={{
          width: 28, height: 28, borderRadius: BR.pill, border: `1px solid ${BC.ink10}`,
          background: BC.white, cursor: value <= min ? 'not-allowed' : 'pointer',
          opacity: value <= min ? 0.4 : 1, display: 'grid', placeItems: 'center',
        }}><RIcon name="minus" size={12} color={BC.ink}/></button>
      <div style={{
        minWidth: 28, height: 28, display: 'grid', placeItems: 'center',
        fontFamily: isAr ? BF.bodyAr : BF.bodyEn, fontSize: 14, fontWeight: 600, color: BC.ink,
      }}>{isAr ? toAr(value) : value}</div>
      <button onClick={() => setValue(Math.min(max, value + 1))} disabled={value >= max}
        className="raya-btn" style={{
          width: 28, height: 28, borderRadius: BR.pill, border: 'none',
          background: BC.ink, cursor: value >= max ? 'not-allowed' : 'pointer',
          opacity: value >= max ? 0.4 : 1, display: 'grid', placeItems: 'center',
        }}><RIcon name="plus" size={12} color={BC.paper}/></button>
    </div>
  );
}

function DatePicker({ checkIn, checkOut, setCheckIn, setCheckOut, lang }) {
  const isAr = lang === 'ar';
  const today = new Date(); today.setHours(0,0,0,0);
  const [viewMonth, setViewMonth] = React.useState(() => new Date(today.getFullYear(), today.getMonth(), 1));

  const shiftMonth = (d) => setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() + d, 1));
  const year = viewMonth.getFullYear();
  const month = viewMonth.getMonth();
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const months = isAr ? BK_MONTHS_AR : BK_MONTHS_EN;
  const daysShort = isAr ? BK_DAYS_AR : BK_DAYS_EN;

  const pick = (day) => {
    const picked = new Date(year, month, day);
    if (!checkIn || (checkIn && checkOut)) {
      setCheckIn(picked); setCheckOut(null);
    } else if (picked <= checkIn) {
      setCheckIn(picked);
    } else {
      setCheckOut(picked);
    }
  };

  const isSame = (a, b) => a && b && a.getTime() === b.getTime();
  const isBetween = (d) => checkIn && checkOut && d > checkIn && d < checkOut;

  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(year, month, d));

  return (
    <div style={{
      background: BC.white, border: `1px solid ${BC.ink10}`, borderRadius: BR.md,
      padding: 14, marginBottom: 14,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 10,
      }}>
        <button onClick={() => shiftMonth(-1)} className="raya-btn" style={{
          width: 30, height: 30, borderRadius: BR.pill, border: 'none',
          background: BC.ink05, cursor: 'pointer', display: 'grid', placeItems: 'center',
        }}><RIcon name={isAr ? 'chevronRight' : 'chevronLeft'} size={14} color={BC.ink}/></button>
        <div style={{
          fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
          fontSize: 14, fontWeight: 600, color: BC.ink,
        }}>{months[month]} {isAr ? toAr(year) : year}</div>
        <button onClick={() => shiftMonth(1)} className="raya-btn" style={{
          width: 30, height: 30, borderRadius: BR.pill, border: 'none',
          background: BC.ink05, cursor: 'pointer', display: 'grid', placeItems: 'center',
        }}><RIcon name={isAr ? 'chevronLeft' : 'chevronRight'} size={14} color={BC.ink}/></button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2, marginBottom: 6 }}>
        {daysShort.map((d, i) => (
          <div key={i} style={{
            textAlign: 'center', fontSize: 10, color: BC.ink60, fontWeight: 500,
            fontFamily: isAr ? BF.bodyAr : BF.bodyEn, padding: '4px 0',
          }}>{d}</div>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
        {cells.map((d, i) => {
          if (!d) return <div key={i}/>;
          const past = d < today;
          const selectedIn  = isSame(d, checkIn);
          const selectedOut = isSame(d, checkOut);
          const between = isBetween(d);
          const selected = selectedIn || selectedOut;
          return (
            <button key={i} onClick={() => !past && pick(d.getDate())}
              disabled={past}
              style={{
                height: 34, border: 'none', borderRadius: 8,
                background: selected ? BC.brand : between ? BC.brandSoft : 'transparent',
                color: selected ? BC.white : past ? BC.ink20 : BC.ink,
                fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                fontSize: 13, fontWeight: selected ? 600 : 400,
                cursor: past ? 'not-allowed' : 'pointer', padding: 0,
              }}>
              {isAr ? toAr(d.getDate()) : d.getDate()}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function BookingSheet({ item, lang, currency = 'EGP', onClose, onConfirm }) {
  const isAr = lang === 'ar';
  const unitNightly = (item.unit_en || '/night').includes('night');

  const today = new Date(); today.setHours(0,0,0,0);
  const [checkIn, setCheckIn] = React.useState(() => { const d = new Date(today); d.setDate(d.getDate() + 7); return d; });
  const [checkOut, setCheckOut] = React.useState(() => { const d = new Date(today); d.setDate(d.getDate() + 12); return d; });
  const [showCal, setShowCal] = React.useState(false);

  const [adults, setAdults]     = React.useState(2);
  const [children, setChildren] = React.useState(0);

  const nights = (checkIn && checkOut)
    ? Math.max(1, Math.round((checkOut - checkIn) / 86400000))
    : 1;
  const units = unitNightly ? nights : (adults + children);

  const sub   = item.price * units;
  const total = sub;

  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(10,22,40,0.4)',
      display: 'flex', alignItems: 'flex-end', zIndex: 100,
      animation: 'raya-fadein 0.25s ease both',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', background: BC.paper,
        borderTopLeftRadius: BR.xl, borderTopRightRadius: BR.xl,
        maxHeight: '86%', overflow: 'auto', direction: isAr ? 'rtl' : 'ltr',
        animation: 'raya-fadein 0.3s cubic-bezier(.2,.7,.3,1) both',
      }}>
        {/* grip */}
        <div style={{ padding: '10px 0' }}>
          <div style={{
            width: 36, height: 4, borderRadius: BR.pill,
            background: BC.ink20, margin: '0 auto',
          }}/>
        </div>
        <div style={{ padding: '4px 22px 100px' }}>
          <h2 style={{
            margin: '0 0 20px',
            fontFamily: isAr ? BF.displayAr : BF.displayEn,
            fontSize: 24, fontWeight: 400, color: BC.ink,
            letterSpacing: isAr ? 0 : -0.4,
            fontStyle: isAr ? 'normal' : 'italic',
          }}>{isAr ? 'تأكيد الحجز' : 'Confirm your stay'}</h2>

          {/* item summary */}
          <div style={{
            padding: 14, borderRadius: BR.md, background: BC.white,
            border: `1px solid ${BC.ink10}`, marginBottom: 18,
            display: 'flex', gap: 12, alignItems: 'center',
          }}>
            <div style={{ width: 56, height: 56, borderRadius: BR.sm, overflow: 'hidden', flexShrink: 0 }}>
              <RImage tone={item.tone} image={coverOfItem(item)} rounded={0} style={{ width: '100%', height: '100%' }}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{
                fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                fontSize: 14, fontWeight: 600, color: BC.ink, marginBottom: 2,
              }}>{isAr ? item.title_ar : item.title_en}</div>
              <RatingChip rating={item.rating} reviews={item.reviews} compact lang={lang}/>
            </div>
          </div>

          {/* dates */}
          <div style={{ marginBottom: 14 }}>
            <label style={{
              display: 'block', marginBottom: 6,
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 11, fontWeight: 600, color: BC.ink60,
              letterSpacing: 0.5, textTransform: isAr ? 'none' : 'uppercase',
            }}>{isAr ? 'التواريخ' : 'Dates'}</label>
            <button onClick={() => setShowCal(s => !s)} className="raya-btn" style={{
              width: '100%', padding: '12px 14px', borderRadius: BR.sm,
              background: BC.white, border: `1px solid ${showCal ? BC.brand : BC.ink10}`,
              display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
              textAlign: isAr ? 'right' : 'left',
              flexDirection: isAr ? 'row-reverse' : 'row',
            }}>
              <RIcon name="calendar" size={16} color={BC.brand} sw={1.7}/>
              <span style={{
                flex: 1,
                fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                fontSize: 14, color: BC.ink,
              }}>{fmtDateRange(checkIn, checkOut, isAr)}</span>
              {unitNightly && checkIn && checkOut && (
                <span style={{
                  fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                  fontSize: 12, color: BC.ink60,
                }}>{isAr ? toAr(nights) : nights} {isAr ? (nights === 1 ? 'ليلة' : 'ليالي') : (nights === 1 ? 'night' : 'nights')}</span>
              )}
              <RIcon name={showCal ? 'chevronUp' : 'chevronDown'} size={14} color={BC.ink60}/>
            </button>
            {showCal && <div style={{ marginTop: 10 }}>
              <DatePicker checkIn={checkIn} checkOut={checkOut} setCheckIn={setCheckIn} setCheckOut={setCheckOut} lang={lang}/>
            </div>}
          </div>

          {/* guests: adults + children */}
          <div style={{ marginBottom: 14 }}>
            <label style={{
              display: 'block', marginBottom: 6,
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 11, fontWeight: 600, color: BC.ink60,
              letterSpacing: 0.5, textTransform: isAr ? 'none' : 'uppercase',
            }}>{isAr ? 'الضيوف' : 'Guests'}</label>
            <div style={{
              borderRadius: BR.sm,
              background: BC.white, border: `1px solid ${BC.ink10}`, overflow: 'hidden',
            }}>
              <div style={{
                padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
                borderBottom: `1px solid ${BC.ink10}`,
                flexDirection: isAr ? 'row-reverse' : 'row',
              }}>
                <RIcon name="user" size={16} color={BC.brand} sw={1.7}/>
                <div style={{ flex: 1, textAlign: isAr ? 'right' : 'left' }}>
                  <div style={{
                    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                    fontSize: 14, fontWeight: 500, color: BC.ink,
                  }}>{isAr ? 'بالغين' : 'Adults'}</div>
                  <div style={{
                    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                    fontSize: 11, color: BC.ink60,
                  }}>{isAr ? '١٣ سنة أو أكبر' : 'Ages 13 or above'}</div>
                </div>
                <Stepper value={adults} setValue={setAdults}
                  min={BCFG.booking.guestsMin} max={BCFG.booking.guestsMax} lang={lang}/>
              </div>
              <div style={{
                padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
                flexDirection: isAr ? 'row-reverse' : 'row',
              }}>
                <RIcon name="heart" size={16} color={BC.brand} sw={1.7}/>
                <div style={{ flex: 1, textAlign: isAr ? 'right' : 'left' }}>
                  <div style={{
                    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                    fontSize: 14, fontWeight: 500, color: BC.ink,
                  }}>{isAr ? 'أطفال' : 'Children'}</div>
                  <div style={{
                    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                    fontSize: 11, color: BC.ink60,
                  }}>{isAr ? 'أقل من ١٣ سنة' : 'Under 13'}</div>
                </div>
                <Stepper value={children} setValue={setChildren}
                  min={0} max={BCFG.booking.childrenMax} lang={lang}/>
              </div>
            </div>
          </div>

          {/* pricing breakdown */}
          <div style={{
            padding: 16, borderRadius: BR.md, background: BC.white,
            border: `1px solid ${BC.ink10}`, marginBottom: 20,
          }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', padding: '4px 0',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn, fontSize: 13, color: BC.ink60,
            }}>
              <span>{isAr
                ? `${window.RAYA_CURRENCY.formatPrice(item.price, currency)} × ${toAr(units)}`
                : `${window.RAYA_CURRENCY.formatPrice(item.price, currency)} × ${units} ${unitNightly ? (units === 1 ? 'night' : 'nights') : (units === 1 ? 'guest' : 'guests')}`}</span>
              <span>{window.RAYA_CURRENCY.formatPrice(sub, currency)}</span>
            </div>
            <div style={{
              display: 'flex', justifyContent: 'space-between', padding: '12px 0 0',
              marginTop: 8, borderTop: `1px solid ${BC.ink10}`,
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn, fontSize: 15, fontWeight: 600, color: BC.ink,
            }}>
              <span>{isAr ? 'الإجمالي' : 'Total'}</span>
              <span style={{ fontFamily: BF.displayEn, fontSize: 18, fontWeight: 500 }}>
                {window.RAYA_CURRENCY.formatPrice(total, currency)}
              </span>
            </div>
            <div style={{
              marginTop: 10, fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 11, color: BC.ink60, textAlign: isAr ? 'right' : 'left',
            }}>{isAr ? 'السعر النهائي شامل كل الرسوم' : 'Final price, all fees included'}</div>
          </div>

          <RButton variant="brand" size="lg" full lang={lang}
            onClick={() => onConfirm({
              id: 'b' + Date.now(), item,
              dates: fmtDateRange(checkIn, checkOut, isAr),
              checkIn, checkOut, nights,
              guests: adults + children, adults, children, total,
            })}>
            {isAr ? 'تأكيد الحجز' : 'Confirm & pay'}
          </RButton>
          <p style={{
            textAlign: 'center', margin: '12px 0 0',
            fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
            fontSize: 11, color: BC.ink60,
          }}>{isAr
            ? `إلغاء مجاني خلال ${toAr(BCFG.booking.cancelWindow)} ساعة`
            : `Free cancellation within ${BCFG.booking.cancelWindow} hours`}</p>
        </div>
      </div>
    </div>
  );
}

function BookingSuccess({ lang, onClose }) {
  const isAr = lang === 'ar';
  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(10,22,40,0.5)',
      display: 'grid', placeItems: 'center', zIndex: 110, padding: 24,
      animation: 'raya-fadein 0.25s ease both',
    }}>
      <div style={{
        background: BC.paper, borderRadius: BR.lg, padding: '32px 26px', textAlign: 'center',
        maxWidth: 320, animation: 'raya-fadein 0.3s ease 0.05s both',
      }}>
        <div style={{
          width: 72, height: 72, borderRadius: BR.pill,
          background: BC.brandSoft, margin: '0 auto 16px',
          display: 'grid', placeItems: 'center',
        }}>
          <RIcon name="check" size={34} color={BC.brand} sw={2.4}/>
        </div>
        <h2 style={{
          margin: '0 0 8px',
          fontFamily: isAr ? BF.displayAr : BF.displayEn,
          fontSize: 22, fontWeight: 500, color: BC.ink,
        }}>{isAr ? 'تم الحجز!' : 'You\'re booked!'}</h2>
        <p style={{
          margin: '0 0 22px',
          fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
          fontSize: 13, color: BC.ink60, lineHeight: 1.5,
        }}>{isAr ? 'تم إرسال التفاصيل على إيميلك' : 'We\'ve sent the details to your email.'}</p>
        <RButton variant="primary" size="md" full lang={lang} onClick={onClose}>
          {isAr ? 'شوف الحجز' : 'View booking'}
        </RButton>
      </div>
    </div>
  );
}

function LoginScreen({ lang = 'ar', onClose, onSignIn }) {
  const isAr = lang === 'ar';
  const [step, setStep] = React.useState('phone');
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const [otp, setOtp] = React.useState('');
  const [error, setError] = React.useState('');

  const phoneOk = /^\+?\d{7,15}$/.test(phone.replace(/\s/g, ''));
  const otpOk = otp.replace(/\s/g, '').length === 4;
  const nameOk = name.trim().length >= 2;

  const submitPhone = (e) => {
    e?.preventDefault?.();
    if (!phoneOk) { setError(isAr ? 'رقم الموبايل مش صح' : 'Enter a valid mobile number'); return; }
    setError('');
    setStep('otp');
  };

  const submitOtp = (e) => {
    e?.preventDefault?.();
    if (!otpOk) { setError(isAr ? 'كود التأكيد لازم يكون ٤ أرقام' : 'OTP must be 4 digits'); return; }
    setError('');
    setStep('name');
  };

  const submitName = (e) => {
    e?.preventDefault?.();
    if (!nameOk) { setError(isAr ? 'اكتب اسمك بالكامل' : 'Please enter your full name'); return; }
    setError('');
    onSignIn({
      name: name.trim(),
      phone: phone.trim(),
      tier: isAr ? 'ذهبي' : 'Gold',
      trips: 0, saved: 0, rating: 5.0,
    });
  };

  const inputBase = {
    width: '100%', padding: '13px 16px', borderRadius: BR.md,
    border: `1px solid ${BC.ink10}`, background: BC.white,
    fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
    fontSize: 15, color: BC.ink, outline: 'none',
    textAlign: isAr ? 'right' : 'left',
    direction: isAr ? 'rtl' : 'ltr',
    boxSizing: 'border-box',
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 120,
      background: 'rgba(10,22,40,0.45)',
      display: 'flex', alignItems: 'flex-end',
      animation: 'raya-fadein 0.25s ease both',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: BC.paper,
        borderTopLeftRadius: BR.xl, borderTopRightRadius: BR.xl,
        padding: '12px 22px 30px',
        direction: isAr ? 'rtl' : 'ltr',
        animation: 'raya-fadein 0.3s cubic-bezier(.2,.7,.3,1) both',
      }}>
        <div style={{
          width: 36, height: 4, borderRadius: BR.pill,
          background: BC.ink20, margin: '0 auto 18px',
        }}/>

        <div style={{ textAlign: 'center', marginBottom: 18 }}>
          <RayaLogo size={22} color={BC.brand} lang={lang}/>
        </div>

        {step === 'phone' && (
          <form onSubmit={submitPhone}>
            <h2 style={{
              margin: '0 0 6px', textAlign: 'center',
              fontFamily: isAr ? BF.displayAr : BF.displayEn,
              fontSize: 22, fontWeight: 500, color: BC.ink,
            }}>{isAr ? 'أهلاً بيك' : 'Welcome'}</h2>
            <p style={{
              margin: '0 0 20px', textAlign: 'center',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, color: BC.ink60,
            }}>{isAr ? 'ادخل رقم موبايلك عشان نبعتلك كود التأكيد' : 'Enter your mobile to receive a verification code.'}</p>
            <label style={{
              display: 'block', marginBottom: 6,
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 12, fontWeight: 600, color: BC.ink60,
            }}>{isAr ? 'رقم الموبايل' : 'Mobile number'}</label>
            <input
              type="tel" value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder={isAr ? '+20 10 0000 0000' : '+20 10 0000 0000'}
              autoComplete="tel"
              style={{ ...inputBase, direction: 'ltr', textAlign: 'left' }}
            />
            {error && <div style={{
              marginTop: 10, fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 12, color: BC.danger,
            }}>{error}</div>}
            <div style={{ marginTop: 20 }}>
              <RButton variant="brand" size="lg" full lang={lang} type="submit" disabled={!phoneOk}>
                {isAr ? 'استلم الكود' : 'Send code'}
              </RButton>
            </div>

            <div style={{
              display: 'flex', alignItems: 'center', gap: 10, margin: '22px 0 14px',
            }}>
              <div style={{ flex: 1, height: 1, background: BC.ink10 }}/>
              <span style={{
                fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                fontSize: 11, color: BC.ink60,
              }}>{isAr ? 'أو' : 'or'}</span>
              <div style={{ flex: 1, height: 1, background: BC.ink10 }}/>
            </div>

            <div style={{ display: 'flex', gap: 10 }}>
              {['Apple', 'Google'].map(p => (
                <button key={p} type="button" className="raya-btn" style={{
                  flex: 1, padding: '12px', borderRadius: BR.md,
                  background: BC.white, border: `1px solid ${BC.ink10}`,
                  fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
                  fontSize: 13, fontWeight: 600, color: BC.ink,
                  cursor: 'pointer', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }} onClick={() => setStep('otp')}>
                  <span style={{
                    display: 'inline-grid', placeItems: 'center',
                    width: 18, height: 18, borderRadius: BR.pill,
                    background: p === 'Apple' ? BC.ink : BC.brand,
                    color: BC.white, fontSize: 11, fontWeight: 700,
                  }}>{p.charAt(0)}</span>
                  {p}
                </button>
              ))}
            </div>
          </form>
        )}

        {step === 'otp' && (
          <form onSubmit={submitOtp}>
            <h2 style={{
              margin: '0 0 6px', textAlign: 'center',
              fontFamily: isAr ? BF.displayAr : BF.displayEn,
              fontSize: 22, fontWeight: 500, color: BC.ink,
            }}>{isAr ? 'كود التأكيد' : 'Enter code'}</h2>
            <p style={{
              margin: '0 0 20px', textAlign: 'center',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, color: BC.ink60,
            }}>{isAr ? `بعتنا كود من ٤ أرقام على ${phone || 'رقمك'}` : `We sent a 4-digit code to ${phone || 'your phone'}`}</p>
            <input
              type="text" inputMode="numeric" maxLength={4}
              value={otp}
              onChange={(e) => setOtp(e.target.value.replace(/[^0-9]/g, ''))}
              placeholder="••••"
              style={{
                ...inputBase, textAlign: 'center', letterSpacing: 10,
                fontSize: 24, fontWeight: 600, direction: 'ltr',
              }}
            />
            {error && <div style={{
              marginTop: 10, textAlign: 'center',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 12, color: BC.danger,
            }}>{error}</div>}
            <div style={{ marginTop: 20 }}>
              <RButton variant="brand" size="lg" full lang={lang} type="submit" disabled={!otpOk}>
                {isAr ? 'تأكيد' : 'Verify'}
              </RButton>
            </div>
            <button type="button" onClick={() => { setStep('phone'); setOtp(''); setError(''); }} className="raya-btn" style={{
              width: '100%', marginTop: 12, padding: 10, borderRadius: BR.pill,
              background: 'transparent', border: 'none',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, color: BC.ink60, cursor: 'pointer',
            }}>{isAr ? 'غيّر الرقم' : 'Change number'}</button>
          </form>
        )}

        {step === 'name' && (
          <form onSubmit={submitName}>
            <h2 style={{
              margin: '0 0 6px', textAlign: 'center',
              fontFamily: isAr ? BF.displayAr : BF.displayEn,
              fontSize: 22, fontWeight: 500, color: BC.ink,
            }}>{isAr ? 'عرّفنا بنفسك' : 'Tell us your name'}</h2>
            <p style={{
              margin: '0 0 20px', textAlign: 'center',
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 13, color: BC.ink60,
            }}>{isAr ? 'هنستخدم اسمك في الحجوزات والإشعارات' : 'We\u2019ll use your name on bookings and notifications.'}</p>
            <label style={{
              display: 'block', marginBottom: 6,
              fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 12, fontWeight: 600, color: BC.ink60,
            }}>{isAr ? 'الاسم الكامل' : 'Full name'}</label>
            <input
              type="text" value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder={isAr ? 'اكتب اسمك الكامل' : 'First and last name'}
              style={inputBase}
            />
            {error && <div style={{
              marginTop: 10, fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
              fontSize: 12, color: BC.danger,
            }}>{error}</div>}
            <div style={{ marginTop: 20 }}>
              <RButton variant="brand" size="lg" full lang={lang} type="submit" disabled={!nameOk}>
                {isAr ? 'يلا نبدأ' : 'Get started'}
              </RButton>
            </div>
          </form>
        )}

        <div style={{
          marginTop: 20, textAlign: 'center',
          fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
          fontSize: 11, color: BC.ink60, lineHeight: 1.6,
        }}>{isAr ? 'باستخدامك للتطبيق أنت بتوافق على شروط الاستخدام وسياسة الخصوصية' : 'By continuing, you agree to our Terms and Privacy Policy.'}</div>
      </div>
    </div>
  );
}

function SplashScreen({ lang = 'ar' }) {
  const isAr = lang === 'ar';
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 200,
      background: `linear-gradient(160deg, ${BC.brand} 0%, oklch(0.42 0.16 258) 100%)`,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      animation: 'raya-fadein 0.4s ease both',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', top: '15%', left: '-20%', width: 320, height: 320,
        borderRadius: '50%', background: 'rgba(255,255,255,0.08)', filter: 'blur(40px)',
      }}/>
      <div style={{
        position: 'absolute', bottom: '10%', right: '-15%', width: 280, height: 280,
        borderRadius: '50%', background: 'rgba(255,255,255,0.06)', filter: 'blur(50px)',
      }}/>

      <div style={{ animation: 'raya-fadein 0.8s cubic-bezier(.2,.7,.3,1) both' }}>
        <RayaLogo size={40} color={BC.white} tagline lang={lang}/>
      </div>

      <div style={{
        position: 'absolute', bottom: 60, left: 0, right: 0, textAlign: 'center',
        animation: 'raya-fadein 1s ease 0.3s both',
      }}>
        <div style={{
          display: 'inline-flex', gap: 6, alignItems: 'center',
        }}>
          {[0, 1, 2].map(i => (
            <span key={i} style={{
              width: 6, height: 6, borderRadius: '50%', background: 'rgba(255,255,255,0.6)',
              animation: `raya-pulse 1.2s ease ${i * 0.2}s infinite`,
            }}/>
          ))}
        </div>
        <div style={{
          marginTop: 12,
          fontFamily: isAr ? BF.bodyAr : BF.bodyEn,
          fontSize: 12, color: 'rgba(255,255,255,0.8)', letterSpacing: isAr ? 0 : 0.5,
        }}>{isAr ? 'رفاهية على شواطئ مصر' : 'Luxury on Egypt\u2019s shores'}</div>
      </div>
    </div>
  );
}

Object.assign(window, { BookingsScreen, FavoritesScreen, ProfileScreen, BookingSheet, BookingSuccess, SplashScreen, LoginScreen });
