/**
 * GoodlifeApp — slim entry-point for goodlifesocial.* visitors.
 *
 * Loaded by main.tsx via dynamic import when the hostname is a Goodlife
 * domain. Declares ONLY Goodlife + minimal public/auth routes. Easylife,
 * Buy Local, Accident Mate code paths never enter the initial bundle.
 *
 * Provider stack mirrors App.tsx because useAuth → TenantContext is shared
 * across the codebase. Forking TenantContext for Goodlife alone would be
 * higher-risk than the bundle saving warrants.
 */
import { Suspense } from "react";
import { BrowserRouter, Routes, Route, Navigate, useLocation } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Skeleton } from "@/components/ui/skeleton";
import { lazyRetry } from "@/lib/lazyRetry";
import { LocaleProvider } from "@/hooks/useLocale.tsx";
import { TenantProvider } from "@/contexts/TenantContext";
import { CustomerViewProvider } from "@/contexts/CustomerViewContext";
import { CartProvider } from "@/contexts/CartContext";
import { ErrorBoundary } from "@/components/ErrorBoundary";
import { useAuth } from "@/hooks/useAuth";
import GoodlifeRequireAuth from "@/components/goodlife/GoodlifeRequireAuth";

// Eager — the public landing must paint without an extra chunk fetch.
import GoodlifeLanding from "./pages/goodlife/GoodlifeLanding";

// Goodlife routes (lazy)
const GoodlifeHome = lazyRetry(() => import("./pages/goodlife/GoodlifeHome"));
const GoodlifeLayoutRoute = lazyRetry(() => import("./components/goodlife/GoodlifeLayoutRoute"));
const GoodlifeAuth = lazyRetry(() => import("./pages/goodlife/GoodlifeAuth"));
const GoodlifeSignup = lazyRetry(() => import("./pages/goodlife/GoodlifeSignup"));
const GoodlifeHandleClaim = lazyRetry(() => import("./pages/goodlife/GoodlifeHandleClaim"));
const GoodlifeWelcome = lazyRetry(() => import("./pages/goodlife/GoodlifeWelcome"));
const GoodlifeSignInMethods = lazyRetry(() => import("./pages/goodlife/GoodlifeSignInMethods"));
const GoodlifeProfileEdit = lazyRetry(() => import("./pages/goodlife/GoodlifeProfileEdit"));
const GoodlifeMessages = lazyRetry(() => import("./pages/goodlife/GoodlifeMessages"));
const GoodlifeTenantPage = lazyRetry(() => import("./pages/goodlife/GoodlifeTenantPage"));
const GoodlifeHandleResolver = lazyRetry(() => import("./pages/goodlife/GoodlifeHandleResolver"));
const GoodlifeTenantSettings = lazyRetry(() => import("./pages/goodlife/GoodlifeTenantSettings"));
const GoodlifeBusinessManagers = lazyRetry(() => import("./pages/goodlife/GoodlifeBusinessManagers"));
const GoodlifeBusinessProfileSettings = lazyRetry(() => import("./pages/goodlife/GoodlifeBusinessProfileSettings"));
const GoodlifeModerationConsole = lazyRetry(() => import("./pages/goodlife/GoodlifeModerationConsole"));
const GoodlifeGroups = lazyRetry(() => import("./pages/goodlife/GoodlifeGroups"));
const GoodlifeGroupPage = lazyRetry(() => import("./pages/goodlife/GoodlifeGroupPage"));
const GoodlifeEvents = lazyRetry(() => import("./pages/goodlife/GoodlifeEvents"));
const GoodlifeVideos = lazyRetry(() => import("./pages/goodlife/GoodlifeVideos"));
const GoodlifeMarketplace = lazyRetry(() => import("./pages/goodlife/GoodlifeMarketplace"));

const GoodlifeMyFeed = lazyRetry(() => import("./pages/goodlife/GoodlifeMyFeed"));
const GoodlifePhotos = lazyRetry(() => import("./pages/goodlife/GoodlifePhotos"));
const GoodlifeFriends = lazyRetry(() => import("./pages/goodlife/GoodlifeFriends"));
const GoodlifeInvite = lazyRetry(() => import("./pages/goodlife/GoodlifeInvite"));
const GoodlifeSearch = lazyRetry(() => import("./pages/goodlife/GoodlifeSearch"));
const GoodlifeCompose = lazyRetry(() => import("./pages/goodlife/GoodlifeCompose"));
const GoodlifeConnectedAccounts = lazyRetry(() => import("./pages/goodlife/GoodlifeConnectedAccounts"));
const GoodlifeFred = lazyRetry(() => import("./pages/goodlife/GoodlifeFred"));
const GoodlifeExplore = lazyRetry(() => import("./pages/goodlife/GoodlifeExplore"));
const GoodlifeNews = lazyRetry(() => import("./pages/goodlife/GoodlifeNews"));
const GoodlifeSnippets = lazyRetry(() => import("./pages/goodlife/GoodlifeSnippets"));
const GoodlifeBlogs = lazyRetry(() => import("./pages/goodlife/GoodlifeBlogs"));
const GoodlifeBlogPost = lazyRetry(() => import("./pages/goodlife/GoodlifeBlogPost"));

const GoodlifeNotifications = lazyRetry(() => import("./pages/goodlife/GoodlifeNotifications"));
const GoodlifeOffboarding = lazyRetry(() => import("./pages/goodlife/GoodlifeOffboarding"));
const GoodlifeMemories = lazyRetry(() => import("./pages/goodlife/GoodlifeMemories"));
const GoodlifeMeet = lazyRetry(() => import("./pages/goodlife/GoodlifeMeet"));
const GoodlifeCV = lazyRetry(() => import("./pages/goodlife/GoodlifeCV"));
const GoodlifeJobs = lazyRetry(() => import("./pages/goodlife/GoodlifeJobs"));
const GoodlifeJobDetail = lazyRetry(() => import("./pages/goodlife/GoodlifeJobDetail"));
const GoodlifeJobApplications = lazyRetry(() => import("./pages/goodlife/GoodlifeJobApplications"));
const GoodlifeJobsManage = lazyRetry(() => import("./pages/goodlife/GoodlifeJobsManage"));
const GoodlifeTalentBoard = lazyRetry(() => import("./pages/goodlife/GoodlifeTalentBoard"));
const GoodlifeJobAlerts = lazyRetry(() => import("./pages/goodlife/GoodlifeJobAlerts"));
const GoodlifeJobOffer = lazyRetry(() => import("./pages/goodlife/GoodlifeJobOffer"));
const GoodlifeJobsAnalytics = lazyRetry(() => import("./pages/goodlife/GoodlifeJobsAnalytics"));
const GoodlifeJobPipeline = lazyRetry(() => import("./pages/goodlife/GoodlifeJobPipeline"));
const GoodlifeJobMatch = lazyRetry(() => import("./pages/goodlife/GoodlifeJobMatch"));
const GoodlifeJobHealth = lazyRetry(() => import("./pages/goodlife/GoodlifeJobHealth"));
const GoodlifeApplicationReview = lazyRetry(() => import("./pages/goodlife/GoodlifeApplicationReview"));
const GoodlifeMyReferrals = lazyRetry(() => import("./pages/goodlife/GoodlifeMyReferrals"));
const GoodlifeTransparency = lazyRetry(() => import("./pages/goodlife/GoodlifeTransparency"));

// Goodlife portal — customer-facing pages
const GoodlifePortalDashboard = lazyRetry(() => import("./pages/community-user/CommunityUserDashboard"));
const GoodlifePortalShop = lazyRetry(() => import("./pages/community-user/CommunityUserShop"));
const GoodlifePortalMyOrders = lazyRetry(() => import("./pages/community-user/CommunityUserMyOrders"));
const GoodlifePortalBookings = lazyRetry(() => import("./pages/community-user/CommunityUserBookings"));
const GoodlifePortalMyBookings = lazyRetry(() => import("./pages/community-user/CommunityUserMyBookings"));
const GoodlifePortalAccount = lazyRetry(() => import("./pages/goodlife/GoodlifeAccountPage"));
const GoodlifePortalMyFeedback = lazyRetry(() => import("./pages/community-user/CommunityUserMyFeedback"));
const GoodlifePortalNetwork = lazyRetry(() => import("./pages/community-user/CommunityUserNetwork"));
const GoodlifePortalMyTickets = lazyRetry(() => import("./pages/community-user/CommunityUserMyTickets"));
const GoodlifeProviders = lazyRetry(() => import("./pages/goodlife-portal/GoodlifeProviders"));

// Minimal shared public routes
const ResetPassword = lazyRetry(() => import("./pages/ResetPassword"));
const SetPassword = lazyRetry(() => import("./pages/SetPassword"));
const PlatformPolicyPage = lazyRetry(() => import("./pages/PlatformPolicyPage"));
const CookiePolicy = lazyRetry(() => import("./pages/CookiePolicy"));
const NotFound = lazyRetry(() => import("./pages/NotFound"));

function PageLoader() {
  return (
    <div className="min-h-screen p-6 space-y-3">
      <Skeleton className="h-10 w-1/2" />
      <Skeleton className="h-32 w-full" />
      <Skeleton className="h-32 w-full" />
    </div>
  );
}

// "/" on goodlifesocial.*: signed-out → eager landing, signed-in → feed.
//
// Perf: to avoid a blank/landing flash for returning signed-in users while
// Supabase rehydrates the session (~200–600ms on cold load), we peek at the
// cached auth token in localStorage synchronously. If a token exists we
// redirect to /goodlife immediately — the /goodlife route's Suspense
// fallback (PageLoader) is a much better bridge than a blank screen or the
// marketing landing.
function hasCachedGoodlifeSession(): boolean {
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key && key.startsWith("sb-") && key.endsWith("-auth-token")) {
        const raw = localStorage.getItem(key);
        if (raw && raw.length > 20) return true;
      }
    }
  } catch { /* private mode / disabled storage */ }
  return false;
}

function GoodlifeRoot() {
  const { user, loading } = useAuth();
  const location = useLocation();
  if (loading) {
    if (hasCachedGoodlifeSession()) {
      return <Navigate to={`/goodlife${location.search}${location.hash}`} replace />;
    }
    return <div className="min-h-screen bg-background" aria-hidden />;
  }
  if (user) {
    return <Navigate to={`/goodlife${location.search}${location.hash}`} replace />;
  }
  return <GoodlifeLanding />;
}

const queryClient = new QueryClient();

// Prefetch the default "Everyone" feed in parallel with React mount + auth
// rehydration. We read the cached Supabase user id synchronously from
// localStorage so signed-in visitors' feed request warms the react-query
// cache under the exact same key the hook will use once user resolves.
function readCachedUserId(): string | null {
  try {
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (!key || !key.startsWith("sb-") || !key.endsWith("-auth-token")) continue;
      const raw = localStorage.getItem(key);
      if (!raw) continue;
      const parsed = JSON.parse(raw);
      const id = parsed?.user?.id ?? parsed?.currentSession?.user?.id;
      if (typeof id === "string" && id.length > 0) return id;
    }
  } catch { /* ignore */ }
  return null;
}

if (typeof window !== "undefined") {
  const cachedUserId = readCachedUserId();
  // Fire-and-forget; failures are swallowed so a slow/offline network never
  // blocks or breaks the initial render — the hook will retry on mount.
  import("@/hooks/goodlife/useGoodlifeFeed")
    .then(({ fetchPublicGoodlifeFeed }) =>
      fetchPublicGoodlifeFeed({ userId: cachedUserId, limit: 50 })
        .then((data) => {
          // Warm both the anon key (used before auth resolves) and, if we
          // know the user, the signed-in key with an empty hidden-set.
          queryClient.setQueryData(["goodlife-feed", "public", undefined, ""], data);
          if (cachedUserId) {
            queryClient.setQueryData(["goodlife-feed", "public", cachedUserId, ""], data);
          }
        })
        .catch(() => {}),
    )
    .catch(() => {});
}

const GoodlifeApp = () => (
  <ErrorBoundary>
    <QueryClientProvider client={queryClient}>
      <LocaleProvider>
        <TenantProvider>
          <CustomerViewProvider>
            <CartProvider>
              <TooltipProvider>
                <Toaster />
                <Sonner />

                <BrowserRouter>
                  <Suspense fallback={<PageLoader />}>
                    <Routes>
                      {/* Public */}
                      <Route path="/" element={<GoodlifeRoot />} />
                      <Route path="/auth" element={<Navigate to="/goodlife/auth" replace />} />
                      <Route path="/goodlife/auth" element={<GoodlifeAuth />} />
                      <Route path="/goodlife/signup" element={<GoodlifeSignup />} />
                      <Route path="/goodlife" element={<GoodlifeLayoutRoute><GoodlifeHome /></GoodlifeLayoutRoute>} />
                      <Route path="/reset-password" element={<ResetPassword />} />
                      <Route path="/set-password" element={<SetPassword />} />
                      <Route path="/policies/cookies" element={<CookiePolicy />} />
                      <Route path="/policies/:policyKey" element={<PlatformPolicyPage />} />

                      {/* Authed Goodlife shell — RequireAuth bounces anon users to /goodlife/auth */}
                      <Route element={<GoodlifeRequireAuth />}>
                        <Route element={<GoodlifeLayoutRoute />}>
                         <Route path="/goodlife/claim" element={<GoodlifeHandleClaim />} />
                         <Route path="/goodlife/welcome" element={<GoodlifeWelcome />} />
                          <Route path="/goodlife/account/sign-in-methods" element={<GoodlifeSignInMethods />} />
                          <Route path="/account/sign-in-methods" element={<GoodlifeSignInMethods />} />
                          <Route path="/goodlife/connected-accounts" element={<GoodlifeConnectedAccounts />} />
                          <Route path="/goodlife/account/connected-accounts" element={<GoodlifeConnectedAccounts />} />
                          <Route path="/goodlife/messages" element={<GoodlifeMessages />} />
                          <Route path="/goodlife/messages/mail/:email" element={<GoodlifeMessages />} />
                          <Route path="/goodlife/messages/:handle" element={<GoodlifeMessages />} />
                          <Route path="/goodlife/settings" element={<GoodlifeTenantSettings />} />
                          <Route path="/goodlife/business/managers" element={<GoodlifeBusinessManagers />} />
                          <Route path="/goodlife/business/settings" element={<GoodlifeBusinessProfileSettings />} />
                          <Route path="/goodlife/moderation" element={<GoodlifeModerationConsole />} />
                          <Route path="/goodlife/profile/edit" element={<GoodlifeProfileEdit />} />
                          <Route path="/goodlife/my-feed" element={<Navigate to="/goodlife" replace />} />
                          <Route path="/goodlife/photos" element={<GoodlifePhotos />} />
                          <Route path="/goodlife/friends" element={<GoodlifeFriends />} />
                          <Route path="/goodlife/invite" element={<GoodlifeInvite />} />
                          <Route path="/goodlife/compose" element={<GoodlifeCompose />} />
                          <Route path="/goodlife/fred" element={<GoodlifeFred />} />
                          <Route path="/goodlife/explore" element={<GoodlifeExplore />} />
                          <Route path="/goodlife/news" element={<GoodlifeNews />} />


                          <Route path="/goodlife/notifications" element={<GoodlifeNotifications />} />
                          <Route path="/goodlife/account/offboarding" element={<GoodlifeOffboarding />} />
                          <Route path="/goodlife/memories" element={<GoodlifeMemories />} />
                          <Route path="/goodlife/cv" element={<GoodlifeCV />} />
                          <Route path="/goodlife/jobs/alerts" element={<GoodlifeJobAlerts />} />
                          <Route path="/goodlife/jobs/applications" element={<GoodlifeJobApplications />} />
                          <Route path="/goodlife/jobs/manage" element={<GoodlifeJobsManage />} />
                          <Route path="/goodlife/jobs/analytics" element={<GoodlifeJobsAnalytics />} />
                          <Route path="/goodlife/talent" element={<GoodlifeTalentBoard />} />
                          <Route path="/goodlife/referrals" element={<GoodlifeMyReferrals />} />
                          <Route path="/goodlife/jobs/offers/:offerId" element={<GoodlifeJobOffer />} />
                          <Route path="/goodlife/jobs/:jobId/pipeline" element={<GoodlifeJobPipeline />} />
                          <Route path="/goodlife/jobs/:jobId/match" element={<GoodlifeJobMatch />} />
                          <Route path="/goodlife/jobs/:jobId/health" element={<GoodlifeJobHealth />} />
                          <Route path="/goodlife/applications/:applicationId/review" element={<GoodlifeApplicationReview />} />

                          {/* Customer portal — logged-in only */}
                          <Route path="/goodlife/portal" element={<GoodlifePortalDashboard />} />
                          <Route path="/goodlife/shop/orders" element={<GoodlifePortalMyOrders />} />
                          <Route path="/goodlife/bookings/my-bookings" element={<GoodlifePortalMyBookings />} />
                          <Route path="/goodlife/account" element={<GoodlifePortalAccount />} />
                          <Route path="/goodlife/my-feedback" element={<GoodlifePortalMyFeedback />} />
                          <Route path="/goodlife/purchases" element={<GoodlifePortalMyTickets />} />
                          <Route path="/goodlife/providers" element={<GoodlifeProviders />} />
                        </Route>
                      </Route>

                      {/* Public-browseable shell (may be viewed signed-out) */}
                      <Route element={<GoodlifeLayoutRoute />}>
                        <Route path="/goodlife/groups" element={<GoodlifeGroups />} />
                        <Route path="/goodlife/groups/:slug" element={<GoodlifeGroupPage />} />
                        <Route path="/goodlife/events" element={<GoodlifeEvents />} />
                        <Route path="/goodlife/videos" element={<GoodlifeVideos />} />
                        <Route path="/goodlife/snippets" element={<GoodlifeSnippets />} />
                        <Route path="/goodlife/blogs" element={<GoodlifeBlogs />} />
                        <Route path="/goodlife/blogs/:postId" element={<GoodlifeBlogPost />} />
                        <Route path="/goodlife/marketplace" element={<GoodlifeMarketplace />} />
                        <Route path="/goodlife/search" element={<GoodlifeSearch />} />
                        <Route path="/goodlife/meet" element={<GoodlifeMeet />} />
                        <Route path="/goodlife/jobs" element={<GoodlifeJobs />} />
                        <Route path="/goodlife/jobs/:jobId" element={<GoodlifeJobDetail />} />
                        <Route path="/goodlife/shop" element={<GoodlifePortalShop />} />
                        <Route path="/goodlife/bookings" element={<GoodlifePortalBookings />} />
                        <Route path="/goodlife/network" element={<GoodlifePortalNetwork />} />
                        <Route path="/goodlife/t/:slug" element={<GoodlifeTenantPage />} />
                        <Route path="/goodlife/transparency" element={<GoodlifeTransparency />} />
                        <Route path="/goodlife/:handle" element={<GoodlifeHandleResolver />} />
                      </Route>

                      {/* Bare /<handle> on goodlifesocial.* */}
                      <Route
                        path="/:handle"
                        element={
                          <GoodlifeLayoutRoute>
                            <GoodlifeHandleResolver />
                          </GoodlifeLayoutRoute>
                        }
                      />

                      <Route path="*" element={<NotFound />} />
                    </Routes>
                  </Suspense>
                </BrowserRouter>
              </TooltipProvider>
            </CartProvider>
          </CustomerViewProvider>
        </TenantProvider>
      </LocaleProvider>
    </QueryClientProvider>
  </ErrorBoundary>
);

export default GoodlifeApp;
