const { color: AC, font: AF, r: AR, shadow: ASH, type: ATY } = window.RAYA;

function readStoredUser() {
  try { return JSON.parse(localStorage.getItem('raya:user') || 'null'); }
  catch (e) { return null; }
}

function BottomNav({ tab, setTab, lang }) {
  const isAr = lang === 'ar';
  const tabs = [
    { id: 'home',     ar: 'الرئيسية',    en: 'Home',     icon: 'home' },
    { id: 'explore',  ar: 'استكشف',      en: 'Explore',  icon: 'search' },
    { id: 'trips',    ar: 'حجوزاتي',     en: 'Trips',    icon: 'bookmark' },
    { id: 'saved',    ar: 'المفضلة',     en: 'Saved',    icon: 'heart' },
    { id: 'profile',  ar: 'حسابي',       en: 'Profile',  icon: 'user' },
  ];
  return (
    <div style={{
      position: 'absolute', left: 16, right: 16, bottom: 18, zIndex: 90,
      padding: 6, borderRadius: AR.pill,
      background: 'rgba(255,255,255,0.78)',
      backdropFilter: 'blur(24px) saturate(180%)',
      WebkitBackdropFilter: 'blur(24px) saturate(180%)',
      border: '1px solid rgba(255,255,255,0.6)',
      boxShadow: '0 1px 0 rgba(255,255,255,0.6) inset, 0 6px 18px rgba(10,22,40,0.06), 0 20px 48px rgba(10,22,40,0.14)',
      display: 'flex', gap: 2, justifyContent: 'space-around',
      direction: isAr ? 'rtl' : 'ltr',
    }}>
      {tabs.map(t => {
        const active = tab === t.id;
        return (
          <button key={t.id} onClick={() => setTab(t.id)} className="raya-btn" style={{
            flex: active ? 1.7 : 1,
            padding: active ? '10px 16px' : '10px 8px',
            borderRadius: AR.pill,
            background: active ? AC.ink : 'transparent',
            border: 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            cursor: 'pointer',
            color: active ? AC.paper : AC.ink60,
            boxShadow: active ? '0 6px 16px rgba(10,22,40,0.25)' : 'none',
            transition: 'flex 0.32s cubic-bezier(.2,.7,.3,1), padding 0.3s, background 0.2s',
            overflow: 'hidden',
          }}>
            <RIcon
              name={active ? (t.icon + 'Fill') : t.icon}
              size={20}
              color={active ? AC.paper : AC.ink60}
              sw={1.8}
            />
            {active && (
              <span style={{
                fontFamily: isAr ? AF.bodyAr : AF.bodyEn,
                fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap',
                letterSpacing: isAr ? 0 : -0.1,
              }}>{isAr ? t.ar : t.en}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

function RayaApp({ initialTab = 'home', initialLang = 'ar', showSplash = false }) {
  const [tab, setTab] = React.useState(initialTab);
  const [exploreCat, setExploreCat] = React.useState('all');
  const [lang, setLang] = React.useState(initialLang);
  const [currency, setCurrency] = React.useState('EGP');
  const [favs, setFavs] = React.useState(new Set(['a1', 'b1']));
  const [detail, setDetail] = React.useState(null);
  const [booking, setBooking] = React.useState(null);
  const [confirmed, setConfirmed] = React.useState(null);
  const [bookings, setBookings] = React.useState([]);
  const [splash, setSplash] = React.useState(showSplash);
  const [login, setLogin] = React.useState(false);
  const [user, setUser] = React.useState(readStoredUser);

  React.useEffect(() => {
    if (!showSplash) return;
    const t = setTimeout(() => setSplash(false), 2400);
    return () => clearTimeout(t);
  }, [showSplash]);

  React.useEffect(() => { window.__rayaCurrency = currency; }, [currency]);

  const toggleFav = (id) => {
    const n = new Set(favs);
    n.has(id) ? n.delete(id) : n.add(id);
    setFavs(n);
  };

  const openListing = (it) => setDetail(it);
  const openSearch = (cat) => {
    setExploreCat(cat || 'all');
    setTab('explore');
  };
  const handleSignIn = (u) => {
    setUser(u);
    try { localStorage.setItem('raya:user', JSON.stringify(u)); } catch (e) {}
    setLogin(false);
  };
  const handleSignOut = () => {
    setUser(null);
    try { localStorage.removeItem('raya:user'); } catch (e) {}
  };

  const current = (() => {
    if (detail) return (
      <DetailsScreen item={detail} lang={lang} currency={currency}
        onBack={() => setDetail(null)}
        favs={favs} toggleFav={toggleFav}
        onBook={() => setBooking(detail)}
      />
    );
    if (tab === 'home') return <HomeScreen lang={lang} currency={currency} favs={favs} toggleFav={toggleFav} openListing={openListing} openSearch={openSearch}/>;
    if (tab === 'explore') return <ExploreScreen lang={lang} currency={currency} favs={favs} toggleFav={toggleFav} openListing={openListing} onBack={() => setTab('home')} initialCategory={exploreCat}/>;
    if (tab === 'trips') return <BookingsScreen lang={lang} currency={currency} bookings={bookings} openListing={openListing} onExplore={() => openSearch('all')}/>;
    if (tab === 'saved') return <FavoritesScreen lang={lang} currency={currency} favs={favs} toggleFav={toggleFav} openListing={openListing}/>;
    if (tab === 'profile') return <ProfileScreen lang={lang} setLang={setLang} currency={currency} setCurrency={setCurrency} setTab={setTab} user={user} onSignIn={() => setLogin(true)} onSignOut={handleSignOut}/>;
  })();

  return (
    <div style={{ position: 'relative', height: '100%', overflow: 'hidden', background: AC.paper }}>
      <div key={detail?.id || tab} className="raya-scroll raya-fadein" style={{
        height: '100%', overflow: 'auto',
      }}>
        {current}
      </div>
      {!detail && <BottomNav tab={tab} setTab={setTab} lang={lang}/>}

      {booking && (
        <BookingSheet item={booking} lang={lang} currency={currency}
          onClose={() => setBooking(null)}
          onConfirm={(b) => {
            setBookings([b, ...bookings]);
            setBooking(null);
            setConfirmed(b);
          }}
        />
      )}
      {confirmed && (
        <BookingSuccess lang={lang} onClose={() => {
          setConfirmed(null); setDetail(null); setTab('trips');
        }}/>
      )}
      {login && (
        <LoginScreen lang={lang} onClose={() => setLogin(false)} onSignIn={handleSignIn}/>
      )}
      {splash && <SplashScreen lang={lang}/>}
    </div>
  );
}

window.RayaApp = RayaApp;
