const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = { confetti: true, suits: true };

// Read first path segment from URL (/samawar → "samawar", / → null)
function getSlug() {
  const path = window.location.pathname.replace(/^\/|\/$/g, "");
  if (!path) return null;
  return path.split("/")[0].toLowerCase();
}

// ── Main router ───────────────────────────────────────────────
function App() {
  const slug = getSlug();

  if (!slug) {
    return (
      <div className="shilletna-wrapper">
        <SuitsBG enabled />
        <ShilletnaLanding />
      </div>
    );
  }

  return <GroupApp slug={slug} />;
}

// ── Group app (existing single-group app, now slug-aware) ─────
function GroupApp({ slug }) {
  const [page, setPage]           = useStateApp("landing");
  const [profileId, setProfileId] = useStateApp(1);
  const [tweaks, setTweaks]       = useStateApp(TWEAK_DEFAULTS);
  const [confetti, setConfetti]   = useStateApp(false);
  const [tick, setTick]           = useStateApp(0);

  useEffectApp(() => {
    const unsub = DB.subscribe(() => setTick(t => t + 1));
    DB.load(slug);
    return unsub;
  }, [slug]);

  function openProfile(id) { setProfileId(id); setPage("profile"); }
  function nav(p) { setPage(p); }
  function fireConfetti() { setConfetti(false); requestAnimationFrame(() => setConfetti(true)); }

  // ── Loading ──
  if (DB.loading && !DB.raw) {
    return (
      <div style={{
        position: "fixed", inset: 0,
        display: "flex", alignItems: "center", justifyContent: "center",
        flexDirection: "column", gap: 20,
        background: "radial-gradient(ellipse at 50% 0%, var(--felt-light) 0%, var(--felt) 45%, var(--felt-dark) 100%)",
      }}>
        <SuitsBG enabled />
        <div style={{ position: "relative", zIndex: 5, display: "flex", flexDirection: "column", alignItems: "center", gap: 20 }}>
          <div style={{ fontFamily: "Rakkas, serif", fontSize: 100, color: "var(--gold)", textShadow: "0 0 30px var(--gold)", lineHeight: 1, animation: "badge-shake 1.2s ease-in-out infinite" }}>♠</div>
          <div style={{ fontFamily: "Lalezar, serif", fontSize: 28, color: "var(--cream)", textShadow: "2px 2px 0 #000" }}>جاري التحميل…</div>
        </div>
      </div>
    );
  }

  // ── Group not found ──
  if (DB.error === "not-found") {
    return (
      <div className="phone" style={{ display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 12, padding: 30, textAlign: "center", minHeight: "100vh" }}>
        <SuitsBG enabled />
        <div style={{ position: "relative", zIndex: 3 }}>
          <div style={{ fontFamily: "Rakkas, serif", fontSize: 80, color: "var(--red)", textShadow: "0 0 20px var(--red)" }}>♠</div>
          <div style={{ fontFamily: "Lalezar, serif", fontSize: 26, color: "var(--cream)", marginBottom: 6 }}>مجموعة غير موجودة</div>
          <div style={{ fontFamily: "Cairo, sans-serif", fontSize: 14, color: "var(--cream)", opacity: 0.55, marginBottom: 22 }}>«{slug}» مش موجودة عندنا</div>
          <a href="/" style={{
            display: "inline-block", textDecoration: "none",
            fontFamily: "Lalezar, serif", fontSize: 20,
            background: "var(--gold)", color: "#000",
            border: "3px solid #000", borderRadius: 16,
            padding: "12px 28px", boxShadow: "4px 4px 0 #000",
          }}>← الرئيسية</a>
        </div>
      </div>
    );
  }

  // ── Other error ──
  if (DB.error) {
    return (
      <div className="phone" style={{ display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", gap: 16, padding: 30 }}>
        <div style={{ fontFamily: "Rakkas, serif", fontSize: 60, color: "var(--red)" }}>☠</div>
        <div style={{ fontFamily: "Lalezar, serif", fontSize: 24, color: "var(--red)", textAlign: "center" }}>خطأ في الاتصال</div>
        <div style={{ fontFamily: "Cairo, sans-serif", fontSize: 13, color: "var(--cream)", opacity: 0.7, textAlign: "center" }}>{DB.error}</div>
        <button className="btn-primary" style={{ marginTop: 10 }} onClick={() => DB.load(slug)}>إعادة المحاولة</button>
      </div>
    );
  }

  const NAV_ITEMS = [
    { id: "leaderboard", label: "الأبطال",   icon: "♛" },
    { id: "history",     label: "المباريات", icon: "♦" },
    { id: "profile",     label: "البروفايل", icon: "♥" },
    { id: "admin",       label: "إدارة",     icon: "♠" },
  ];

  return (
    <div className="phone">
      {tweaks.suits && <SuitsBG enabled />}

      {/* Desktop sidebar — hidden on mobile via CSS */}
      {page !== "landing" && (
        <nav className="sidebar-nav">
          <div className="sidebar-brand">
            <div className="sidebar-suit">♠</div>
            <div className="sidebar-name">شلتنا</div>
          </div>
          {NAV_ITEMS.map(item => (
            <button key={item.id}
              className={`sidebar-btn${page === item.id ? " active" : ""}`}
              onClick={() => nav(item.id)}>
              <span className="sidebar-ico">{item.icon}</span>
              <span className="sidebar-lbl">{item.label}</span>
            </button>
          ))}
        </nav>
      )}

      {/* Page content */}
      <div className="content-area">
        {page === "landing"     && <LandingPage onEnter={() => setPage("leaderboard")} />}
        {page === "leaderboard" && <LeaderboardPage onOpenProfile={openProfile} />}
        {page === "profile"     && <ProfilePage playerId={profileId} onBack={() => setPage("leaderboard")} />}
        {page === "history"     && <HistoryPage />}
        {page === "admin"       && <AdminPage onSaved={() => { setPage("leaderboard"); fireConfetti(); }} />}
      </div>

      {/* Mobile bottom nav — hidden on desktop via CSS */}
      {page !== "landing" && <BottomNav page={page} onNav={nav} />}

      {tweaks.confetti && <Confetti fire={confetti} onDone={() => setConfetti(false)} />}
      <TweaksPanel tweaks={tweaks} setTweaks={setTweaks} onFireConfetti={fireConfetti} />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
