"use client";

import { trackVisit } from "@/libs/axios/modules/analytics";
import Cookies from "js-cookie";
import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";

const VISITOR_ID_COOKIE = "visitor_id";

function generateId(): string {
    if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
        return crypto.randomUUID();
    }

    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0;
        const v = c === "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}

function getOrCreateVisitorId(): string {
    let id = Cookies.get(VISITOR_ID_COOKIE);
    if (!id) {
        id = generateId();
        Cookies.set(VISITOR_ID_COOKIE, id, {
            expires: 365,
            path: "/",
            sameSite: "lax",
        });
    }
    return id;
}

export default function VisitTracker() {
    const pathname = usePathname();
    const searchParams = useSearchParams();

    useEffect(() => {
        const visitor_id = getOrCreateVisitorId();
        const path = searchParams.toString()
            ? `${pathname}?${searchParams.toString()}`
            : pathname;

        trackVisit({
            path,
            visitor_id,
            referrer: document.referrer || undefined,
        }).catch(() => {
            // tracking must never disrupt the actual page
        });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pathname, searchParams]);

    return null;
}
