export function getFrontendLogContext() {
    const nav = typeof navigator !== "undefined" ? navigator : null;
    const win = typeof window !== "undefined" ? window : null;

    return {
        timestamp: new Date().toISOString(),
        user: {
            user_id: localStorage.getItem("user_id") || null,
            session_id: localStorage.getItem("session_id") || null,
            device_id: localStorage.getItem("device_id") || generateDeviceId(),
        },

        client: {
            browser: nav?.userAgent || null,
            os: getOS(),
            device_type: getDeviceType(),
            screen_size: win
                ? `${win.screen.width}x${win.screen.height}`
                : null,
        },

        network: {
            online: nav?.onLine ?? true,
            type: (nav as any)?.connection?.effectiveType || null,
        },

        environment: {
            app_version: process.env.NEXT_PUBLIC_APP_VERSION || null,
            url: win?.location?.href || null,
            path: win?.location?.pathname || null,
        },
    };
}

function generateDeviceId() {
    const id = crypto.randomUUID();
    localStorage.setItem("device_id", id);
    return id;
}

function getOS() {
    const userAgent = navigator.userAgent.toLowerCase();

    if (userAgent.includes("windows")) return "Windows";
    if (userAgent.includes("mac")) return "macOS";
    if (userAgent.includes("linux")) return "Linux";
    if (userAgent.includes("iphone")) return "iOS";
    if (userAgent.includes("android")) return "Android";

    return "Unknown";
}
function getDeviceType() {
    const width = window.innerWidth;

    if (width <= 480) return "mobile";
    if (width <= 1024) return "tablet";
    return "desktop";
}
