// Temporarily stores control elements until IQNECT becomes available
window.IQLMControlElements = window.IQLMControlElements || [];

const IQLM_UI_BOOTSTRAP_URL_PREFERENCE = '/ai/iqnect/integration/windchill/uiBootstrapUrl';
const IQLM_DEFAULT_UI_BOOTSTRAP_URL = 'https://app.iqnect.ai/wc/bootstrap.js';

function IQLMLoadBootstrap() {
    if (window.IQLMBootstrapLoading) {
        return;
    }

    window.IQLMBootstrapLoading = true;

    let uiBootstrapUrl = IQLM_DEFAULT_UI_BOOTSTRAP_URL;
    if (window.PTC && window.PTC.util && typeof window.PTC.util.getPreference === 'function') {
        try {
            const value = window.PTC.util.getPreference(IQLM_UI_BOOTSTRAP_URL_PREFERENCE);
            if (value && value.trim()) {
                uiBootstrapUrl = value.trim();
            }
            else {
                console.warn('IQNECT: Windchill preference is empty, using default bootstrap URL.', IQLM_UI_BOOTSTRAP_URL_PREFERENCE);
            }
        }
        catch (error) {
            console.error('IQNECT: Failed to read Windchill preference, using default bootstrap URL.', IQLM_UI_BOOTSTRAP_URL_PREFERENCE, error);
        }
    }
    else {
        console.warn('IQNECT: PTC.util.getPreference is unavailable, using default bootstrap URL.');
    }

    const script = document.createElement('script');
    script.src = uiBootstrapUrl;
    script.onerror = function() {
        console.error('IQNECT: Failed to load Windchill widget bootstrap script.', uiBootstrapUrl);
    };
    document.body.appendChild(script);
}

class IQLMResourceActions extends HTMLElement {
    constructor() {
        super();
    }

    connectedCallback() {
        if (window.IQLMInitControl) {
            window.IQLMInitControl(this);
        }
        else {
            if (window.IQLMControlElements.indexOf(this) == -1) {
                window.IQLMControlElements.push(this);
            }
        }
    }

    disconnectedCallback() {
        const index = window.IQLMControlElements.indexOf(this);
        if (index != -1) {
            window.IQLMControlElements.splice(index, 1);
        }
    }
}

if (!customElements.get('iqlm-resource-actions')) {
    customElements.define('iqlm-resource-actions', IQLMResourceActions);
}

document.addEventListener('DOMContentLoaded', IQLMLoadBootstrap, { once: true });
