import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { BottomNav } from "@/components/BottomNav";
import { AppHeader } from "@/components/AppHeader";

import { supabase } from "@/integrations/supabase/client";
import { useRealtimeWallet } from "@/hooks/use-realtime-wallet";
import { usePushKeepAlive } from "@/hooks/use-push-keepalive";
import { useFundingSweep } from "@/hooks/use-funding-sweep";
import { BrandSplash } from "@/components/AppLogo";

export const Route = createFileRoute("/app")({
  ssr: false,
  beforeLoad: async () => {
    if (typeof window !== "undefined") {
      const { data, error } = await supabase.auth.getUser();
      if (error || !data.user) throw redirect({ to: "/login" });
    }
  },
  component: AppLayout,
});

function AppLayout() {
  const [userId, setUserId] = useState<string | null>(null);
  const [authReady, setAuthReady] = useState(false);
  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      setUserId(data.session?.user.id ?? null);
      setAuthReady(true);
    });
    const { data: sub } = supabase.auth.onAuthStateChange((_e, session) => {
      setUserId(session?.user?.id ?? null);
      setAuthReady(true);
    });
    return () => sub.subscription.unsubscribe();
  }, []);
  useRealtimeWallet(userId);
  usePushKeepAlive(userId);
  useFundingSweep(userId);

  if (!authReady || !userId) {
    return <BrandSplash label="Loading your wallet" />;
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md">
        <AppHeader />
        <main className="pb-4">
          <Outlet />
        </main>
      </div>
      <BottomNav />
    </div>
  );
}
