"use client";

import { useEffect } from "react";
import dynamic from "next/dynamic";
import { usePathname } from "next/navigation";
import { initUpdateSystem, checkForUpdate, checkBuildIntegrity } from "@/lib/update";
import { AuthProvider } from "@/lib/provider/auth.provider";
import { bootPlatform, platformReady } from "@/lib/platform/boot";
import { captureReferral } from "@/lib/services/referral.service";
import RouteTracker from "@/components/common/route-tracker.component";

// How long to wait after a route renders before inspecting which chunks it actually loaded.
const INTEGRITY_CHECK_DELAY_MS = 1200;

// App-only UI (deep links, back button, update prompt); the literal check keeps it out of the website.
const NativeShell =
    process.env.NEXT_PUBLIC_APP_TARGET === "native"
        ? dynamic(() => import("@/lib/platform/native/native-shell"), { ssr: false })
        : null;

export function ClientProviders({ children }: { children: React.ReactNode }) {
    const pathname = usePathname();

    // Apps: read the build info and native storage before AuthProvider.
    useEffect(() => bootPlatform(), []);

    // A coach's invite (?ref=) is kept until login (technical-plan 4.7).
    useEffect(() => {
        const search = window.location.search;
        const path = window.location.pathname;
        platformReady().then(() => captureReferral(search, path));
    }, [pathname]);

    useEffect(() => initUpdateSystem(), []);

    useEffect(() => {
        checkForUpdate();
    }, [pathname]);

    useEffect(() => {
        const timer = setTimeout(() => { checkBuildIntegrity(); }, INTEGRITY_CHECK_DELAY_MS);
        return () => clearTimeout(timer);
    }, [pathname]);

    return (
        <AuthProvider>
            <RouteTracker />
            {children}
            {NativeShell && <NativeShell />}
        </AuthProvider>
    );
}
