function isSocialShopping () {
    return window.location.href.indexOf('lets-go-shopping') > -1;
}

function getRoomCode () {
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    return params.get('lets-go-shopping') ?? null;
}


if (isSocialShopping()) {
    insertAuglioTryOnWidget(null, null, false, false, false, true);
}


function isOpenPd() {
    
    const url = new URL(window.location.href);
    
    const openpd = url.searchParams.get('openpd');
    
    return openpd === '1';
}


function isOpenWig() {
    
    const url = new URL(window.location.href);
    
    const openwig = url.searchParams.get('openwig');
    
    return openwig === '1';
}




function isOpenVto() {
    
    const url = new URL(window.location.href);
        
    const openvto = url.searchParams.get('openvto')
        
    return openvto === '1';
}


function isAuglioDemoStore() {
    
    const url = new URL(window.location.href);
    
    const isDemoMode = url.searchParams.get('auglioDemoStore');
    
    return isDemoMode === 'fashion' || isDemoMode === 'makeup';
}


function isShoppingSession() {
    
    const url = new URL(window.location.href);
    
    const shoppingSession = url.searchParams.get('shopping-session');
    
    return shoppingSession !== null;
}


function isOpenVtoProduct() {
    
    const url = new URL(window.location.href);
    
    const item_id = url.searchParams.get('openvtoproduct');
    
    return item_id;
}


(function() {
    if(isOpenPd()) {
        insertAuglioTryOnWidget(null, null, null, false, 'pd')
    } else if(isOpenWig()) {
        insertAuglioTryOnWidget(null, null, null, false, 'wig')
    } else if(isOpenVto() || isShoppingSession() || isAuglioDemoStore()) {
        insertAuglioTryOnWidget()
    } else if(isOpenVtoProduct()) {
        
        fetch("https://tryon.auglio.com/api/check-item-ids", {
            method: "POST",
            headers: {
                "Content-Type" : "application/json",
            },
            body: JSON.stringify({
                item_ids: [isOpenVtoProduct()],
                partner_id: 9847,
                ignore_published: 0,
            }),
        })
        .then((res) => res.json())
        .then((ids) => {
            createHiddenAuglioTryOnBtns(ids)
            
            if(ids.length > 0) {
                insertAuglioTryOnWidget(ids[0].product_id, ids[0].group_id, false)
            } else {
                
                insertAuglioTryOnWidget()
            }
        })
    }
})();


function isAuglioStandaloneMirror() {
    return getAuglioStandaloneMirror() ? true : false
}


function getAuglioStandaloneMirror() {
    return document.getElementById('auglio-standalone-mirror')
}


function initializeAuglioStandaloneMirror() {
    if(isAuglioStandaloneMirror()) {
        let item_id = getAuglioStandaloneMirror().getAttribute('data-item_id');
        console.log("item_id", item_id)
        if(item_id) {
            
            fetch("https://tryon.auglio.com/api/check-item-ids", {
                method: "POST",
                headers: {
                    "Content-Type" : "application/json",
                },
                body: JSON.stringify({
                    item_ids: [item_id],
                    partner_id: 9847,
                    ignore_published: 0,
                }),
            })
            .then((res) => res.json())
            .then((ids) => {
                
                if(ids.length > 0) {
                    insertAuglioTryOnWidget(ids[0].product_id, ids[0].group_id, true)
                } else {
                    insertAuglioTryOnWidget(null, null, true)
                }
            })
        } else {
            insertAuglioTryOnWidget(null, null, true)
        }
    }
}

// Initialize the standalone mirror when the script loads
initializeAuglioStandaloneMirror();


var virtooalRefreshBtnsEvent = new Event('virtooalRefreshBtnsReady', {});
document.dispatchEvent(virtooalRefreshBtnsEvent);

let virtooalMirrorState;
let isCrossmirrorLoaded = true;


function virtooalRefreshBtns(reverse, callback = () => {}, display_method = "block") {
    let btns = Array.from(document.querySelectorAll('.virtooal-tryon-btn, .auglio-tryon-btn'))
    if (reverse) {
        btns.forEach(btn => {
            btn.style.display = "none"
            if(btn.dataset.virtooal_id) {
                btn.dataset.item_id = btn.dataset.virtooal_id;
            }
            btn.classList.add('auglio-tryon-btn');
        })
    } else {
        btns.forEach(btn => {
            if(btn.dataset.virtooal_id) {
                btn.dataset.item_id = btn.dataset.virtooal_id;
            }
            btn.classList.add('auglio-tryon-btn');
        })
    }
    auglioRefreshBtns();

    if(typeof callback !== "function") {
        callback = () => {}
    }
    callback();
}

    virtooalRefreshBtns()


function auglioRefreshGroupBtns(callback = () => {}, context = document) {
    
    let group_item_ids = getAuglioBtns(context, true);
    
    if(group_item_ids.length < 1) {
        return
    }
    
    fetch("https://tryon.auglio.com/api/check-group-item-ids", {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
        },
        body: JSON.stringify({
            partner_id: 9847,
            group_item_ids: group_item_ids,
        }),
    })
    .then((res) => res.json())
    .then((ids) => {
        
        refreshExistingAuglioTryOnBtns(ids, undefined, context, true)
        
        document.dispatchEvent(new CustomEvent('auglioButtonsRefreshed'))
        
        if(typeof callback !== "function") {
            callback = () => {}
        }
        callback();
    })
}


function auglioRefreshBtns(callback = () => {}, context = document) {
    
    let item_ids = getAuglioBtns(context);
    
    if(item_ids.length < 1) {
        
                refreshHeadMeasurementBtns(context)
        return
    }
    
    fetch("https://tryon.auglio.com/api/check-item-ids", {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
        },
        body: JSON.stringify({
            item_ids: item_ids,
            partner_id: 9847,
            ignore_published: 0,
        }),
    })
    .then((res) => res.json())
    .then((ids) => {
        
        if(ids.length > 0) {
            insertAuglioFloatingIcon()
        }
        
        refreshExistingAuglioTryOnBtns(ids, undefined, context)
        
        document.dispatchEvent(new CustomEvent('auglioButtonsRefreshed'))
        
        if(typeof callback !== "function") {
            callback = () => {}
        }
        callback();
        
                refreshHeadMeasurementBtns(context)
    })
}


function getRelatedProductBtns(product_id, category_id, group_id) {
    
    fetch("https://tryon.auglio.com/api/related-products", {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
        },
        body: JSON.stringify({
            product_id: product_id,
            category_id: category_id,
            partner_id: 9847,
            group_id: group_id,
        }),
    })
    .then((res) => res.json())
    .then((ids) => {
        
        createHiddenAuglioTryOnBtns(ids)
    })
}


function getUrlTryOnBtn() {
    
    fetch("https://tryon.auglio.com/api/url-tryon-btn", {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
        },
        body: JSON.stringify({
            partner_id: 9847,
            url: encodeURIComponent(window.location.href),
        }),
    })
    .then((res) => res.json())
    .then((id) => {
        
        createHiddenAuglioTryOnBtns([id])
        insertAuglioFloatingIcon()
    })
    .catch((error) => {
        
        console.log('No url product');
    });
}


function createHiddenAuglioTryOnBtns(ids) {
    ids.forEach(item => {
        let btn = document.createElement('button');
        btn.classList.add('auglio-tryon-btn', 'auglio-tryon-btn-hidden');
        btn.style.display = 'none';
        btn.dataset.item_id = item.item_id;
        btn.dataset.product_id = item.product_id;
        btn.dataset.category_id = item.category_id;
        btn.dataset.group_id = item.group_id;
        btn.dataset.full_3d = item.full_3d;
        document.body.appendChild(btn);
    })
}


function getAuglioBtns(context = document, is_group = false) {
    
    let btns = Array.from(context.querySelectorAll('.auglio-tryon-btn'))
    
    if(btns.length < 1) {
        return []
    }
    if(is_group) {
        
        return btns.map(btn => btn.dataset.group_item_id)
    } else {
        
        return btns.map(btn => btn.dataset.item_id)
    }
}


function refreshExistingAuglioTryOnBtns(ids, displayMethod = "flex", context = document, is_group = false) {
    
    context.querySelectorAll('.auglio-tryon-btn').forEach(btn => {
        btn.removeAttribute('data-product_id');
        btn.removeAttribute('data-group_id');
        btn.removeAttribute('data-full_3d');
        btn.style.display = 'none';
    })
    ids.forEach(item => {
        let btns = [];
        
        if(is_group) {
            btns = Array.from(context.querySelectorAll(`.auglio-tryon-btn[data-group_item_id="${item.group_item_id}"]`))
        } else {
            btns = Array.from(context.querySelectorAll(`.auglio-tryon-btn[data-item_id="${item.item_id}"]`))
        }
        
        btns?.forEach(btn => {
            btn.style.display = displayMethod;
            btn.dataset.product_id = item.product_id;
            btn.dataset.category_id = item.category_id;
            btn.dataset.group_id = item.group_id;
            btn.dataset.full_3d = item.full_3d;
        })
    })
}


function refreshHeadMeasurementBtns(context = document) {
    let btns = Array.from(context.querySelectorAll('.auglio-head-btn'))
    if(btns.length < 1) {
        return
    }

    btns.forEach(btn => {
        btn.removeAttribute('data-product_id');
        btn.setAttribute('data-item-id-checked', 'false')
        btn.setAttribute('data-config-exist', 'false')
    })

    const itemIds = btns
        .map(btn => btn.getAttribute('data-item_id'))
        .filter(id => typeof id === 'string' && id.length > 0)

    if(itemIds.length < 1) {
        btns.forEach(btn => {
            btn.setAttribute('data-item-id-checked', 'true')
            btn.setAttribute('data-config-exist', 'false')
        })
        return
    }

    fetch("https://tryon.auglio.com/api/head-measurement-check-item-ids", {
        method: "POST",
        headers: {
            "Content-Type" : "application/json",
        },
        body: JSON.stringify({
            item_ids: itemIds,
            partner_id: 9847,
            ignore_published: 0,
        }),
    })
    .then((res) => res.json())
    .then((ids) => {
        const map = {}
        ids?.forEach(item => {
            if(item?.item_id && item?.product_id) {
                map[item.item_id] = item.product_id
            }
        })
        btns.forEach(btn => {
            const btnItemId = btn.getAttribute('data-item_id')
            const mappedProductId = btnItemId ? map[btnItemId] : null
            if(mappedProductId) {
                btn.setAttribute('data-product_id', mappedProductId)
                btn.setAttribute('data-config-exist', 'true')
            } else {
                btn.setAttribute('data-config-exist', 'false')
            }
            btn.setAttribute('data-item-id-checked', 'true')
        })
    })
    .catch(() => {
        // leave dataset.itemIdChecked as false to signal retry needed
    })
}


function insertAuglioFloatingIcon() {
    
        
    if(document.getElementById('auglio-bubble')) {
        return
    }

    let basicElement = document.createElement('div')
    basicElement.id = 'auglio-bubble'
    basicElement.classList.add('auglio-floating-icon')

            document.body.appendChild(basicElement)
    document.getElementById('auglio-bubble').innerHTML = `<div id="auglio-bubble-logo" data-cy="auglio-bubble">
    <div id="auglio-bubble-text">
                    TRY ON
            </div>
        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 49.81 43.46" style="width:35px; height:35px;">
        <defs>
            <style>
                .cls-1{
                    fill:url(#linear-gradient);
                }
                .cls-3{
                    fill:url(#linear-gradient-2);
                }
            </style>
            <linearGradient id="linear-gradient" x1="31.28" y1="15.55" x2="51.69" y2="11.58" gradientTransform="translate(0 45.36) scale(1 -1)" gradientUnits="userSpaceOnUse">
                <stop offset=".3" stop-color="#000" stop-opacity=".47" />
                <stop offset=".35" stop-color="#000" stop-opacity=".41" />
                <stop offset=".49" stop-color="#000" stop-opacity=".26" />
                <stop offset=".63" stop-color="#000" stop-opacity=".15" />
                <stop offset=".77" stop-color="#000" stop-opacity=".07" />
                <stop offset=".89" stop-color="#000" stop-opacity=".02" />
                <stop offset="1" stop-color="#000" stop-opacity="0" />
            </linearGradient>
            <linearGradient id="linear-gradient-2" x1="48.76" y1="27.02" x2="22.57" y2="37.06" gradientTransform="translate(0 45.36) scale(1 -1)" gradientUnits="userSpaceOnUse">
                <stop offset=".38" stop-color="#000" stop-opacity=".5" />
                <stop offset=".46" stop-color="#000" stop-opacity=".4" />
                <stop offset=".72" stop-color="#000" stop-opacity=".18" />
                <stop offset=".91" stop-color="#000" stop-opacity=".05" />
                <stop offset="1" stop-color="#000" stop-opacity="0" />
            </linearGradient>
        </defs>
        <g id="logo">
            <path id="spodna_noha" d="M49.8,43.46c-6.45,0-10.33-2.79-12.38-5.18-4.66-5.42-4.57-15.24-4.57-16.54h10.6c0,1.54-.23,7.13,1.93,9.54,.61,.68,1.73,1.58,4.43,1.58v10.6h0Z" />
            <path id="spodny_tien" class="cls-1" d="M49.8,43.46c-6.45,0-10.33-2.79-12.38-5.18-4.66-5.42-4.57-15.24-4.57-16.54h10.6c0,1.54-.23,7.13,1.93,9.54,.61,.68,1.73,1.58,4.43,1.58v10.6h0Z" />
            <path id="lavy_obluk" d="M21.72,43.46C9.74,43.46,0,33.71,0,21.74S9.75,.02,21.72,.02s21.72,9.74,21.72,21.72-9.74,21.72-21.72,21.72Zm0-32.84c-6.13,0-11.12,4.99-11.12,11.12s4.99,11.12,11.12,11.12,11.12-4.99,11.12-11.12-4.99-11.12-11.12-11.12Z" />
            <path id="vrchny_tien" class="cls-3" d="M32.84,21.73h10.6C43.44,9.75,33.7,.02,21.72,.02V10.62c6.13,0,11.12,4.98,11.12,11.11Z" />
            <path id="prava_noha" d="M32.84,0l-.02,22.19c-.24,5.92-5.09,10.67-11.09,10.67v10.6c11.82,0,21.47-9.51,21.72-21.27V0h-10.61Z" />
        </g>
            </svg>
</div>
`

    
    }


function isAuglioTouchDevice() {
    return ('ontouchstart' in window) && window.matchMedia('(pointer: coarse)').matches && !window.matchMedia('(pointer: fine)').matches;
}


function isAuglioDemo() {
    return window.location.href.includes("woo.virtooal.com") || window.location.href.includes("woo.auglio.com")
}


function isAuglioPreview() {
    return window.location.href.indexOf('preview=1') > -1
}


function getAuglioSupportedLangs() {
    return ["sk","ru","pt","pl","lv","hu","fr","es","en","de","cz","it","ar","ro","hr","no","sv","da","nl","vi","tr","th","ja"]}


function insertAuglioTryOnWidget(
    productId = null,
    groupId = null,
    isStandalone = false,
    initialNoGroup = false,
    isMode = false,
    isAssistant = "",
    isOpenedThroughFloatingIcon = false,
    is360View = false,
    isHideUI = false,
    isPhotochromic = false,
    photochromicColor = '#000000',
    photochromicAnimation = false,
    photochromicOpacity = 50,
    photochromicStops = null,
    targetElementClass = null
    ) {
    
    if(document.body.classList.contains('auglio-widget-inserted')) {
        return
    }

    let targetContainer = null
    if (targetElementClass && typeof targetElementClass === 'string') {
        const trimmedTarget = targetElementClass.trim()
        if (trimmedTarget.length > 0) {
            let selector = trimmedTarget
            const simpleClassPattern = /^[A-Za-z0-9_-]+(\s+[A-Za-z0-9_-]+)*$/
            if (simpleClassPattern.test(trimmedTarget)) {
                const classParts = trimmedTarget.split(/\s+/).filter(Boolean).map(part => {
                    if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
                        return CSS.escape(part)
                    }
                    return part.replace(/([^A-Za-z0-9_-])/g, '\\$1')
                })
                selector = '.' + classParts.join('.')
            } else if (!/^[.#\[]/.test(trimmedTarget)) {
                selector = '.' + trimmedTarget
            }
            try {
                targetContainer = document.querySelector(selector)
            } catch (error) {
                console.warn('Auglio VTO target selector error:', selector, error)
            }
        }
    }

    const effectiveStandalone = Boolean(isStandalone || targetContainer)
    const autoStartStandalone = Boolean(targetContainer)
    
    if (typeof gtag === 'function' && 0 === 1) {
        gtag('event', 'Auglio_VTO_started', {
            event_category: 'VTO_started',
            event_label: 'VTO_started',
            value: 1
        });
    }
    
    let widget = document.createElement("div")
    widget.id = "auglio-widget"
    widget.dataset.partner_id = "9847"
    widget.dataset.lang = "en"
    widget.dataset.custom_lang = "1"
    widget.dataset.auglio_hash = "b4ce140125b00eeac7ce7d2fb1fa0357e68896d587bf884e6bab488d34a92067"
    widget.dataset.live_preview = "0"
    widget.innerHTML = `
        <auglio-base
            :product-id="${productId}"
            :group-id="${groupId}"
            :initial-no-group="${initialNoGroup}"
            :touch-device="${isAuglioTouchDevice()}"
            :settings="{&quot;industry&quot;:&quot;eyewear&quot;,&quot;partnerId&quot;:9847,&quot;apiKey&quot;:&quot;551d36d927256ccbaffd6e04e9be3b1c&quot;,&quot;storeUrl&quot;:&quot;https:\/\/filteroptix.com\/&quot;,&quot;platformId&quot;:1,&quot;color1&quot;:&quot;000000&quot;,&quot;color2&quot;:&quot;000000&quot;,&quot;mirrorPaused&quot;:0,&quot;currency&quot;:&quot;$&quot;,&quot;fullscreen&quot;:1,&quot;pdDetection&quot;:2,&quot;cartSync&quot;:1,&quot;side&quot;:&quot;left&quot;,&quot;currencyPosition&quot;:&quot;before&quot;,&quot;logo&quot;:&quot;&quot;,&quot;overrideLenseOpacity&quot;:null,&quot;overrideLenseReflection&quot;:null,&quot;disableDetectionOnClose&quot;:1,&quot;defaultPd&quot;:64,&quot;savePd&quot;:1,&quot;mirrorEnabled&quot;:true,&quot;showWishlist&quot;:1,&quot;showAppliedProducts&quot;:1,&quot;showBuy&quot;:1,&quot;showInformation&quot;:1,&quot;showPrice&quot;:0,&quot;showDescription&quot;:1,&quot;whiteLabel&quot;:0,&quot;gdpr&quot;:1,&quot;syncWishlist&quot;:0,&quot;openProductsInNewTab&quot;:1,&quot;showNonBinary&quot;:1,&quot;floatingIconQuery&quot;:0,&quot;bgSegmentation&quot;:0,&quot;screenRecordingShare&quot;:0,&quot;socialShopping&quot;:0,&quot;assistedShopping&quot;:0,&quot;stockManagement&quot;:1,&quot;atLeastOneProductApplied&quot;:0,&quot;onlyOneCategoryApplied&quot;:0,&quot;orderByName&quot;:0,&quot;googleAnalytics&quot;:0,&quot;show360&quot;:0,&quot;saveWishlist&quot;:1,&quot;imageTryOn&quot;:0,&quot;pdModeIntro&quot;:0,&quot;pdModePrecision&quot;:1,&quot;hideableUI&quot;:0,&quot;showMinimize&quot;:1,&quot;showCategories&quot;:1,&quot;showFilter&quot;:0,&quot;showIntensitySlider&quot;:1,&quot;intensitySliderMap&quot;:0,&quot;showBeforeAfter&quot;:0,&quot;showShare&quot;:1,&quot;showPd&quot;:1,&quot;showStyles&quot;:1,&quot;showZoomInOut&quot;:0,&quot;lensColorCarousel&quot;:0,&quot;aiAssistant&quot;:0,&quot;cameraDeniedUpload&quot;:1,&quot;faceShapeRecommendation&quot;:0,&quot;showHeadMeasurementReview&quot;:0,&quot;customIframeUrl&quot;:null}"
            :is-preview="${isAuglioPreview()}"
            :is-demo="${isAuglioDemo()}"
            :is-presentation="false"
            :is-fullscreen-mode="false"
            :is-kiosk="false"
            is-test=""
            :is-standalone="${effectiveStandalone}"
            :is-assistant="'${isAssistant}'"
            :is-pd-mode="${isMode === 'pd' ? 'true' : 'false' }"
            :is-fsr-mode="${isMode === 'fsr' ? 'true' : 'false' }"
            :is-wrist-mode="${isMode === 'wrist' ? 'true' : 'false' }"
            is-head-measurement-mode="${isMode && isMode !== 'pd' && isMode !== 'wrist' && isMode !== 'fsr' ? isMode.split('_')[0] : '' }"
            head-measurement-result-type="${isMode ? isMode.split('_')[1] ?? 'default' : 'default' }"
            :is-opened-through-floating-icon="${isOpenedThroughFloatingIcon}"
            :ignore-published="false"
            :is-360-view="${is360View}"
            :is-hide-ui="${isHideUI}"
            :is-photochromic="${isPhotochromic}"
            photochromic-color="${photochromicColor}"
            :photochromic-animation="${photochromicAnimation}"
            :photochromic-opacity="${photochromicOpacity}"
            :photochromic-stops='${JSON.stringify(photochromicStops)}'
            :auto-start-standalone="${autoStartStandalone ? 'true' : 'false'}"
        >
                                                <auglio-container>
    <filter-optix-ui></filter-optix-ui>                    
</auglio-container>
                                    </auglio-base>`;

    
    if(targetContainer) {
        targetContainer.appendChild(widget)
    } else if(isStandalone) {
        document.getElementById('auglio-standalone-mirror').appendChild(widget)
    } else {
        
        document.body.appendChild(widget)
    }

    
    let link = document.createElement("link")
    link.rel = "modulepreload"
    link.href = 'https://tryon.auglio.com//build/assets/app.c87b20e8.js'
    document.body.appendChild(link)

    
    let script = document.createElement("script")
    script.src = 'https://tryon.auglio.com//build/assets/app.c87b20e8.js'
    script.type = 'module'
    document.body.appendChild(script)

    
    document.body.classList.add('auglio-widget-inserted')
}


document.addEventListener('click', function (event) {
    
    let path = event.composedPath();
    let targetElement = path[0]; // The actual target element of the click

    
    if(targetElement.matches('.auglio-no-group-btn')) {
        insertAuglioTryOnWidget(null, null, false, true)
        return;
    }

    
    if(targetElement.closest('.auglio-floating-icon')) {
        insertAuglioTryOnWidget(null, null, false, false, false, false, true)
        window.dispatchEvent( new Event('auglio-bubble'))
        return;
    }

    
    if(targetElement.matches('.auglio-assisted-shopping-btn')) {
        let roomCode = targetElement.getAttribute('data-room-code')
        insertAuglioTryOnWidget(null, null, false, false, false, roomCode, false)
        window.dispatchEvent( new Event('auglio-assisted-shopping-btn'))
        return;
    }

    
    if(targetElement.matches('.auglio-pd-btn')) {
        event.preventDefault()
        insertAuglioTryOnWidget(null, null, null, false, 'pd')
        window.dispatchEvent( new CustomEvent('auglio-pd-btn'))
        return;
    }

    
    if(targetElement.matches('.auglio-wig-btn')) {
        event.preventDefault()
        insertAuglioTryOnWidget(null, null, null, false, 'wig')
        window.dispatchEvent( new CustomEvent('auglio-wig-btn'))
        return;
    }

    
    if(targetElement.matches('.auglio-wrist-btn')) {
        event.preventDefault()
        insertAuglioTryOnWidget(null, null, null, false, 'wrist')
        window.dispatchEvent( new CustomEvent('auglio-wrist-btn'))
        return;
    }

    
    if(targetElement.matches('.auglio-head-btn')) {
        event.preventDefault()
        let mode = targetElement?.getAttribute('data-mode') ?? 'headHatEar'
        let headItemId = targetElement?.getAttribute('data-item_id') ?? null
        let headProductId = targetElement?.getAttribute('data-product_id') ?? null
        let normalizedHeadProductId = headProductId && !isNaN(parseInt(headProductId)) ? parseInt(headProductId) : null
        insertAuglioTryOnWidget(normalizedHeadProductId, normalizedHeadProductId, null, false, mode)
        window.dispatchEvent( new CustomEvent('auglio-head-btn', {
            detail: {
                mode: mode,
                itemId: headItemId,
                productId: headProductId
            }
        }))
        return;
    }

    
    if(targetElement.matches('.auglio-fsr-btn')) {
        event.preventDefault()
        insertAuglioTryOnWidget(null, null, null, false, 'fsr')
        window.dispatchEvent( new CustomEvent('auglio-fsr-btn'))
        return;
    }

    
    if(targetElement.closest('.auglio-tryon-btn')) {
        targetElement = targetElement.closest('.auglio-tryon-btn')
    } else if (!targetElement.matches('.auglio-tryon-btn')) {
        return
    }

    
    event.preventDefault()
    
    let productId = targetElement.getAttribute('data-product_id')
    let fullscreen = targetElement.getAttribute('data-fullscreen')
    let categoryId = targetElement.getAttribute('data-category_id')
    let groupId = targetElement.getAttribute('data-group_id')
    let is360View = targetElement.hasAttribute('data-360-view')
    let isHideUI = targetElement.hasAttribute('data-hide-ui')
    let isPhotochromic = targetElement.hasAttribute('data-photochromic')
    let photochromicColorAttr = targetElement.getAttribute('data-photochromic-color') || '#000000'
    let photochromicColor = '#000000'
    let photochromicOpacity = 50
    let photochromicStops = null

    let targetElementClass = targetElement.getAttribute('data-target_element')

    // Parse stops string: "#hex,opacity[,position]|#hex,opacity[,position]|..."
    // Backwards compatible with "#hex,opacity" and "#hex" formats
    if (typeof photochromicColorAttr === 'string' && photochromicColorAttr.includes('|')) {
        // Multiple stops
        photochromicStops = photochromicColorAttr.split('|')
            .map(s => s.trim())
            .filter(Boolean)
            .map((stopStr, idx, arr) => {
                const parts = stopStr.split(',').map(p => p.trim())
                const color = parts[0] || '#000000'
                const opacityPct = parseInt(parts[1] || '50', 10)
                const position = parts.length > 2 ? parseInt(parts[2], 10) : Math.round((idx / Math.max(arr.length - 1, 1)) * 100)
                return {
                    color,
                    opacity: isNaN(opacityPct) ? 0.5 : Math.max(0, Math.min(1, opacityPct / 100)),
                    position: isNaN(position) ? undefined : position,
                }
            })
    } else if (typeof photochromicColorAttr === 'string' && photochromicColorAttr.includes(',')) {
        // Single stop with opacity
        const parts = photochromicColorAttr.split(',')
        photochromicColor = parts[0].trim()
        photochromicOpacity = parseInt(parts[1].trim()) || 50
        photochromicStops = [
            {
                color: photochromicColor,
                opacity: Math.max(0, Math.min(1, (parseInt(parts[1].trim()) || 50) / 100)),
                position: 0,
            },
        ]
    } else {
        // Only color provided
        photochromicColor = photochromicColorAttr
        photochromicStops = [
            {
                color: photochromicColor,
                opacity: 0.5,
                position: 0,
            },
        ]
    }

    let photochromicAnimation = targetElement.hasAttribute('data-photochromic-animation')
    
    insertAuglioTryOnWidget(productId, groupId, false, false, false, null, false, is360View, isHideUI, isPhotochromic, photochromicColor, photochromicAnimation, photochromicOpacity, photochromicStops, targetElementClass)
    
    window.dispatchEvent( new CustomEvent('auglio-tryon-btn', {
        detail: {
            id: productId,
            groupId: groupId,
            fullscreen: fullscreen,
            categoryId: categoryId,
            is360View: is360View,
            isHideUI: isHideUI,
            isPhotochromic: isPhotochromic,
            photochromicColor: photochromicColor,
            photochromicOpacity: photochromicOpacity,
            photochromicAnimation: photochromicAnimation,
            photochromicStops: photochromicStops,
            targetElementClass: targetElementClass,
        }
    }))

}, false)


    function auglioAddToCart(variantId) {
    const quantity = 1;

    const requestUrl = '/cart/add.js';

    const requestData = {
        'id': variantId,
        'quantity': quantity
    };

    fetch(requestUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(requestData)
    })
        .then(response => response.json())
        .then(data => {
            console.log(data);
        })
        .catch(error => {
            console.error(error);
        });
}


function auglioCodeLoadedStats() {
    
    const statsUrl = `//www.virtooal.com/render/stats.php?partnerId=9847&interaction=4&url=${encodeURIComponent(window.location.href)}`;

    
    fetch(statsUrl, { method: 'GET', mode: 'no-cors' });
}
auglioCodeLoadedStats();


function auglioTryonBtnVisibleStats() {
    
    if(document.body.classList.contains('auglio-tryon-btn-visible')) {
        return
    }
    
    const statsUrl = `//www.virtooal.com/render/stats.php?partnerId=9847&interaction=5&url=${encodeURIComponent(window.location.href)}&sessionid=b4ce140125b00eeac7ce7d2fb1fa0357e68896d587bf884e6bab488d34a92067`;
    fetch(statsUrl, { method: 'GET', mode: 'no-cors' });

    
    document.body.classList.add('auglio-tryon-btn-visible')
    
    if (typeof gtag === 'function' && 0 === 1) {
        gtag('event', 'Auglio_VTO_loaded', {
            event_category: 'VTO_loaded',
            event_label: 'VTO_loaded',
            value: 1
        });
    }
}

function isAnyAuglioButtonVisible() {
    
    let buttons = document.querySelectorAll('.auglio-tryon-btn, .auglio-pd-btn, .auglio-wig-btn, .auglio-head-btn');
    
    for (let i = 0; i < buttons.length; i++) {
        let style = window.getComputedStyle(buttons[i]);
        if (style.display !== 'none') {
            return true;
        }
    }
    return false;
}

function isAuglioBubbleVisible() {
    
    let element = document.getElementById('auglio-bubble');
    
    if (element) {
        let style = window.getComputedStyle(element);
        return style.display !== 'none';
    }
    return false;
}


function checkAuglioVisibility(count) {
    
    if(count <= 0 || document.body.classList.contains('auglio-tryon-btn-visible')) return;
    
    setTimeout(() => {
        if(isAuglioBubbleVisible() || isAnyAuglioButtonVisible()) {
            auglioTryonBtnVisibleStats()
        }
        checkAuglioVisibility(count - 1);
    }, 1250);
}

checkAuglioVisibility(5);


function auglioCss() {
    let styleSheet = document.createElement("style")
    styleSheet.textContent = `@import url('https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,400;0,700;1,400;1,700&display=swap');

@font-face {
    font-family: 'AuglioHeading';
    src: url('https://tryon.auglio.com/fonts/headings.otf') format('opentype');
    font-weight: 700;
    font-style: normal;
    font-display: swap;
}
:root {
    --auglio-primary-background: #000000;
    --auglio-primary-rgb-color: 0, 0, 0;
    --auglio-primary-color: #FFFFFF;
    --auglio-blur: 5px;
        --auglio-heading-font: 'AuglioHeading', sans-serif;
            --auglio-text-font: 'Noto Sans', sans-serif;
        --auglio-lens-reflection: url('https://tryon.auglio.com/assets/img/reflection-v2.png');
}

#auglio-container *:empty {
    display: block !important;
}

.auglio-sr-only {
    position: absolute !important;
    width: 1px !important;
    height: 1px !important;
    padding: 0 !important;
    margin: -1px !important;
    overflow: hidden !important;
    clip: rect(0,0,0,0) !important;
    white-space: nowrap !important;
    border: 0 !important;
}

#auglio-container *,
#auglio-container ::after,
#auglio-container ::before {
    box-sizing: content-box;
}

#auglio-backdrop:empty,
#auglio-backdrop-close:empty,
.auglio-minified #auglio-handler:empty,
.auglio-minified #auglio-size-right:empty,
.auglio-minified #auglio-size-left:empty,
.auglio-minified #auglio-size-top:empty,
.auglio-minified #auglio-size-bottom:empty {
    display: block !important;
}

@keyframes auglioFadeIn {
    0% {
        opacity: 0;
        transform: scale(0);
    },
    100% {
        opacity: 100;
        transform: scale(1);
    }
}

#auglio-bubble {
    display: none;
    z-index: 9999999;
    will-change: transform;
    cursor: pointer;
    background: rgba(0,0,0,0);
    border: none;
    transition: transform .225s ease-in-out;
    animation: auglioFadeIn 0.225s ease-in-out;
    position: fixed;
                left: 50px;
            bottom: 40px;
            }

#auglio-bubble:hover {
    transform: scale(1.05);
}

@media screen and (max-width:768px) {
    #auglio-bubble.auglio-mobile {
        display: block;
    }
    #auglio-bubble.auglio-mobile.hide {
        display: none;
    }
}

@media screen and (min-width:768px) {
    #auglio-bubble.auglio-desktop {
        display: block;
    }
    #auglio-bubble.auglio-desktop.hide {
        display: none;
    }
}

#auglio-bubble-logo {
    background-color: var(--auglio-primary-background);
    color: var(--auglio-primary-color);
    width: 50px;
    height: 50px;
    border-radius: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
}

#auglio-bubble-text {
    position: absolute;
    user-select: none;
    top: -35px;
    width:auto;
    font-size: 16px;
    z-index: 10;
    white-space: nowrap;
    background-color: var(--auglio-primary-background);
    color: var(--auglio-primary-color);
    border-radius: 100px;
    display: inline-block;
    padding: 5px 10px 5px 10px;
    line-height: 100%;
}

#auglio-bubble-text:after {
    content: '';
    display: block;
    width:4px;
    z-index: 9;
    height: 4px;
    transform: rotate(45deg);
    position: absolute;
    left: calc(50% - 2px);
    bottom: -4px;
    box-sizing: content-box !important;
    border-bottom: 4px solid var(--auglio-primary-background);
    border-right: 4px solid var(--auglio-primary-background);
}

.auglio-body-no-scroll {
    overflow: hidden;
    position: fixed;
    width: 100%;
    height: 100%;
}

#auglio-wrapper {
    font-family: var(--auglio-text-font);
}

#auglio-wrapper svg {
    fill: currentColor;
    
        width: auto;
    height: auto;
    }

#auglio-wrapper iframe {
    height: 100%;
}

#auglio-wrapper input {
    max-width: unset;
}

.auglio-btn-hidden {
    display: none !important;
}

#auglio-standalone-mirror {
    padding-top: 30px;
    padding-bottom: 20px;
}

#auglio-widget {
    height: 100%;
}

#auglio-widget.auglio-widget-target-hidden {
    pointer-events: none;
    height: 0 !important;
    max-height: 0 !important;
    min-height: 0 !important;
    overflow: hidden;
}
`
    document.head.appendChild(styleSheet)
}
auglioCss();


function auglioSendErrorToBackend(details) {
    fetch('https://tryon.auglio.com/api/report-integration-error', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(details),
    })
    .then(response => response.json())
    .then(data => {
        
    })
    .catch(networkError => {
        
    });
}


function auglioHandleIntegrationError(error, type = null) {
    
    const request = {
        partner_id: 9847,
        url: window.location.href,
        message: error.message,
        stack: error.stack,
        type: type,
    };
    
    auglioSendErrorToBackend(request);
}

    
            try {
            virtooalCrossmirrorScript.addEventListener('load', () => {
    try {
        function insertButtonToProductPage() {
            const container = document.querySelector('.product_form .button__drawer');
            const itemId = document.querySelector('[name="id"]')?.value;
            /*console.log(container, container);*/
            /*console.log(itemId, itemId);*/

            if (!container) {
                auglioHandleIntegrationError(new Error("Integration failed: container not found"), "PDP");
            }

            if (!itemId) {
                auglioHandleIntegrationError(new Error("Integration failed: itemId not found"), "PDP");
            }

            if (container && itemId != null) {
                container.insertAdjacentElement('beforebegin', createTryOnButton(itemId, 'auglio-tryon-btn-product'));
                document.body.appendChild(fakeFloatingIcon(itemId));
                auglioRefreshBtns();
            }
        }

    	function createTryOnButton(id, extraClass){
            const btn = document.createElement('button');
            btn.type = 'button';
            btn.innerText = 'VIRTUAL TRY-ON';
            btn.classList.add('auglio-tryon-btn', extraClass);
            btn.setAttribute('data-item_id', id);
            btn.style.display = 'none';
            return btn;
    	}

    	function fakeFloatingIcon(id) {
    	    const fakeFloatingBtn = document.createElement('div');
    	    fakeFloatingBtn.classList.add('auglio-tryon-btn', 'auglio-tryon-floating');
    	    const auglioFloatingLogo = document.createElement('div');
    	    auglioFloatingLogo.classList.add('auglio-floating-logo');
    	    const auglioFloatingText = document.createElement('div');
    	    auglioFloatingText.classList.add('auglio-floating-text');
    	    auglioFloatingText.innerText = 'TRY ON';
    	    auglioFloatingLogo.appendChild(auglioFloatingText);
    	    fakeFloatingBtn.appendChild(auglioFloatingLogo);
    	    fakeFloatingBtn.setAttribute('data-item_id', id);
            fakeFloatingBtn.style.display = 'none';
    	    return fakeFloatingBtn;
    	}

        if (window.location.href.indexOf('products') > -1) {
            insertButtonToProductPage();
        }
    } catch(e) {
        auglioHandleIntegrationError(e);
    }
});

function auglioAddToCart() {
    const addToCartBtn = document.querySelector('.button__drawer .add_to_cart');
    /*console.log(`Trying to add to cart. addToCartBtn:`, addToCartBtn);*/
    if (addToCartBtn && getComputedStyle(addToCartBtn).display !== 'none') {
        addToCartBtn.click();
        /*console.log('add to cart btn clicked');*/
    }
}

function observeAddToCartVisibility() {
    function updateAuglioButtons() {
        const addToCartBtn = document.querySelector('.button__drawer .add_to_cart');
        const auglioBuyBtn = document.querySelector('.auglio-buy-button');
        const auglioProductBtn = document.querySelector('.auglio-product-information_buttons .auglio-button');

        /*console.log("Checking visibility of .add_to_cart...");*/
        if (addToCartBtn) {
            const isVisible = getComputedStyle(addToCartBtn).display !== 'none';
            /*console.log(`.add_to_cart is ${isVisible ? 'VISIBLE' : 'HIDDEN'}`);*/

            if (auglioBuyBtn) {
                auglioBuyBtn.style.display = isVisible ? 'flex' : 'none';
                /*console.log(`Setting .auglio-buy-button display to ${auglioBuyBtn.style.display}`);*/
            } else {
                console.log("WARNING: .auglio-buy-button not found in the DOM.");
            }

            if (auglioProductBtn) {
                auglioProductBtn.style.display = isVisible ? 'inline-block' : 'none';
                /*console.log(`Setting .auglio-product-information_buttons .auglio-button display to ${auglioProductBtn.style.display}`);*/
            } else {
                console.log("WARNING: .auglio-product-information_buttons .auglio-button not found in the DOM.");
            }
        } else {
            console.log("WARNING: .add_to_cart not found in the DOM.");
        }
    }

    function startObserving() {
        const addToCartBtn = document.querySelector('.button__drawer .add_to_cart');
        if (addToCartBtn) {
            /*console.log(".add_to_cart found, setting up MutationObserver...");*/

            const observer = new MutationObserver(() => {
                /*console.log("Mutation detected on .add_to_cart, updating button visibility...");*/
                updateAuglioButtons();
            });

            observer.observe(addToCartBtn, { attributes: true, attributeFilter: ['style'] });
            updateAuglioButtons();
        } else {
            /*console.log("ERROR: .add_to_cart not found at initialization. Retrying in 1 second...");*/
            setTimeout(startObserving, 1000);
        }
    }

    // Observing dynamic insertion of .auglio-buy-button
    const toolObserver = new MutationObserver(() => {
        /*console.log("Checking if Auglio buttons have been added dynamically...");*/
        const auglioBuyBtn = document.querySelector('.auglio-buy-button');

        if (auglioBuyBtn) {
            /*console.log(".auglio-buy-button detected, updating visibility...");*/
            updateAuglioButtons();
            toolObserver.disconnect();
        }
    });

    // Observing dynamic insertion of .auglio-product-information_buttons .auglio-button
    const productButtonObserver = new MutationObserver(() => {
        /*console.log("Checking if .auglio-product-information_buttons .auglio-button has been added dynamically...");*/
        const auglioProductBtn = document.querySelector('.auglio-product-information_buttons .auglio-button');

        if (auglioProductBtn) {
            /*console.log(".auglio-product-information_buttons .auglio-button detected, updating visibility...");*/
            updateAuglioButtons();
            productButtonObserver.disconnect();
        }
    });

    toolObserver.observe(document.body, { childList: true, subtree: true });
    productButtonObserver.observe(document.body, { childList: true, subtree: true });

    startObserving();
}

// Call function to initialize the observer
observeAddToCartVisibility();
        } catch (e) {
            auglioHandleIntegrationError(e)
        }
    
    
        function auglioAdditionalCSS() {
        let styles = `.auglio-tryon-btn-product {    width: 100%;    background-color: #a20901 !important;    margin-bottom: 15px;}.auglio-tryon-btn-product:hover {    background-color: #151515 !important;}#auglio-logo {    background-color: transparent !important;    border-radius: 0 !important;    box-shadow: none !important;    top: 12px !important;    left: calc(50% - 65px) !important;    height: 33.75px !important;    width: 150px !important;    background-size: 100% 100%;    background-position: center center;    background-repeat: no-repeat;    background-image: url('https://filteroptix.com/cdn/shop/files/Filter-Optix-400px-nobackground_410x.png?v=1631395263');    z-index: 60 !important;}#auglio-logo svg {    display: none !important;}.auglio-minified #auglio-categories-container {    padding-top: 44px !important;}.auglio-product-information_buttons {    align-items: center;    justify-content: center;}.auglio-tryon-floating {    bottom: 60px !important;    z-index: 9999999;    will-change: transform;    cursor: pointer;    background: rgba(0, 0, 0, 0);    border: none;    transition: transform .225s ease-in-out;    animation: auglioFadeIn 0.225s ease-in-out;    position: fixed;    left: 50px;}.auglio-tryon-floating:hover {    transform: scale(1.05);}.auglio-floating-logo {    color: #FFFFFF;    width: 50px;    height: 50px;    border-radius: 100px;    display: flex;    justify-content: center;    align-items: center;    background-color: #a20901;    background-size: 75% 75%;    background-position: center center;    background-repeat: no-repeat;    background-image: url("data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJMYXllcl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgMTc5LjggMTc5LjgiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDE3OS44IDE3OS44OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxzdHlsZSB0eXBlPSJ0ZXh0L2NzcyI+Cgkuc3Qwe2ZpbGw6IzZBQkQ0NTt9Cgkuc3Qxe2ZpbGw6I2ZmZmZmZjt9Cjwvc3R5bGU+CjxnPgoJPGc+CgkJPHBhdGggY2xhc3M9InN0MSIgZD0iTTEyNy44LDE0MC41Yy04LjIsMC0xOS44LTAuOC0yNS4xLTcuN2MtNi44LTktNy4yLTI0LjMtNy4yLTI3LjNjMC0wLjcsMC40LTEuNCwxLTEuOAoJCQljMC42LTAuMywxNC40LTguNSwzNi43LTguNWMyMS44LDAsMjcuNywyLjcsMjguMywzYzAuNywwLjQsMS4yLDEuMSwxLjIsMS45YzAsOC4xLTIuNSwyNC4xLTUuOSwyOC44Yy0wLjIsMC4zLTAuNCwwLjUtMC41LDAuOAoJCQlDMTUyLjYsMTM1LjIsMTQ3LjQsMTQwLjUsMTI3LjgsMTQwLjV6IE05OS44LDEwNi44YzAuMywxNC44LDUuMywyMi4xLDYuMywyMy41YzMsNCwxMC4zLDYsMjEuNyw2YzE5LDAsMjIuNi01LjQsMjUuMS05CgkJCWMwLjItMC4zLDAuNC0wLjYsMC42LTAuOWMyLjItMy4xLDQuOC0xNi4yLDUuMS0yNC45Yy0yLjUtMC43LTkuNi0yLjEtMjUuMi0yLjFDMTE1LjUsOTkuNSwxMDMuMywxMDUsOTkuOCwxMDYuOHoiLz4KCTwvZz4KCTxnPgoJCTxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik01MS4yLDE0MC41Yy0xOS42LDAtMjQuOC01LjMtMjguNS0xMC44Yy0wLjItMC4zLTAuNC0wLjUtMC41LTAuOGMtMy4zLTQuNy01LjktMjAuNy01LjktMjguOAoJCQljMC0wLjgsMC40LTEuNSwxLjItMS45YzAuNi0wLjMsNi41LTMsMjguMy0zYzIyLjIsMCwzNi4xLDguMiwzNi43LDguNWMwLjYsMC40LDEsMS4xLDEsMS44YzAsMy0wLjMsMTguMy03LjIsMjcuMwoJCQlDNzEsMTM5LjcsNTkuNCwxNDAuNSw1MS4yLDE0MC41eiBNMjAuNSwxMDEuNmMwLjMsOC43LDIuOSwyMS44LDUuMSwyNC45YzAuMiwwLjMsMC40LDAuNiwwLjYsMC45YzIuNCwzLjYsNi4xLDksMjUuMSw5CgkJCWMxMS40LDAsMTguNy0yLDIxLjctNmMxLTEuMyw2LTguNyw2LjMtMjMuNWMtMy41LTEuOC0xNS44LTcuNC0zMy41LTcuNEMzMC4xLDk5LjUsMjMsMTAwLjksMjAuNSwxMDEuNnoiLz4KCTwvZz4KCTxnPgoJCTxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik04MS4zLDEwNy43Yy0wLjUsMC0xLTAuMi0xLjQtMC42Yy0wLjktMC44LTAuOS0yLjEtMC4xLTNjMC4zLTAuNCwzLjMtMy40LDkuOC0zLjRjNi40LDAsOS40LDMuMSw5LjgsMy40CgkJCWMwLjgsMC45LDAuNywyLjItMC4xLDNjLTAuOSwwLjgtMi4yLDAuNy0zLTAuMWMtMC4xLTAuMS0yLjEtMi4xLTYuNy0yLjFjLTQuNiwwLTYuNiwyLTYuNywyLjFDODIuNCwxMDcuNSw4MS44LDEwNy43LDgxLjMsMTA3Ljd6CgkJCSIvPgoJPC9nPgoJPGc+CgkJPHBhdGggY2xhc3M9InN0MSIgZD0iTTE2My40LDEwMi4yaC0yLjdjLTEuMiwwLTIuMS0wLjktMi4xLTIuMWMwLTAuOSwwLjYtMS43LDEuMy0ybC0yNS42LTQ2LjNjMCwwLDAtMC4xLDAtMC4xCgkJCWMtMi4xLTQuMy00LjItNC4zLTQuOS00LjNjLTIuNywwLTMuMywwLjItNS4xLDIuMWwtMTEuMywxMS4xYy0wLjgsMC44LTIuMiwwLjgtMywwYy0wLjgtMC44LTAuOC0yLjIsMC0zbDExLjMtMTEuMQoJCQljMi43LTIuNyw0LjMtMy4zLDguMS0zLjNjMy42LDAsNi41LDIuMiw4LjcsNi42bDI3LjMsNDkuMmMwLjQsMC43LDAuMywxLjQsMCwyLjFDMTY0LjgsMTAxLjgsMTY0LjEsMTAyLjIsMTYzLjQsMTAyLjJ6Ii8+Cgk8L2c+Cgk8Zz4KCQk8cGF0aCBjbGFzcz0ic3QxIiBkPSJNMTguMywxMDIuMmgtMi43Yy0wLjcsMC0xLjQtMC40LTEuOC0xYy0wLjQtMC42LTAuNC0xLjQsMC0yLjFMNDEsNDkuOWMyLjItNC40LDUuMS02LjYsOC43LTYuNgoJCQljMy44LDAsNS40LDAuNyw4LjEsMy40bDExLjMsMTEuMWMwLjgsMC44LDAuOCwyLjEsMCwzYy0wLjgsMC44LTIuMSwwLjgtMywwTDU0LjgsNDkuNmMtMS45LTEuOS0yLjQtMi4xLTUuMi0yLjEKCQkJYy0wLjcsMC0yLjgsMC00LjksNC4zYzAsMCwwLDAuMSwwLDAuMUwxOS4xLDk4LjFjMC44LDAuMywxLjMsMS4xLDEuMywyQzIwLjQsMTAxLjMsMTkuNSwxMDIuMiwxOC4zLDEwMi4yeiIvPgoJPC9nPgo8L2c+Cjwvc3ZnPgo=");}.auglio-floating-text {    position: absolute;    user-select: none;    top: -35px;    z-index: 10;    white-space: nowrap;    color: #FFFFFF;    border-radius: 100px;    display: inline-block;    padding: 5px 10px 5px 10px;    line-height: 100%;    background-color: #a20901;    font-family: Oswald, sans-serif;    font-weight: 400;    font-style: normal;    letter-spacing: 2px;    font-size: 12px;    width: 63px;    text-align: center;}.auglio-floating-text::after {    content: '';    display: block;    width: 4px;    z-index: 9;    height: 4px;    position: absolute;    bottom: -4px;    box-sizing: content-box;    border-bottom: 4px solid #a20901;    border-right: 4px solid #a20901;    transform: translateX(-50%) rotate(45deg);    left: 50%;}`;
        let styleSheet = document.createElement("style");
        styleSheet.innerText = styles;
        document.body.appendChild(styleSheet)
    }
    auglioAdditionalCSS()
    
function isAuglioMinifiedAndOpened() {
    return document.body.classList.contains("auglio-widget-inserted") && document.getElementById("auglio-wrapper").classList.contains("auglio-minified") && window.innerWidth > 768 && document.getElementById("auglio-wrapper").style.display !== "none";
}

const AUGLIO_CONFIG = Object.freeze({
    domains: Object.freeze([
        'iframe.auglio.com',
        'admin.auglio.com'
    ]),
    viteAsset: 'https://tryon.auglio.com//build/assets/app.c87b20e8.js',
    shouldPreload: 1, 
    apiUrl: 'https://tryon.auglio.com/api/product'
});

function auglioCreateLink(options) {
    const link = document.createElement('link');
    Object.assign(link, options);
    link.crossOrigin = 'anonymous';
    return link;
}

function auglioInsertAuglioPreconnects() {
    
    const fragment = document.createDocumentFragment();
    
    AUGLIO_CONFIG.domains.forEach(domain => {
        
        fragment.appendChild(auglioCreateLink({
            rel: 'preconnect',
            href: `https://${domain}`
        }));

        
        fragment.appendChild(auglioCreateLink({
            rel: 'dns-prefetch',
            href: `https://${domain}`
        }));
    });

    document.head.appendChild(fragment);
}

function auglioCreatePreloadIframe() {
    if (!AUGLIO_CONFIG.shouldPreload) return;

    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = 'https://iframe.auglio.com/preload.php';
    
    document.body.appendChild(iframe);
}

async function auglioFindProductsToPreload() {
    
    const button = document.querySelector('.auglio-tryon-btn[data-group_id]');
    if (!button?.dataset?.group_id) return null;

    const groupId = button.dataset.group_id;
    
    try {
        
        const response = await fetch(`${AUGLIO_CONFIG.apiUrl}?${new URLSearchParams({
            product_id: groupId,
            partner_id: '9847',
            ignore_published: '0'
        })}`);
        
        if (!response.ok) return null;
        
        const product = await response.json();
        if (!product?.id) return null;
        
        return [product]; 
    } catch (error) {
        return null;
    }
}

function auglioCreateTimestamp(modifiedAt) {
    if (!modifiedAt || typeof modifiedAt !== 'string') {
        return Math.floor(new Date().getTime() / 1000);
    }

    const dateStr = modifiedAt;
    const isoStr = dateStr.replace(' ', 'T') + 'Z';
    const dateObj = new Date(isoStr);

    if (isNaN(dateObj.getTime())) {
        return Math.floor(new Date().getTime() / 1000);
    }

    return Math.floor(dateObj.getTime() / 1000);
}

async function auglioPreloadProductAssets(product) {
    if (!product?.fotopng) return [];
    
    const assetsToPreload = new Set();

    
    const mainUrl = product.fotopng;
    const timestamp = auglioCreateTimestamp(product.modified);
    const mainUrlWithTimestamp = `${mainUrl}?v=${timestamp}`;
    assetsToPreload.add(mainUrlWithTimestamp);

    
    if (mainUrl.endsWith('.png') && 
        (product.category_id === 11 || product.category_id === 16)) {
        if (product.fotopng2 === '1') {
            const leftUrl = `${mainUrl.replace('.png', '_L.png')}?v=${timestamp}`;
            const rightUrl = `${mainUrl.replace('.png', '_R.png')}?v=${timestamp}`;
            assetsToPreload.add(leftUrl);
            assetsToPreload.add(rightUrl);
        }
        if (product.hasLens === 1) {
            const lensUrl = `${mainUrl.replace('.png', '_X.png')}?v=${timestamp}`;
            assetsToPreload.add(lensUrl);
        }
    }

    
    if (Array.isArray(product.group)) {
        for (const groupProduct of product.group) {
            if (groupProduct?.fotopng?.endsWith('.auglio') && 
                groupProduct.id !== product.id) { 
                const auglioUrl = groupProduct.fotopng;
                const timestamp = auglioCreateTimestamp(groupProduct.modified);
                const auglioUrlWithTimestamp = `${auglioUrl}?v=${timestamp}`;
                assetsToPreload.add(auglioUrlWithTimestamp);
            }
        }
    }

    
    const loadedAssets = [];
    
    const loadImage = (src) => new Promise((resolve, reject) => {
        const img = new Image();
        img.crossOrigin = 'anonymous';
        const timeoutId = setTimeout(() => reject(), 30000); 

        img.onload = () => {
            clearTimeout(timeoutId);
            resolve(img);
        };
        img.onerror = () => {
            clearTimeout(timeoutId);
            reject();
        };
        img.src = src;
    });

    const loadBinary = async (src) => {
        const timeoutId = setTimeout(() => { throw new Error(); }, 30000); 

        try {
            const response = await fetch(src);
            if (!response.ok) throw new Error();

            const reader = response.body.getReader();
            const chunks = [];
            let loadedSize = 0;

            try {
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    chunks.push(value);
                    loadedSize += value.length;
                }

                const modelData = new Uint8Array(loadedSize);
                let position = 0;
                for (const chunk of chunks) {
                    modelData.set(chunk, position);
                    position += chunk.length;
                }

                clearTimeout(timeoutId);
                return modelData.buffer;
            } finally {
                reader.releaseLock();
            }
        } catch (error) {
            clearTimeout(timeoutId);
            throw error;
        }
    };

    for (const src of assetsToPreload) {
        try {
            if (src.includes('.png') || src.includes('.jpg')) {
                const img = await loadImage(src);
                if (img) loadedAssets.push(img);
            } else if (src.includes('.glb') || src.includes('.auglio')) {
                const buffer = await loadBinary(src);
                if (buffer) loadedAssets.push(buffer);
            }
        } catch {
            
        }
    }

    return loadedAssets;
}

async function auglioScheduleResourcePreload() {
    const schedulePreload = window.requestIdleCallback || 
        ((cb) => setTimeout(cb, 1000));

    const startPreload = async () => {
        if (!AUGLIO_CONFIG.shouldPreload) return;

        try {
            // Create preload iframe first for core libraries
            auglioCreatePreloadIframe();

            // Preload Vite module if not already loaded
            if (!document.querySelector(`link[href="${AUGLIO_CONFIG.viteAsset}"]`)) {
                const link = auglioCreateLink({
                    rel: 'modulepreload',
                    href: AUGLIO_CONFIG.viteAsset
                });
                document.head.appendChild(link);
            }

            // Then preload product assets
            const products = await auglioFindProductsToPreload();
            if (!products) return;

            // Preload first product's assets
            await auglioPreloadProductAssets(products[0]);
        } catch (error) {
            
        }
    };

    schedulePreload(() => {
        startPreload().catch(() => {});
    });
}


document.addEventListener('auglioButtonsRefreshed', () => {
    if (!AUGLIO_CONFIG.shouldPreload) return;

    const preloadFn = async () => {
        try {
            const products = await auglioFindProductsToPreload();
            if (products?.[0]) {
                await auglioPreloadProductAssets(products[0]);
            }
        } catch {
            
        }
    };

    if (window.requestIdleCallback) {
        requestIdleCallback(() => preloadFn());
    } else {
        setTimeout(preloadFn, 1);
    }
});


auglioInsertAuglioPreconnects();


auglioScheduleResourcePreload();