// Marker Management Extension for Aladin
(function() {
    'use strict';

    const createMarkersExtension = (aladinInstance) => {
        return {
            markers: [],
            markerCatalog: null,
            labelPositions: [],
            hoveredLabelBounds: null,

            initialize: async function() {
                this.setupMarkerCanvas();
            },

            setupMarkerCanvas: function() {
                const aladinDiv = this.aladin.aladinDiv;
                if (!aladinDiv) return;

                // Create marker canvas if it doesn't exist
                let markerCanvas = aladinDiv.querySelector('.marker-overlay-canvas');
                if (!markerCanvas) {
                    markerCanvas = document.createElement('canvas');
                    markerCanvas.className = 'marker-overlay-canvas';
                    markerCanvas.style.position = 'absolute';
                    markerCanvas.style.top = '0';
                    markerCanvas.style.left = '0';
                    markerCanvas.style.pointerEvents = 'auto';
                    markerCanvas.style.zIndex = '15';
                    aladinDiv.appendChild(markerCanvas);

                    // Add click handler for marker interactions
                    markerCanvas.addEventListener('click', (e) => {
                        this.handleMarkerClick(e);
                    });
                }
            },

            // Add markers to the view
            addMarkers: function(markersData) {
                try {
                    if (!this.markerCatalog) {
                        this.markerCatalog = A.catalog();
                        this.aladin.addCatalog(this.markerCatalog);
                    }

                    // Clear existing markers
                    this.markerCatalog.removeAll();
                    this.markers = [];

                    markersData.forEach(markerData => {
                        const source = A.source(markerData.ra, markerData.dec, {
                            objId: markerData.objId,
                            label: markerData.label,
                            color: markerData.color || '#ff0000',
                            size: markerData.size || 10
                        });

                        this.markerCatalog.addSources([source]);
                        this.markers.push(source);
                    });

                } catch (error) {
                    console.error('Error adding markers:', error);
                }
            },

            // Remove all markers
            clearMarkers: function() {
                if (this.markerCatalog) {
                    this.markerCatalog.removeAll();
                }
                this.markers = [];
            },

            // Handle marker click events
            handleMarkerClick: function(event) {
                const rect = event.target.getBoundingClientRect();
                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;

                // Check if click is on a marker label
                for (const bounds of this.labelPositions) {
                    if (x >= bounds.x && x <= bounds.x + bounds.width &&
                        y >= bounds.y && y <= bounds.y + bounds.height) {
                        
                        if (bounds.source && bounds.source.data && bounds.source.data.objId) {
                            // Trigger marker selection
                            this.selectMarker(bounds.source.data.objId);
                        }
                        break;
                    }
                }
            },

            // Select a marker by ID
            selectMarker: function(objId) {
                // Add your marker selection logic here
            },

            // Update marker labels
            updateAllMarkerLabels: function() {
                if (!this.showMarkerLabels || !this.markers.length) return;

                const canvas = this.aladin.aladinDiv?.querySelector('.marker-overlay-canvas');
                if (!canvas) return;

                const ctx = canvas.getContext('2d');
                const rect = this.aladin.aladinDiv.getBoundingClientRect();
                
                canvas.width = rect.width;
                canvas.height = rect.height;
                ctx.clearRect(0, 0, canvas.width, canvas.height);

                this.labelPositions = [];

                this.markers.forEach(marker => {
                    if (marker.data && marker.data.label) {
                        this.drawMarkerLabel(ctx, marker);
                    }
                });
            },

            // Draw individual marker label
            drawMarkerLabel: function(ctx, marker) {
                try {
                    const xy = this.aladin.world2pix(marker.ra, marker.dec);
                    if (!xy || xy[0] < 0 || xy[1] < 0) return;

                    const x = xy[0];
                    const y = xy[1];
                    const label = marker.data.label;
                    const color = marker.data.color || '#ffffff';

                    // Set text style
                    ctx.fillStyle = color;
                    ctx.font = '12px Arial';
                    ctx.textAlign = 'left';
                    ctx.textBaseline = 'middle';

                    // Draw label with background
                    const textMetrics = ctx.measureText(label);
                    const padding = 4;
                    const bgX = x + 15;
                    const bgY = y - 8;
                    const bgWidth = textMetrics.width + padding * 2;
                    const bgHeight = 16;

                    // Draw background
                    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
                    ctx.fillRect(bgX - padding, bgY, bgWidth, bgHeight);

                    // Draw text
                    ctx.fillStyle = color;
                    ctx.fillText(label, bgX, bgY + bgHeight / 2);

                    // Store label bounds for click detection
                    this.labelPositions.push({
                        x: bgX - padding,
                        y: bgY,
                        width: bgWidth,
                        height: bgHeight,
                        source: marker
                    });

                } catch (error) {
                    console.error('Error drawing marker label:', error);
                }
            },

            // Toggle marker labels visibility
            toggleMarkerLabels: function() {
                this.showMarkerLabels = !this.showMarkerLabels;
                if (this.showMarkerLabels) {
                    this.updateAllMarkerLabels();
                } else {
                    const canvas = this.aladin.aladinDiv?.querySelector('.marker-overlay-canvas');
                    if (canvas) {
                        const ctx = canvas.getContext('2d');
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                    }
                }
            },

            // Set marker labels visibility
            setShowMarkerLabels: function(show) {
                this.showMarkerLabels = show;
                this.updateAllMarkerLabels();
            }
        };
    };

    // Register the extension
    if (window.AladinExtensions) {
        window.AladinExtensions.registerExtension('markers', createMarkersExtension);
    } else {
        console.error('AladinExtensions not found. Make sure aladin-core.js is loaded first.');
    }

})();
