function ampRecordVisit(what, id, mls, cid) {
    // If ?preview=1 then abort
    const urlParams = new URLSearchParams(window.location.search);
    const isPreview = urlParams.get('preview');
    if (isPreview == 1) {
        return false;
    }

    if (window.location.hostname == 'localhost') {
        return false;
    }

    const refer = document.referrer.split('/')[2];
    if (refer == 'www.amplistings.com') {
        return false;
    }

    // Get IP from ipify
    const ipresponse = fetch('https://api.ipify.org?format=json&callback=')
        .then(res => res.json())
        .then(ipdata => {
            ampSendVisitRequest(what, id, mls, cid, ipdata.ip);
        })
        .catch((error) => {
            console.log('Error:', error);
            ampSendVisitRequest(what, id, mls, cid, '');
        });
}

function ampSendVisitRequest(what, id, mls, cid, ip) {
    let statdata = {};
    statdata.event = what;
    statdata.slw_prop_id = id;
    statdata.slw_prop_mls = mls;
    statdata.slw_cid = cid;
    
    // Get window
    statdata.browser_width = window.outerWidth;
    statdata.browser_height = window.outerHeight;
    
    // Get navigator
    statdata.browser_platform = navigator.platform;
    statdata.browser_useragent = navigator.userAgent;
    statdata.browser_vendor = navigator.vendor;
    statdata.language = navigator.language;
    if (navigator.connection != undefined && navigator.connection.effectiveType != undefined) {
        statdata.connection = navigator.connection.effectiveType;
    } else {
        statdata.connection = '';
    }

    // Get timezone
    statdata.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

    // Domain
    statdata.domain = window.location.hostname;
    statdata.page = window.location.pathname;

    statdata.ip = ip;
    statdata.refer = document.referrer.split('/')[2];

    const response = fetch('https://app.amplistings.com/api/visit', {
        method: 'post',
        body: JSON.stringify(statdata),
        headers: { 'Content-Type': 'application/json' }
    })
    .then(res => res.json())
    .then(json => {
        //console.log("RECORDED STAT");
        console.log(json);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}
