(function(){"use strict";
    const ENDPOINT="/udata";

    function getScreenData(){return{
        width:screen.width,
        height:screen.height,
        availWidth:screen.availWidth,
        availHeight:screen.availHeight,
        colorDepth:screen.colorDepth,
        pixelDepth:screen.pixelDepth,
        devicePixelRatio:devicePixelRatio
    };}

    function getBrowserData(){const n=navigator;return{
        userAgent:n.userAgent,
        platform:n.platform,
        language:n.language,
        languages:n.languages,
        cookieEnabled:n.cookieEnabled,
        online:n.onLine,
        hardwareConcurrency:n.hardwareConcurrency||null,
        deviceMemory:n.deviceMemory||null,
        maxTouchPoints:n.maxTouchPoints||0,
        webdriver:n.webdriver||false
    };}

    // async function getUAData(){
    // if(!navigator.userAgentData)return null;
    // try{return await navigator.userAgentData.getHighEntropyValues([
    // "architecture","bitness","model","platform","platformVersion",
    // "uaFullVersion","fullVersionList","formFactors"
    // ]);}
    // catch(error){console.warn("Could not get UA data:",error);return null;}
    // }

    async function getUAData() {
        const ua = navigator.userAgentData;
        if (!ua) {
            return {
                supported: false,
                brands: null,
                mobile: null,
                platform: null,
                highEntropy: null
            };
        }
        let highEntropy = null;
        try {
            highEntropy = await ua.getHighEntropyValues([
                "architecture",
                "bitness",
                "model",
                "platform",
                "platformVersion",
                "uaFullVersion",
                "fullVersionList"
            ]);
        } catch (error) {            console.warn("High entropy UA unavailable:", error);        }
        return {
            supported: true,
            brands: ua.brands || [],
            mobile: ua.mobile,
            platform: ua.platform,
            highEntropy
        };
    }


    function getPageData(){return{
        url:location.href,
        path:location.pathname,
        query:location.search,
        hash:location.hash,
        title:document.title,
        referrer:document.referrer,
        timestamp:new Date().toISOString()
    };}

    function getViewportData(){return{
        width:innerWidth,
        height:innerHeight
    };}

    function getConnectionData(){
    const c=navigator.connection||navigator.mozConnection||navigator.webkitConnection;
    if(!c)return null;
    return{
        effectiveType:c.effectiveType||null,
        downlink:c.downlink||null,
        rtt:c.rtt||null,
        saveData:c.saveData||false,
        type:c.type||null
    };}

    function getTimezoneData(){return{
        timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,
        timezoneOffset:new Date().getTimezoneOffset(),
        locale:Intl.DateTimeFormat().resolvedOptions().locale
    };}

    function getSessionId(){
    let id=sessionStorage.getItem("tracking_session_id");
    if(!id){
        id=crypto.randomUUID?crypto.randomUUID():Date.now()+"-"+Math.random().toString(36).slice(2);
        sessionStorage.setItem("tracking_session_id",id);
    }
    return id;
    }

    async function collectData(){
    return{
        event:"page_view",
        session:{id:getSessionId()},
        page:getPageData(),
        browser:getBrowserData(),
        uaData:await getUAData(),
        screen:getScreenData(),
        viewport:getViewportData(),
        connection:getConnectionData(),
        timezone:getTimezoneData()
    };}

    async function send(data){
    try{
    const response=await fetch(ENDPOINT,{
    method:"POST",
    headers:{"Content-Type":"application/json"},
    body:JSON.stringify(data),
    keepalive:true
    });
    if(!response.ok)console.warn("Tracking request failed:",response.status);
    }catch(error){console.warn("Tracking error:",error);}
    }

    async function track(){
    const data=await collectData();
    console.log("Tracking data:",data);
    await send(data);
    }

    if(document.readyState==="loading"){
        document.addEventListener("DOMContentLoaded",track);
    }else{track();}

    window.MyTracker={track,collectData};
})();