import { SessionProvider } from "@xtablo/shared/contexts/SessionContext";
import { ThemeProvider } from "@xtablo/shared/contexts/ThemeContext";
import { Toaster } from "@xtablo/ui/components/sonner";
import { BrowserRouter as Router, useRoutes } from "react-router-dom";
import { CookieBanner } from "./components/CookieBanner";
import { PendingSignupCheckout } from "./components/PendingSignupCheckout";
import { TrialUpsellModal } from "./components/TrialUpsellModal";
import { UpgradePanel } from "./components/UpgradePanel";
import { UpgradeBlockProvider } from "./contexts/UpgradeBlockContext";
import { useCookieConsent } from "./hooks/useCookieConsent";
import { useDatadogRumViewName } from "./hooks/useDatadogRumViewName";
import { publicRoutes } from "./lib/publicRoutes";
import { routes } from "./lib/routes";
import { supabase } from "./lib/supabase";
import { NotFoundPage } from "./pages/NotFoundPage";
import { UserStoreProvider } from "./providers/UserStoreProvider";

const Routes = () => {
  useDatadogRumViewName();
  const publicElement = useRoutes(publicRoutes);
  const appElement = useRoutes(routes);

  // If public route matched, render it (outside UserStoreProvider)
  if (publicElement) {
    return publicElement;
  }

  // If app route matched, render it inside UserStoreProvider and UpgradeBlockProvider
  if (appElement) {
    return (
      <UserStoreProvider>
        <UpgradeBlockProvider>
          <PendingSignupCheckout />
          <UpgradePanel />
          <TrialUpsellModal />
          {appElement}
        </UpgradeBlockProvider>
      </UserStoreProvider>
    );
  }

  // Neither matched, show 404
  return <NotFoundPage />;
};

export const App = () => {
  const { showBanner, acceptAll, rejectAll, saveConsent } = useCookieConsent();

  return (
    <ThemeProvider>
      <SessionProvider supabase={supabase}>
        <Toaster />
        <Router>
          <div className="min-h-screen bg-background">
            <Routes />
            {showBanner && (
              <CookieBanner
                onAcceptAll={acceptAll}
                onRejectAll={rejectAll}
                onSavePreferences={saveConsent}
              />
            )}
            <style>
              {`
                  @keyframes slide {
                    0% { transform: translateX(-100vw); }
                    100% { transform: translateX(100vw); }
                  }
                  .animate-slide {
                    animation: slide 24s linear infinite;
                  }
                `}
            </style>
          </div>
        </Router>
      </SessionProvider>
    </ThemeProvider>
  );
};
