// Aladin Lite Extensions - Custom UI components and utilities
// Provides helper functions for adding custom buttons and UI elements to Aladin viewer

/**
 * Adds a custom button to the Aladin viewer
 * @param {Object} aladin - The Aladin instance
 * @param {Object} options - Button configuration options
 * @param {string} options.content - Button text/HTML content
 * @param {string[]} options.classList - CSS classes to apply to the button
 * @param {Object} options.tooltip - Tooltip configuration
 * @param {string} options.tooltip.content - Tooltip text
 * @param {string} options.tooltip.position - Tooltip position ('top', 'bottom', 'left', 'right')
 * @param {Object} options.tooltip.cssStyle - Custom CSS styles for tooltip
 * @param {Function} options.action - Click handler function
 * @returns {Object} The created button element
 */

/**
 * Creates a polygon selection button for MOC creation
 * @param {Object} aladin - The Aladin instance
 * @param {Object} options - Configuration options
 * @param {string} options.mocName - Name for the created MOC
 * @param {string} options.mocColor - Color for the MOC
 * @param {number} options.lineWidth - Line width for the MOC
 * @param {Function} options.onMocCreated - Callback when MOC is created
 * @returns {Object} The created button element
 */
window.addPolygonSelectionButton = function(aladin, options = {}) {
    const config = {
        mocName: options.mocName || 'Selection',
        mocColor: options.mocColor || 'pink',
        lineWidth: options.lineWidth || 3.0,
        onMocCreated: options.onMocCreated || function(moc) { }
    };

    return window.addAladinButton(aladin, {
        content: options.buttonText || 'Select Region',
        classList: ['polygon-selection-btn'],
        tooltip: {
            cssStyle: { color: 'blue' },
            content: 'Click to select a polygon region and create a MOC',
            position: { direction: 'top' }
        },
        action: function(o) {
            aladin.select('poly', p => {
                try {
                    let ra = [];
                    let dec = [];
                    
                    for (const v of p.vertices) {
                        let [lon, lat] = aladin.pix2world(v.x, v.y);
                        ra.push(lon);
                        dec.push(lat);
                    }

                    let moc = A.MOCFromPolygon(
                        { ra, dec },
                        { 
                            name: config.mocName, 
                            lineWidth: config.lineWidth, 
                            color: config.mocColor 
                        }
                    );
                    
                    aladin.addMOC(moc);
                    config.onMocCreated(moc);
                } catch (error) {
                    console.error('Error creating MOC from polygon:', error);
                    alert('Selection covers a region out of the projection definition domain.');
                }
            });
        }
    });
};

/**
 * Creates a survey switcher button
 * @param {Object} aladin - The Aladin instance
 * @param {string[]} surveys - Array of survey names to cycle through
 * @returns {Object} The created button element
 */
window.addSurveySwitcherButton = function(aladin, surveys = ['https://alasky.cds.unistra.fr/DSS/DSSColor', 'CDS/P/allWISE/color', 'CDS/P/2MASS/color']) {
    let currentSurveyIndex = 0;

    return window.addAladinButton(aladin, {
        content: 'Survey',
        classList: ['survey-switcher-btn'],
        tooltip: {
            cssStyle: { color: 'green' },
            content: 'Switch between different sky surveys',
            position: { direction: 'top' }
        },
        action: function() {
            currentSurveyIndex = (currentSurveyIndex + 1) % surveys.length;
            const newSurvey = surveys[currentSurveyIndex];
            aladin.setImageSurvey(newSurvey);
        }
    });
};

/**
 * Creates a field of view reset button
 * @param {Object} aladin - The Aladin instance
 * @param {number} defaultFov - Default field of view in degrees
 * @returns {Object} The created button element
 */
window.addFovResetButton = function(aladin, defaultFov = 1.5) {
    return window.addAladinButton(aladin, {
        content: 'Reset FOV',
        classList: ['fov-reset-btn'],
        tooltip: {
            cssStyle: { color: 'orange' },
            content: `Reset field of view to ${defaultFov}°`,
            position: { direction: 'top' }
        },
        action: function() {
            aladin.setFoV(defaultFov);
        }
    });
};

/**
 * Creates a coordinate display toggle button
 * @param {Object} aladin - The Aladin instance
 * @returns {Object} The created button element
 */
window.addCoordinateToggleButton = function(aladin) {
    let showCoordinates = true;

    return window.addAladinButton(aladin, {
        content: 'Coords',
        classList: ['coordinate-toggle-btn'],
        tooltip: {
            cssStyle: { color: 'purple' },
            content: 'Toggle coordinate display',
            position: { direction: 'top' }
        },
        action: function() {
            showCoordinates = !showCoordinates;
            aladin.showReticle(showCoordinates);
        }
    });
};

/**
 * Creates a fullscreen toggle button
 * @param {Object} aladin - The Aladin instance
 * @param {string} containerId - ID of the container element
 * @returns {Object} The created button element
 */
window.addFullscreenButton = function(aladin, containerId = 'aladin-lite-div') {
    return window.addAladinButton(aladin, {
        content: 'Fullscreen',
        classList: ['fullscreen-btn'],
        tooltip: {
            cssStyle: { color: 'red' },
            content: 'Toggle fullscreen mode',
            position: { direction: 'top' }
        },
        action: function() {
            const container = document.getElementById(containerId);
            if (container) {
                if (!document.fullscreenElement) {
                    container.requestFullscreen().catch(err => {
                        console.error('Error attempting to enable fullscreen:', err);
                    });
                } else {
                    document.exitFullscreen();
                }
            }
        }
    });
};

/**
 * Example usage function - demonstrates how to use the extension functions
 * @param {Object} aladin - The Aladin instance
 */
window.addExampleButtons = function(aladin) {
    // Add polygon selection button
    window.addPolygonSelectionButton(aladin, {
        mocName: 'My Selection',
        mocColor: 'cyan',
        lineWidth: 2.0,
        buttonText: 'Select Area',
        onMocCreated: function(moc) {
            // You can add custom logic here when a MOC is created
        }
    });

    // Add survey switcher
    window.addSurveySwitcherButton(aladin, ['CDS/P/DSS2/color', 'CDS/P/allWISE/color', 'CDS/P/2MASS/color', 'CDS/P/Fermi/color']);

    // Add FOV reset button
    window.addFovResetButton(aladin, 1.5);

    // Add coordinate toggle
    window.addCoordinateToggleButton(aladin);

    // Add fullscreen button
    window.addFullscreenButton(aladin, 'aladin-lite-div');
};

// Aladin Extensions loaded
