// FOV Overlay Extension for Aladin
// This extends the main aladin object with FOV overlay functionality

(function() {
    'use strict';

    // FOV Extension Factory
    const createFovExtension = (aladinInstance) => {
        return {
            // FOV overlay specific properties
            fovOverlays: [],
            fovOverlayElements: new Map(),

            // Initialize FOV extension
            initialize: async function() {
                this.setupFovOverlayCanvas();
            },

            // Setup canvas for FOV overlays
            setupFovOverlayCanvas: function() {
                const aladinDiv = this.aladin.aladinDiv;
                if (!aladinDiv) return;

                // Create overlay canvas if it doesn't exist
                let overlayCanvas = aladinDiv.querySelector('.fov-overlay-canvas');
                if (!overlayCanvas) {
                    overlayCanvas = document.createElement('canvas');
                    overlayCanvas.className = 'fov-overlay-canvas';
                    overlayCanvas.style.position = 'absolute';
                    overlayCanvas.style.top = '0';
                    overlayCanvas.style.left = '0';
                    overlayCanvas.style.pointerEvents = 'none';
                    overlayCanvas.style.zIndex = '10';
                    aladinDiv.appendChild(overlayCanvas);
                }
            },

            // Update FOV overlays
            updateFovOverlays: function(overlayData) {
                this.fovOverlays = overlayData || [];
                this.renderFovOverlays();
            },

            // Render FOV overlays on canvas
            renderFovOverlays: function() {
                const aladinDiv = this.aladin.aladinDiv;
                const overlayCanvas = aladinDiv?.querySelector('.fov-overlay-canvas');
                if (!overlayCanvas) return;

                const ctx = overlayCanvas.getContext('2d');
                const rect = aladinDiv.getBoundingClientRect();
                
                // Set canvas size
                overlayCanvas.width = rect.width;
                overlayCanvas.height = rect.height;
                
                // Clear canvas
                ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height);

                // Render each overlay
                this.fovOverlays.forEach(overlay => {
                    if (overlay.isVisible) {
                        this.drawFovOverlay(ctx, overlay);
                    }
                });
            },

            // Draw individual FOV overlay
            drawFovOverlay: function(ctx, overlay) {
                try {
                    // Get current view center
                    const center = this.aladin.getRaDec();
                    const fov = this.aladin.getFov();
                    
                    if (!center || !fov) return;

                    // Calculate overlay position and size
                    const overlayPos = this.calculateOverlayPosition(overlay, center, fov);
                    if (!overlayPos) return;

                    // Draw the overlay rectangle
                    ctx.strokeStyle = overlay.color || '#ff0000';
                    ctx.lineWidth = 2;
                    ctx.setLineDash([5, 5]);
                    
                    ctx.strokeRect(
                        overlayPos.x - overlayPos.width / 2,
                        overlayPos.y - overlayPos.height / 2,
                        overlayPos.width,
                        overlayPos.height
                    );
                    
                    // Draw label
                    ctx.fillStyle = overlay.color || '#ff0000';
                    ctx.font = '12px Arial';
                    ctx.fillText(
                        overlay.name || 'FOV',
                        overlayPos.x - overlayPos.width / 2,
                        overlayPos.y - overlayPos.height / 2 - 5
                    );
                    
                } catch (error) {
                    console.error('Error drawing FOV overlay:', error);
                }
            },

            // Calculate overlay screen position
            calculateOverlayPosition: function(overlay, center, fov) {
                // This is a simplified calculation - you may need more complex math
                // for accurate positioning based on your coordinate system
                const canvas = this.aladin.view.imageCanvas;
                if (!canvas) return null;

                // Convert arcminutes to degrees
                const widthDeg = overlay.widthArcmin / 60;
                const heightDeg = overlay.heightArcmin / 60;
                
                // Calculate pixel size based on current FOV
                const pixelsPerDegree = canvas.width / fov[0];
                
                return {
                    x: canvas.width / 2,  // Center for now
                    y: canvas.height / 2,
                    width: widthDeg * pixelsPerDegree,
                    height: heightDeg * pixelsPerDegree
                };
            },

            // Update overlay positions when view changes
            updateAllFovOverlayPositions: function() {
                this.renderFovOverlays();
            }
        };
    };

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

})();
