"use client";

import { createContext, useContext, useMemo, useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { getAuthTokenFromCookie } from "@/utils/getAuthToken";

type User = { role: string };
type Ctx = { user: User; token?: string; isAuthorized: boolean };

const UserAuthContext = createContext<Ctx>({ user: { role: "ADMIN" }, isAuthorized: false });

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

    // ⚠️ Lea sólo strings estables para deps
    const tParam = searchParams?.get("t") ?? null;

    const [token, setToken] = useState<string | undefined>(undefined);
    const [authorized, setAuthorized] = useState(false);
    const [hydrated, setHydrated] = useState(false);

    useEffect(() => {
        const raw = getAuthTokenFromCookie("authToken");
        let tok: string | undefined = undefined;
        if (raw) {
            try {
                const parsed = JSON.parse(raw);
                tok = parsed?.token ?? undefined;
            } catch {
                tok = raw || undefined;
            }
        }
        setToken(tok);
        setAuthorized(!!tok);
        setHydrated(true);
        if (!tok && pathname !== "/unauthorized") router.replace("/unauthorized");
    }, [pathname, router]);

    console.log("UserAuthContext value:", token);

    const value = useMemo<Ctx>(() => ({ user: { role: "ADMIN" }, token, isAuthorized: authorized }), [token, authorized]);

    return (
        <UserAuthContext.Provider value={value}>
            {hydrated ? children : null}
        </UserAuthContext.Provider>
    );
}

export function useUserAuth() {
    return useContext(UserAuthContext);
}
