const DEMO_JQUERY_URL = 'https://code.jquery.com/jquery-1.12.1.min.js';
const DEMO_OPTIONS = {
    survey: 'P/DSS2/color',
    target: '10.6847083 41.26875',
    fov: 4
};
const DEFAULT_DEMO_VERSION = '3.6.5';
const KNOWN_DEMO_VERSIONS = new Set(['3.6.5', 'v3.7.1-beta']);

const demoInstances = new Map();

function getBuildUrl(version) {
    return `https://aladin.cds.unistra.fr/AladinLite/api/v3/${version}/aladin.js`;
}

function loadScript(url, isReady) {
    if (isReady()) {
        return Promise.resolve();
    }

    return new Promise((resolve, reject) => {
        const existing = Array.from(document.querySelectorAll('script')).find((script) => script.src === url);
        if (existing) {
            existing.addEventListener('load', () => resolve(), { once: true });
            existing.addEventListener('error', () => reject(new Error(`Failed to load script: ${url}`)), { once: true });
            return;
        }

        const script = document.createElement('script');
        script.src = url;
        script.async = true;
        script.charset = 'utf-8';
        script.addEventListener('load', () => resolve(), { once: true });
        script.addEventListener('error', () => reject(new Error(`Failed to load script: ${url}`)), { once: true });
        document.head.appendChild(script);
    });
}

function getPlatformLabel() {
    try {
        return `${navigator.platform || 'unknown'} | ${navigator.userAgent || 'unknown'}`;
    } catch {
        return 'unknown';
    }
}

function createBaseResult(version) {
    const effectiveVersion = KNOWN_DEMO_VERSIONS.has(version) ? version : DEFAULT_DEMO_VERSION;
    return {
        success: false,
        version: effectiveVersion,
        buildUrl: getBuildUrl(effectiveVersion),
        jqueryUrl: DEMO_JQUERY_URL,
        survey: DEMO_OPTIONS.survey,
        target: DEMO_OPTIONS.target,
        fov: DEMO_OPTIONS.fov,
        hasNamespace: !!window.A,
        hasAladinFactory: typeof window.A?.aladin === 'function',
        hasInitPromise: typeof window.A?.init?.then === 'function',
        message: 'Not initialized',
        hiddenAladinError: '',
        platform: getPlatformLabel(),
        userAgent: navigator.userAgent || ''
    };
}

function unloadExistingDemoBuild() {
    try {
        delete window.A;
        delete globalThis.A;
    } catch {
        window.A = undefined;
        globalThis.A = undefined;
    }

    document.querySelectorAll('script[data-am-aladin-demo="true"]').forEach((script) => {
        script.parentNode?.removeChild(script);
    });
}

export async function initializeAladinV3Demo(containerId, options = {}) {
    await destroyAladinV3Demo(containerId);

    const container = document.getElementById(containerId);
    if (!container) {
        throw new Error(`Demo container '${containerId}' was not found.`);
    }

    container.innerHTML = '';

    const version = KNOWN_DEMO_VERSIONS.has(options?.version) ? options.version : DEFAULT_DEMO_VERSION;
    const buildUrl = getBuildUrl(version);
    const result = createBaseResult(version);
    let hiddenAladinError = '';
    const originalConsoleError = console.error;

    try {
        unloadExistingDemoBuild();
        await loadScript(DEMO_JQUERY_URL, () => typeof window.jQuery === 'function');
        await loadScript(buildUrl, () => typeof window.A?.aladin === 'function');
        const loadedScript = Array.from(document.querySelectorAll('script')).find((script) => script.src === buildUrl);
        if (loadedScript) {
            loadedScript.dataset.amAladinDemo = 'true';
        }

        result.hasNamespace = !!window.A;
        result.hasAladinFactory = typeof window.A?.aladin === 'function';
        result.hasInitPromise = typeof window.A?.init?.then === 'function';

        if (!result.hasInitPromise) {
            throw new Error('A.init is not available after loading Aladin Lite.');
        }

        console.error = (...args) => {
            if (!hiddenAladinError) {
                hiddenAladinError = args.map((arg) => typeof arg === 'string' ? arg : JSON.stringify(arg)).join(' ');
            }

            originalConsoleError.apply(console, args);
        };

        await window.A.init;
        await new Promise((resolve) => requestAnimationFrame(resolve));
        await new Promise((resolve) => requestAnimationFrame(resolve));

        const aladin = window.A.aladin(`#${containerId}`, {
            survey: DEMO_OPTIONS.survey,
            target: DEMO_OPTIONS.target,
            fov: DEMO_OPTIONS.fov
        });

        demoInstances.set(containerId, aladin);

        result.success = true;
        result.message = 'Plain Aladin v3 demo initialized successfully.';
        result.hiddenAladinError = hiddenAladinError;
        return result;
    } catch (error) {
        result.success = false;
        result.message = error?.message || String(error);
        result.hiddenAladinError = hiddenAladinError;
        return result;
    } finally {
        console.error = originalConsoleError;
    }
}

export async function destroyAladinV3Demo(containerId) {
    const instance = demoInstances.get(containerId);
    demoInstances.delete(containerId);

    try {
        instance?.destroy?.();
    } catch {
        // Ignore teardown errors.
    }

    const container = document.getElementById(containerId);
    if (container) {
        container.innerHTML = '';
    }
}
