function copyToClipboard(ID) {
    var copyText = document.getElementById(ID);
    copyText.select();
    copyText.setSelectionRange(0, 99999)
    document.execCommand("copy");
}


jQuery(document).ready(function(){

    // Initialize ARModelViewer from data attributes.
    // This avoids inline <script> blocks in shortcode output, which page builders
    // (e.g. Elementor Canvas) can corrupt with wpautop, breaking AR on Android.
    (function initArModelViewers() {
        function tryInitOnce() {
            if (typeof window === 'undefined' || typeof window.ARModelViewer !== 'function') {
                return false;
            }

            var nodes = document.querySelectorAll ? document.querySelectorAll('model-viewer[data-ar-options]') : [];
            for (var i = 0; i < nodes.length; i++) {
                var mv = nodes[i];
                if (mv.__arModelViewerInit) continue;
                var id = mv.getAttribute('id') || '';
                if (!id || id.indexOf('model_') !== 0) continue;
                var modelId = id.slice('model_'.length);
                var raw = mv.getAttribute('data-ar-options') || '';
                try {
                    var options = raw ? JSON.parse(raw) : {};
                    window['model_' + modelId] = window.ARModelViewer(modelId, options || {});
                    mv.__arModelViewerInit = true;
                } catch (e) {
                    // If JSON is invalid for any reason, don't loop forever.
                    mv.__arModelViewerInit = true;
                }
            }
            return true;
        }

        // Run immediately; if ARModelViewer isn't ready yet, retry briefly.
        var attempts = 0;
        (function tick() {
            attempts++;
            if (tryInitOnce()) return;
            if (attempts < 50) setTimeout(tick, 100);
        })();
    })();

    jQuery(document).on('click','button.ar-button', function(event){
        var alt_id = jQuery(this).data('alt');
        var primaryId = jQuery(this).data('id');

        // If this is a slot="ar-button" that relies on <model-viewer>'s internal AR handling
        // (user-upload / gallery-builder parity), don't intercept the click.
        if (!alt_id && !primaryId) {
            return;
        }

        event.preventDefault();
        var pluginId = jQuery(this).data('plugin');
        var targetId = alt_id || primaryId;
        var arViewer = jQuery('#model_' + targetId);
        if (arViewer.length && arViewer[0].canActivateAR) {
            // For gallery-builder models (dynamic glTF via ar-gallery.php), force WebXR-in-browser.
            try {
                var mv = arViewer[0];
                var src = arViewer.attr('src') || '';
                if (src.indexOf('ar-gallery.php') !== -1) {
                    mv.setAttribute('ar-modes', 'webxr');
                    mv.setAttribute('ar-placement', 'floor');
                }

                var activate = function() {
                    console.log('AR launch', { targetId: targetId, arModes: mv.getAttribute('ar-modes'), arPlacement: mv.getAttribute('ar-placement'), src: mv.getAttribute('src') });
                    var result = mv.activateAR();
                    if (result && typeof result.catch === 'function') {
                        result.catch(function(err) {
                            var name = (err && err.name) ? err.name : '';
                            var msg = (err && err.message) ? err.message : String(err);
                            console.error('AR activateAR() failed:', name, msg, err);
                        });
                    } else {
                        console.warn('AR activateAR() returned non-promise:', result);
                    }
                };

                // If model-viewer isn't loaded yet, wait for load then activate AR.
                // On some Android devices, activateAR can fail immediately if the model hasn't finished loading.
                if (mv.model) {
                    activate();
                } else {
                    mv.addEventListener('load', function onLoad() {
                        mv.removeEventListener('load', onLoad);
                        activate();
                    });
                }
            } catch (e) {
                console.error('AR activateAR() threw:', e);
            }

            var instanceId = arViewer.attr('data-ar-instance') || '';

            if (typeof window !== 'undefined' && window.ARAnalytics && typeof window.ARAnalytics.track === 'function') {
                window.ARAnalytics.track('ar_launch', {
                    pluginId: pluginId || (typeof window.ARAnalytics.getDefaultPluginId === 'function' ? window.ARAnalytics.getDefaultPluginId() : ''),
                    modelId: targetId || '',
                    instanceId: instanceId
                });
            }
          
        }
    });


    /*jQuery(document).on('click','button.ar-button', function(event){
        
        event.preventDefault();

        var id = jQuery(this).data('id');        
        var arViewer = jQuery('#model_' + id);
        var alt_glb = jQuery('#alt_glb_file_' + id).val();
        var alt_usdz = jQuery('#alt_usdz_file_' + id).val();

        var orig_glb = jQuery('#alt_glb_file_' + id).data('orig');
        var orig_usdz = jQuery('#alt_usdz_file_' + id).data('orig');

        //console.log('id - ' + id);
        //console.log(arViewer[0]);
        //console.log('alt-glb - ' + alt_glb);
        //console.log('alt-usdz - ' + alt_usdz);        
        //alert("HERE");

        arViewer.attr('src',alt_glb);
        arViewer.attr('ios-src',alt_usdz);

        if (arViewer[0].canActivateAR) {
		    // Programmatically enter AR mode
		    //arViewer.shadowRoot.querySelector('#default-exit-webxr-ar-button').addEventListener("click", function(){ alert("AR CLOSED") });

	    	arViewer[0].activateAR();



	    	//arViewer.attr('src',orig_glb);
        	//arViewer.attr('ios-src',orig_usdz);

	    	
	  	}
        
        return true;
        

    });*/
}); 