// Modified main aladin.js to use extension system
export async function initializeAladin(pContainerId, dotNetHelper, options = {}) {
    // Default options
    const defaults = {
        target: "10.6847 41.2692", // Default to M31
        fov: 2.0, // 1 degree FOV
        survey: "P/DSS2/color",
        showFov: false,
        fovWidth: 0,
        fovHeight: 0,
        fovRotation: 0
    };

    const settings = { ...defaults, ...options };
    const containerId = pContainerId;
    
    // Function to load a script
    const loadScript = (src) => {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = src;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
            document.head.appendChild(script);
        });
    };

    try {
        // Load Aladin Lite script if not already loaded
        if (!window.A) {
            try {
                await loadScript('https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js');
            } catch (e) {
                console.warn('Failed to load Aladin from official CDN, trying alternative source');
                try {
                    await loadScript('https://unpkg.com/aladin-lite@2.8.13/dist/aladin.js');
                } catch (e2) {
                    console.error('All script loading attempts failed');
                    throw new Error('Could not load Aladin Lite from any source');
                }
            }
            
            // Wait for A.aladin to be available
            await new Promise((resolve, reject) => {
                const startTime = Date.now();
                const checkAladin = () => {
                    if (window.A && window.A.aladin) {
                        resolve();
                    } else if (Date.now() - startTime > 10000) {
                        reject(new Error('Timeout waiting for Aladin to load'));
                    } else {
                        setTimeout(checkAladin, 100);
                    }
                };
                checkAladin();
            });
        }

        // Initialize Aladin
        const aladin = A.aladin(containerId, {
            target: settings.target,
            fov: settings.fov,
            survey: settings.survey,
            showReticle: true,
            showZoomControl: true,
            showLayersControl: true
        });

        // Set position angle to 0 at the bottom (like Telescopius)
        aladin.setRotation(0);
        aladin.setFrame('ICRS');

        // Create base aladin instance
        const aladinInstance = {
            aladin: aladin,
            markers: [],
            markerCatalog: null,
            showMarkerLabels: true,
            
            // Core functionality
            gotoRaDec: async function(ra, dec) {
                this.aladin.gotoRaDec(ra, dec);
                return Promise.resolve();
            },
            
            setFov: async function(fov) {
                this.aladin.setFov(fov);
                return Promise.resolve();
            },

            setSurvey: async function(survey) {
                this.aladin.setImageSurvey(survey);
                return Promise.resolve();
            },

            showGrid: function(show) {
                this.aladin.showGrid(show);
            },

            showReticle: function(show) {
                this.aladin.showReticle(show);
            },

            showConstellations: function(show) {
                this.aladin.showConstellations(show);
            }
        };

        // Load extensions
        if (window.AladinExtensions) {
            // Load UI extension
            await window.AladinExtensions.loadExtension('ui-controls', aladinInstance);
            
            // Load FOV extension
            await window.AladinExtensions.loadExtension('fov-overlays', aladinInstance);
            
            // Execute post-initialization hooks
            await window.AladinExtensions.executeHook('post-init', aladinInstance);
        }

        // Set up event listeners
        const positionChangedHandler = () => {
            // Execute position change hooks
            if (window.AladinExtensions) {
                window.AladinExtensions.executeHook('position-changed', aladinInstance);
            }
            
            // Update FOV overlays if extension is loaded
            if (aladinInstance.updateAllFovOverlayPositions) {
                aladinInstance.updateAllFovOverlayPositions();
            }
        };
        
        aladin.on('positionChanged', positionChangedHandler);
        aladin.on('zoomChanged', positionChangedHandler);

        // Object click handler
        aladin.on('objectClicked', (object) => {
            if (object) {
                aladin.gotoRaDec(object.ra, object.dec);
                
                if (object.data.objId && dotNetHelper) {
                    dotNetHelper.invokeMethodAsync('SelectDSO', object.data.objId)
                        .catch(err => console.error('Error selecting DSO:', err));
                }
            }
        });

        // Store global reference
        window.aladinInstance = aladinInstance;
        
        return aladinInstance;

    } catch (error) {
        console.error('Error initializing Aladin:', error);
        throw error;
    }
}
