const ARModelViewer = (() => {
  const globalScope = typeof window !== 'undefined' ? window : globalThis;
  const modelTexturesArray = globalScope.__arModelTexturesArray || (globalScope.__arModelTexturesArray = {});
  const modelLastSrc = globalScope.__arModelLastSrc || (globalScope.__arModelLastSrc = {});

  class ARModelViewerClass {    
    constructor(containerId, options = {}) {
        this.modelid = containerId;
        this.options = Object.assign({}, options);  
        this.suffix = options.suffix || '';
        this.instanceId = options.instanceId || '';
        this.instanceSelector = this.buildInstanceSelector(this.instanceId);
        this.storageKey = this.instanceId ? `${this.modelid}::${this.instanceId}` : this.modelid;
        
        const elementId = 'model_' + this.modelid;
        this.modelViewer = this.findElementByIdWithInstance(elementId);
        this.container = this.findElementByIdWithInstance('ardisplay_viewer_' + this.modelid);
        if (!this.container && this.instanceSelector) {
            this.container = document.querySelector(`div${this.instanceSelector}`);
        }
        this.pluginId = options.pluginId || (typeof window !== 'undefined' && window.ARAnalytics && typeof window.ARAnalytics.getDefaultPluginId === 'function' ? window.ARAnalytics.getDefaultPluginId() : '');
        
        // Safety check: ensure the main modelViewer element exists and is valid
        if (!this.modelViewer) {
            console.error('ARModelViewer: Main modelViewer element not found for', this.modelid);
            return;
        }

        // Check if the element is a valid model-viewer element
        if (!this.modelViewer.tagName || this.modelViewer.tagName.toLowerCase() !== 'model-viewer') {
            console.error('ARModelViewer: Main element is not a model-viewer:', this.modelViewer);
            return;
        }
        
        this.initARModelViewer();
    }

    buildInstanceSelector(instanceId) {
        if (!instanceId) {
            return '';
        }
        if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
            return `[data-ar-instance="${CSS.escape(instanceId)}"]`;
        }
        const safeId = String(instanceId).replace(/"/g, '\\"');
        return `[data-ar-instance="${safeId}"]`;
    }

    elementMatchesInstance(element) {
        if (!element || !this.instanceSelector) {
            return false;
        }
        return Boolean(element.closest(this.instanceSelector));
    }

    findElementByIdWithInstance(elementId) {
        if (!elementId) {
            return null;
        }
        const primary = document.getElementById(elementId);
        if (!this.instanceSelector) {
            return primary;
        }
        if (primary && this.elementMatchesInstance(primary)) {
            return primary;
        }
        const escapedId = String(elementId).replace(/"/g, '\\"');
        const candidates = document.querySelectorAll(`[id="${escapedId}"]`);
        for (const candidate of candidates) {
            if (this.elementMatchesInstance(candidate)) {
                return candidate;
            }
        }
        return primary;
    }

    initARModelViewer() {     
        // Safety check: ensure modelViewer is valid before proceeding
        if (!this.modelViewer || !this.modelViewer.tagName || this.modelViewer.tagName.toLowerCase() !== 'model-viewer') {
            console.error('ARModelViewer: Cannot initialize - modelViewer is not valid');
            return;
        }
        
        this.setScale();
        this.setDimensions();
        this.setHotspots();
        this.setMaterialStates();

        if (this.options.ar_animation) {
            this.setAnimation();
        }

        if (this.options.ar_model_list > 1) {
            this.setSlider();
        }

        if (this.options.ar_variants) {
            this.setVariants();
        }

        if (this.options.ar_pop == 'pop') {
            this.popUp();
        }

        // Initialize the scale change handler
        this.handleScaleChange();
    }

    setAnimation() {
        // Placeholder method - animation functionality can be added here later
        console.log('ARModelViewer: setAnimation called for', this.modelid);
    }

    handleScaleChange() {
        // Check if the select#scale element exists
        const scaleSelect = document.querySelector("select#scale");

        if (scaleSelect) {
            scaleSelect.addEventListener('change', () => {
                // Get the selected value
                const selectedSize = scaleSelect.value;

                // Update the scale of the model viewer
                const updateScale = () => {
                    this.modelViewer.scale = `${selectedSize} ${selectedSize} ${selectedSize}`;
                };

                updateScale();
            });
        }
    }

    trackAnalytics(eventType, payload = {}) {
        if (typeof window === 'undefined' || !window.ARAnalytics || typeof window.ARAnalytics.track !== 'function') {
            return;
        }

        const data = Object.assign(
            {
                pluginId: this.pluginId,
                modelId: this.modelid,
                instanceId: this.instanceId || '',
            },
            payload
        );

        window.ARAnalytics.track(eventType, data);
    }

    
    setMaterialStates(){
        const modelViewer = this.modelViewer;
        if (!modelViewer) {
            console.warn("ARModelViewer: Model element not found for material state binding.");
            return;
        }
        let materialStatesHiddenInput = null;
        if (this.container) {
            materialStatesHiddenInput = this.container.querySelector(`input[name="_ar_material_states${this.suffix}"]`);
        }
        if (!materialStatesHiddenInput) {
            materialStatesHiddenInput = document.querySelector(`input[name="_ar_material_states${this.suffix}"]`);
        }
        
        //if (!materialStatesHiddenInput || !materialStatesHiddenInput.value) return;

        //console.log('armodelviewer = _ar_material_states' + this.suffix);
        
        const storageKey = this.storageKey;
        modelLastSrc[storageKey] = null;   


        const handleLoad = async () => {
          this.trackAnalytics('viewer_load', { variant: modelViewer.variantName || '' });
          let savedStates;
          const currentSrc = modelViewer.src;

          if (modelLastSrc[storageKey] !== null && modelLastSrc[storageKey] !== currentSrc) {
            if (materialStatesHiddenInput) {
              materialStatesHiddenInput.value = '';
            }
          }

          modelLastSrc[storageKey] = currentSrc;

          try {
            savedStates = materialStatesHiddenInput ? JSON.parse(materialStatesHiddenInput.value) : {};
          } catch (err) {
            savedStates = {};
          }

          if (!modelViewer.model) {
            console.warn("Model not loaded yet.");
            return;
          }

          const materials = modelViewer.model.materials;
          await Promise.all(materials.map((mat) => mat.ensureLoaded()));

          const allTextures = {};
          let modelTextures = {};

          for (const mat of materials) {

            const textures = {
              baseColorTexture: mat.pbrMetallicRoughness.baseColorTexture,
              metallicRoughnessTexture: mat.pbrMetallicRoughness.metallicRoughnessTexture,
              normalTexture: mat.normalTexture,
              emissiveTexture: mat.emissiveTexture,
              occlusionTexture: mat.occlusionTexture,
            };

            for (const [type, info] of Object.entries(textures)) {
              if (!info) continue;
              const tex = info.texture;
              const texUri = tex?.source?.uri || tex?.image?.src || "";
              const texName = tex?.name || texUri.split("/").pop() || "";

              allTextures[texName] = tex;

              modelTextures[texName] = {
                type: type,
                info: info,   // wrapper → has createThumbnail()
                texture: tex     // raw three.js texture
              };

            }

            modelTexturesArray[storageKey] = modelTextures;
          }

          for (const [index, state] of Object.entries(savedStates)) {
            const mat = materials[index];
            if (!mat) continue;

            if (state.basecolor) {
              // Preserve original alpha value from the material to maintain transparency (e.g., glass materials)
              const originalAlpha = mat.pbrMetallicRoughness.baseColorFactor 
                ? mat.pbrMetallicRoughness.baseColorFactor[3] 
                : 1.0;
              
              // Preserve original alphaMode if material has transparency
              const originalAlphaMode = mat.alphaMode || (originalAlpha < 1.0 ? 'BLEND' : 'OPAQUE');
              
              mat.pbrMetallicRoughness.setBaseColorFactor(
                this.hexToRgbaArray(state.basecolor, originalAlpha)
              );
              
              // Restore alphaMode if it was saved, or ensure BLEND for transparent materials
              if (state.alphaMode) {
                mat.alphaMode = state.alphaMode;
              } else if (originalAlpha < 1.0 && mat.alphaMode !== 'BLEND') {
                mat.alphaMode = 'BLEND';
              } else if (originalAlphaMode === 'BLEND' && mat.alphaMode !== 'BLEND') {
                mat.alphaMode = 'BLEND';
              }
            }

            //console.log(state);


            if (state.texture) {
              try {
                if(state.texture == 'null'){
                    continue;                    
                } else if(state.texture != 'none'){                    
                    //const newTexture = await modelViewer.createTexture(allTextures[state.texture]);
                    let mbaseColorTexture = allTextures[state.texture];
                    if(state.texture_uploaded == 1){
                        mbaseColorTexture = await modelViewer.createTexture(state.texture_url);
                    }
                    setTimeout(() => {
                        mat.pbrMetallicRoughness.baseColorTexture.setTexture(mbaseColorTexture);
                        const materialSelect = document.querySelector("#_ar_material" + this.suffix);
                        //if materials dropdown is present (in admin)
                        if(materialSelect){       
                          var textureImg = document.querySelector(`#color_texture_picker${this.suffix} img[data-texture="${state.texture}"]`);                          
                          if(textureImg){               
                            if(index == 0){
                                document.querySelectorAll('#color_texture_picker' + this.suffix + ' img').forEach(i => i.style.outline = '');
                                textureImg.style.outline = '2px solid #00f';                                                   
                            }
                          }
                        }
                    }, 1000);

                  //end



                } else {
                    setTimeout(() => {
                      mat.pbrMetallicRoughness.baseColorTexture.setTexture(null);
                      /*if(index == 0){
                        document.querySelectorAll('#color_texture_picker img').forEach(i => i.style.outline = '');
                        document.querySelector('#blank-texture').style.outline = '2px solid #00f';                                                   
                      }*/
                    }, 1000);

                      
                }
              } catch (err) {
                console.error(`Failed to apply texture for material ${index}:`, err);
              }
            } else {
              setTimeout(() => {
                  mat.pbrMetallicRoughness.baseColorTexture.setTexture(null);

                  /*if(index == 0){
                    document.querySelectorAll('#color_texture_picker img').forEach(i => i.style.outline = '');
                    document.querySelector('#blank-texture').style.outline = '2px solid #00f';                                                   
                  }*/
              }, 1000);
            }



            if (state.metallic_texture) {
              try {
                if(state.metallic_texture == 'null'){
                    continue;                    
                } else if(state.metallic_texture != 'none'){                    
                    //const newTexture = await modelViewer.createTexture(allTextures[state.texture]);
                    let metallicTexture = allTextures[state.metallic_texture];
                    if(state.metallic_texture_uploaded == 1){
                        metallicTexture = await modelViewer.createTexture(state.metallic_texture_url);
                    }
                    setTimeout(() => {
                        mat.pbrMetallicRoughness.metallicRoughnessTexture.setTexture(metallicTexture);
                        const materialSelect = document.querySelector("#_ar_material" + this.suffix);
                        //if materials dropdown is present (in admin)
                        if(materialSelect){       
                          var textureImg = document.querySelector(`#metallic_texture_picker${this.suffix} img[data-texture="${state.metallic_texture}"]`);                          
                          if(textureImg){               
                            if(index == 0){
                                document.querySelectorAll('#metallic_texture_picker' + this.suffix + ' img').forEach(i => i.style.outline = '');
                                textureImg.style.outline = '2px solid #00f';                                                   
                            }
                          }
                        }
                    }, 1000);

                  //end

                } else {
                    setTimeout(() => {
                      mat.pbrMetallicRoughness.metallicRoughnessTexture.setTexture(null);
                      /*if(index == 0){
                        document.querySelectorAll('#metallic_texture_picker img').forEach(i => i.style.outline = '');
                        document.querySelector('#metallic-blank-texture').style.outline = '2px solid #00f';                                                   
                      }*/
                    }, 1000);                    
                }
              } catch (err) {
                console.error(`Failed to apply texture for material ${index}:`, err);
              }
            } else {
                setTimeout(() => {
                  mat.pbrMetallicRoughness.metallicRoughnessTexture.setTexture(null);
                  /*if(index == 0){
                    document.querySelectorAll('#metallic_texture_picker img').forEach(i => i.style.outline = '');
                    document.querySelector('#metallic-blank-texture').style.outline = '2px solid #00f';                                                   
                  }*/
                }, 1000);
            }


            // --- Metallic / Roughness if saved ---
            if (state.metallic !== null && state.metallic !== undefined) {
              mat.pbrMetallicRoughness.setMetallicFactor(state.metallic);
            }
            if (state.roughness !== null && state.roughness !== undefined) {
              mat.pbrMetallicRoughness.setRoughnessFactor(state.roughness);
            }
          }
        };

        modelViewer.addEventListener("load", handleLoad);
        if (modelViewer.model) {
          handleLoad();
        }
    }


    hexToRgbaArray(hex, alpha = 1) {
          hex = hex.replace(/^#/, '');
          if (hex.length === 3) {
            hex = hex.split('').map(x => x + x).join('');
          }
          const bigint = parseInt(hex, 16);
          const r = ((bigint >> 16) & 255) / 255;
          const g = ((bigint >> 8) & 255) / 255;
          const b = (bigint & 255) / 255;
          return [r, g, b, alpha];
    }



    setVariants(){
        const modelViewerVariants = this.modelViewer;
        if (!modelViewerVariants) {
            console.warn('ARModelViewer: modelViewerVariants element not found for', this.modelid);
            return;
        }
        let select = null;
        if (this.container) {
            select = this.container.querySelector(`#variant_${this.modelid}${this.suffix}`);
            if (!select) {
                select = this.container.querySelector('select[id^="variant_"]');
            }
        }
        if (!select) {
            select = this.findElementByIdWithInstance('variant_' + this.modelid + this.suffix);
        }
        
        // Check if the element is a valid model-viewer element
        if (!modelViewerVariants.tagName || modelViewerVariants.tagName.toLowerCase() !== 'model-viewer') {
            console.warn('ARModelViewer: Element is not a model-viewer:', modelViewerVariants);
            return;
        }
        
        modelViewerVariants.addEventListener('load', () => {
        const names = modelViewerVariants.availableVariants;
        for (const name of names) {
            const option = document.createElement('option');
            option.value = name;
            option.textContent = name;
            select.appendChild(option);
          }
        });
        
        select.addEventListener('input', (event) => {
          modelViewerVariants.variantName = event.target.value;
          this.trackAnalytics('variant_change', { variant: event.target.value });
        });
    }

    setScale() {
      if(isNumeric(this.options.ar_x) && isNumeric(this.options.ar_x) && isNumeric(this.options.ar_x) && this.options.ar_pop!='pop'){
        const modelViewerTransform = this.findElementByIdWithInstance('model_' + this.modelid  + this.suffix) || this.modelViewer;
        
        // Safety check: ensure modelViewerTransform exists and is ready
        if (!modelViewerTransform) {
            console.warn('ARModelViewer: modelViewerTransform element not found for setScale', this.modelid);
            return;
        }

        // Check if the element is a valid model-viewer element
        if (!modelViewerTransform.tagName || modelViewerTransform.tagName.toLowerCase() !== 'model-viewer') {
            console.warn('ARModelViewer: Element is not a model-viewer in setScale:', modelViewerTransform);
            return;
        }
        
        const updateScale = () => {
          modelViewerTransform.scale = this.options.ar_x + ' ' + this.options.ar_y + ' ' + this.options.ar_z;
        };
        updateScale();
      }
    }


    setSlider(){
        // Safety check: ensure slider elements exist
        const sliderElement = document.querySelector(".ar_slider");
        if (!sliderElement) {
            console.warn('ARModelViewer: Slider element not found for', this.modelid);
            return;
        }
        
        window.switchSrc = (modelid, buttonElement, name, usdz) => {
            var modelViewerList = document.querySelector("#" + modelid);
            if (modelViewerList) {
                modelViewerList.src = name;
                modelViewerList.poster = name;
                modelViewerList.iosSrc = usdz;
                // console.log(name);
                
                const slides = document.querySelectorAll(".ar_slide");
                slides.forEach((element) => {
                    element.classList.remove("selected");
                });
        
                if (buttonElement && buttonElement.classList) {
                    buttonElement.classList.add("selected"); // Use the passed element to add the class
                } else {
                    console.error("buttonElement is not defined or does not have a classList.");
                }
            } else {
                console.error("Model viewer element not found.");
            }
        };

        sliderElement.addEventListener('beforexrselect', (ev) => {
            // Keep slider interactions from affecting the XR scene.
            ev.preventDefault();
        });
    }


    setDimensions(){       
        const modelViewer = this.modelViewer;
        
        // Safety check: ensure modelViewer exists and is ready
        if (!modelViewer) {
            console.warn('ARModelViewer: modelViewer element not found for setDimensions', this.modelid);
            return;
        }

        // Check if the element is a valid model-viewer element
        if (!modelViewer.tagName || modelViewer.tagName.toLowerCase() !== 'model-viewer') {
            console.warn('ARModelViewer: Element is not a model-viewer in setDimensions:', modelViewer);
            return;
        }
        
        const srcElement = modelViewer.querySelector('#src_'+this.modelid+this.suffix);
        if (srcElement) {
            srcElement.addEventListener('input', (event) => {
              modelViewer.src = event.target.value;
            });
        }
        
        const checkbox = modelViewer.querySelector('#show-dimensions_' + this.modelid  + this.suffix);
        
        if (checkbox) {
            checkbox.addEventListener('change', () => {
          modelViewer.querySelectorAll('button').forEach((hotspot) => {
              if ((hotspot.classList.contains('dimension'))||(hotspot.classList.contains('dot'))){
                if (checkbox.checked) {
                  hotspot.classList.remove('nodisplay');
                } else {
                  hotspot.classList.add('nodisplay');
                }
              }
            
              if (this.options.ar_hide_fullscreen==''){
              
                 const popBtn = this.findElementByIdWithInstance('ar_pop_Btn_'+this.options.id);
                 const closeBtn = this.findElementByIdWithInstance('ar_close_'+this.modelid  + this.suffix);
                 if (popBtn && popBtn.classList.contains('nodisplay')){
                      popBtn.classList.remove('nodisplay');
                      if (closeBtn) {
                          closeBtn.classList.remove('nodisplay');
                      }
                 }                
                
                 const arButton = this.findElementByIdWithInstance('ar-button_'+this.modelid + this.suffix);
                 const arQrCode = this.findElementByIdWithInstance('ar-qrcode_'+this.modelid + this.suffix);
                 if (arButton) {
                     arButton.classList.remove('nodisplay');
                 }
                 if (arQrCode) {
                     arQrCode.classList.remove('nodisplay');
                 }
              }
          });
            });
        }

        const dimensionButton = modelViewer.querySelector('button.dimension');
        if (dimensionButton) {
            dimensionButton.addEventListener('click', (event) => {
                event.preventDefault();
            });
        }
    }

    setHotspots(){
        const modelViewer = this.modelViewer;
        
        // Safety check: ensure modelViewer exists and is ready
        if (!modelViewer) {
            console.warn('ARModelViewer: modelViewer element not found for setHotspots', this.modelid);
            return;
        }

        // Check if the element is a valid model-viewer element
        if (!modelViewer.tagName || modelViewer.tagName.toLowerCase() !== 'model-viewer') {
            console.warn('ARModelViewer: Element is not a model-viewer in setHotspots:', modelViewer);
            return;
        }
        
        modelViewer.addEventListener('load', () => {
            const center = modelViewer.getCameraTarget();
            const size = modelViewer.getDimensions();
            const x2 = size.x / 2;
            const y2 = size.y / 2;
            const z2 = size.z / 2;
        
            modelViewer.updateHotspot({
              name: 'hotspot-dot+X-Y+Z',
              position: `${center.x + x2} ${center.y - y2} ${center.z + z2}`
            });
        
            modelViewer.updateHotspot({
              name: 'hotspot-dim+X-Y',
              position: `${center.x + x2} ${center.y - y2} ${center.z}`
            });

            var hotspotx; 
            var hotspoty; 
            var hotspotz;

            if ((this.options.ar_dimensions_units == 'inches') || (this.options.ar_dimensions_inches == true)){
                hotspotz = `${(size.z * 39.370).toFixed(2)} in`;
            } else if (this.options.ar_dimensions_units == 'cm'){
                hotspotz = `${(size.z * 100).toFixed(0)} cm`;
            } else if (this.options.ar_dimensions_units == 'mm'){
                hotspotz = `${(size.z * 1000).toFixed(0)} mm`;
            } else {
                hotspotz = `${(size.z).toFixed(2)} m`;
            }
            const hotspotDimXY = modelViewer.querySelector('button[slot="hotspot-dim+X-Y"]');
            if (hotspotDimXY) {
                hotspotDimXY.textContent = hotspotz;
            }
                     
            modelViewer.updateHotspot({
              name: 'hotspot-dot+X-Y-Z',
              position: `${center.x + x2} ${center.y - y2} ${center.z - z2}`
            });
        
            modelViewer.updateHotspot({
              name: 'hotspot-dim+X-Z',
              position: `${center.x + x2} ${center.y} ${center.z - z2}`
            });

            if ((this.options.ar_dimensions_units == 'inches') || (this.options.ar_dimensions_inches == true)){
                hotspoty = `${(size.y * 39.370).toFixed(2)} in`;
            } else if (this.options.ar_dimensions_units == 'cm'){
                hotspoty = `${(size.y * 100).toFixed(0)} cm`;
            } else if (this.options.ar_dimensions_units == 'mm'){
                hotspoty = `${(size.y * 1000).toFixed(0)} mm`;
            } else {
                hotspoty = `${(size.y).toFixed(2)} m`;
            }

            const hotspotDimXZ = modelViewer.querySelector('button[slot="hotspot-dim+X-Z"]');
            if (hotspotDimXZ) {
                hotspotDimXZ.textContent = hotspoty;
            }
                        
            modelViewer.updateHotspot({
              name: 'hotspot-dot+X+Y-Z',
              position: `${center.x + x2} ${center.y + y2} ${center.z - z2}`
            });
        
            modelViewer.updateHotspot({
              name: 'hotspot-dim+Y-Z',
              position: `${center.x} ${center.y + y2} ${center.z - z2}`
            });

            if ((this.options.ar_dimensions_units == 'inches') || (this.options.ar_dimensions_inches == true)){
                hotspotx = `${(size.x * 39.370).toFixed(2)} in`;
            } else if (this.options.ar_dimensions_units == 'cm'){
                hotspotx = `${(size.x * 100).toFixed(0)} cm`;
            } else if (this.options.ar_dimensions_units == 'mm'){
                hotspotx = `${(size.x * 1000).toFixed(0)} mm`;
            } else {
                hotspotx = `${(size.x).toFixed(2)} m`;
            }

            const hotspotDimYZ = modelViewer.querySelector('button[slot="hotspot-dim+Y-Z"]');
            if (hotspotDimYZ) {
                hotspotDimYZ.textContent = hotspotx;
            }
                        
            modelViewer.updateHotspot({
              name: 'hotspot-dot-X+Y-Z',
              position: `${center.x - x2} ${center.y + y2} ${center.z - z2}`
            });
        
            modelViewer.updateHotspot({
              name: 'hotspot-dim-X-Z',
              position: `${center.x - x2} ${center.y} ${center.z - z2}`
            });

            const hotspotDimMinusXZ = modelViewer.querySelector('button[slot="hotspot-dim-X-Z"]');
            if (hotspotDimMinusXZ) {
                hotspotDimMinusXZ.textContent = hotspoty;
            }
                       
            modelViewer.updateHotspot({
              name: 'hotspot-dot-X-Y-Z',
              position: `${center.x - x2} ${center.y - y2} ${center.z - z2}`
            });
        
            modelViewer.updateHotspot({
              name: 'hotspot-dim-X-Y',
              position: `${center.x - x2} ${center.y - y2} ${center.z}`
            });

            const hotspotDimMinusXY = modelViewer.querySelector('button[slot="hotspot-dim-X-Y"]');
            if (hotspotDimMinusXY) {
                hotspotDimMinusXY.textContent = hotspotz;
            }
            
            modelViewer.updateHotspot({
              name: 'hotspot-dot-X-Y+Z',
              position: `${center.x - x2} ${center.y - y2} ${center.z + z2}`
            });
            
          });
    }

    popUp(){

        //ar_pop_Btn_100
        //console.log("ar_close_" + this.options.id + "_pop");
        var model_id = this.options.id;
        var ar_pop_ = this.findElementByIdWithInstance("ar_popup_" + this.options.id);
        var ar_close_ = this.findElementByIdWithInstance("ar_close_" + this.options.id);
        var popTrigger = this.findElementByIdWithInstance("ar_pop_Btn_" + this.options.id);
        if(popTrigger){
            jQuery(document).on('click', "#ar_pop_Btn_" + this.options.id, function(e) {  
              // console.log(model_id + ' show');          
              jQuery("#ar_popup_" + model_id).show();
            });
        }

        jQuery(document).on('click', "#ar_close_" + this.options.id, function(e) {            
          jQuery("#ar_popup_" + model_id).hide();
        });
        

        let modelViewer = this.findElementByIdWithInstance("model_" + model_id);            
                // Wait until the model is loaded
        if (modelViewer) {
            modelViewer.addEventListener('load', () => {
                const shadowRoot = modelViewer.shadowRoot;
                if (shadowRoot) {
                    // Create a new <style> element
                    const style = document.createElement('style');
                    style.textContent = `
                        canvas#webgl-canvas.show {
                            left: 0 !important;
                            top: 0 !important;
                        }
                    `;
                    shadowRoot.appendChild(style);
                } else {
                    console.error('Shadow root not accessible.');
                }
            });
        }


        window.onclick = function(event) {
          if (event.target == ar_pop_ && ar_pop_) {
            ar_pop_.style.display = "none";
          }
        }
    }
  }

  return (containerId, options) => new ARModelViewerClass(containerId, options);

})();

function getData(){
  
}

function isNumeric(value) {
    return typeof value === 'number' && isFinite(value);
}

jQuery(document).ready(function(){

    jQuery('table.variations').on('change','select', function(e) {

        if(jQuery(this).val() == ''){
          jQuery('.ar_slide').first().click();
        }

    });

    jQuery('form.variations_form').on('reset_data', function () {
        jQuery('.ar_slide').first().click();
    });

    jQuery('form.variations_form').on('found_variation', function (event, variation) {
        const variationID = variation.variation_id;
        
        jQuery('#ar_btn_' + variationID).click();
    });
    
    // Focus Manager for AR Model Viewer
    function manageFocusOnAR() {
        // Get the current focused element
        const currentFocusedElement = document.activeElement;

        // If the active element is a button inside the AR viewer, ensure focus stays
        if (currentFocusedElement && currentFocusedElement.matches('.ar-button, button, [aria-hidden="true"], .model-viewer')) {
            // Use setTimeout to wait for UI updates before managing focus
            setTimeout(function() {
                // If aria-hidden is applied, remove it to ensure accessibility
                let hiddenElements = document.querySelectorAll('[aria-hidden="true"], [inert]');
                hiddenElements.forEach((elem) => {
                    elem.removeAttribute('aria-hidden');
                    elem.removeAttribute('inert');
                });

                // Re-focus on the active element after the model is switched
                if (currentFocusedElement) {
                    currentFocusedElement.focus();
                }
            }, 100);
        }
    }

    // Add event listener to focus on AR buttons or other interactive controls
    jQuery(document).on('click', '.ar-button, .model-viewer', function() {
        manageFocusOnAR();
    });

    // You can also add listeners for the AR model switching to ensure focus is handled
    jQuery(document).on('model-change', function() {
        manageFocusOnAR();
    });

});