/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Stage Fullscreen Module
 * Handles fullscreen toggle for the content block stage.
 * 
 * Responsibilities:
 *  - Enter/exit fullscreen mode
 *  - Keyboard shortcut handling (F11, Escape)
 *  - Notify viewport to reapply scale on fullscreen change
 */

/**
 * FullscreenManager - handles fullscreen mode for the stage
 */
export class FullscreenManager {
    constructor(options = {}) {
        this.containerSelector = options.containerSelector || '#block-stage-wrapper';
        this.buttonSelector = options.buttonSelector || '#ccve-fullscreen-btn';
        this.fullscreenClass = options.fullscreenClass || 'ccve-fullscreen-active';
        
        // Callbacks
        this.onEnter = options.onEnter || null;
        this.onExit = options.onExit || null;
        
        // State
        this._isFullscreen = false;
        this._boundHandleFullscreenChange = null;
        this._boundHandleKeydown = null;
    }
    
    /**
     * Initialize fullscreen handling
     */
    init() {
        // Bind event handlers
        this._boundHandleFullscreenChange = this._handleFullscreenChange.bind(this);
        this._boundHandleKeydown = this._handleKeydown.bind(this);
        
        // Listen for fullscreen changes
        document.addEventListener('fullscreenchange', this._boundHandleFullscreenChange);
        document.addEventListener('webkitfullscreenchange', this._boundHandleFullscreenChange);
        
        // Listen for keyboard shortcuts
        document.addEventListener('keydown', this._boundHandleKeydown);
        
        // Setup button click
        this._setupButton();
        
        console.debug('[FullscreenManager] Initialized');
        return true;
    }
    
    /**
     * Setup fullscreen button
     */
    _setupButton() {
        const btn = document.querySelector(this.buttonSelector);
        if (!btn) return;
        
        btn.addEventListener('click', (e) => {
            e.preventDefault();
            this.toggle();
        });
        
        // Update button state
        this._updateButtonState();
    }
    
    /**
     * Handle fullscreen change events
     */
    _handleFullscreenChange() {
        const wasFullscreen = this._isFullscreen;
        this._isFullscreen = !!document.fullscreenElement || !!document.webkitFullscreenElement;
        
        // Update UI
        const container = document.querySelector(this.containerSelector);
        if (container) {
            container.classList.toggle(this.fullscreenClass, this._isFullscreen);
        }
        
        this._updateButtonState();
        
        // Fire callbacks
        if (this._isFullscreen && !wasFullscreen && this.onEnter) {
            this.onEnter();
        } else if (!this._isFullscreen && wasFullscreen && this.onExit) {
            this.onExit();
        }
        
        console.debug('[FullscreenManager] Fullscreen:', this._isFullscreen);
    }
    
    /**
     * Handle keyboard shortcuts
     */
    _handleKeydown(e) {
        // F11 to toggle fullscreen (prevent default browser behavior)
        if (e.key === 'F11') {
            e.preventDefault();
            this.toggle();
            return;
        }
        
        // Escape to exit fullscreen (browser handles this, but we track state)
        if (e.key === 'Escape' && this._isFullscreen) {
            // Let browser handle the exit
            return;
        }
    }
    
    /**
     * Update button visual state
     */
    _updateButtonState() {
        const btn = document.querySelector(this.buttonSelector);
        if (!btn) return;
        
        btn.setAttribute('aria-pressed', this._isFullscreen ? 'true' : 'false');
        btn.title = this._isFullscreen ? 'Exit Fullscreen' : 'Fullscreen';
        
        // Update icon if button has icon element
        const icon = btn.querySelector('.ccve-fullscreen-icon');
        if (icon) {
            icon.textContent = this._isFullscreen ? '⛶' : '⛶';
        }
    }
    
    /**
     * Enter fullscreen mode
     */
    async enter() {
        const container = document.querySelector(this.containerSelector);
        if (!container) {
            console.warn('[FullscreenManager] Container not found');
            return false;
        }
        
        try {
            if (container.requestFullscreen) {
                await container.requestFullscreen();
            } else if (container.webkitRequestFullscreen) {
                await container.webkitRequestFullscreen();
            } else {
                console.warn('[FullscreenManager] Fullscreen API not supported');
                return false;
            }
            return true;
        } catch (e) {
            console.warn('[FullscreenManager] Failed to enter fullscreen:', e);
            return false;
        }
    }
    
    /**
     * Exit fullscreen mode
     */
    async exit() {
        try {
            if (document.exitFullscreen) {
                await document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
                await document.webkitExitFullscreen();
            }
            return true;
        } catch (e) {
            console.warn('[FullscreenManager] Failed to exit fullscreen:', e);
            return false;
        }
    }
    
    /**
     * Toggle fullscreen mode
     */
    async toggle() {
        if (this._isFullscreen) {
            return this.exit();
        } else {
            return this.enter();
        }
    }
    
    /**
     * Check if currently in fullscreen
     */
    isFullscreen() {
        return this._isFullscreen;
    }
    
    /**
     * Cleanup
     */
    destroy() {
        if (this._boundHandleFullscreenChange) {
            document.removeEventListener('fullscreenchange', this._boundHandleFullscreenChange);
            document.removeEventListener('webkitfullscreenchange', this._boundHandleFullscreenChange);
        }
        if (this._boundHandleKeydown) {
            document.removeEventListener('keydown', this._boundHandleKeydown);
        }
        console.debug('[FullscreenManager] Destroyed');
    }
}

/**
 * Factory function for easy instantiation
 */
export function createFullscreenManager(options = {}) {
    return new FullscreenManager(options);
}
