/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Stage Viewport Module - FIXED DIMENSIONS APPROACH
 * 
 * DESIGN PHILOSOPHY:
 * This module uses the EXACT same approach as Scenes & Containers stage:
 * - Fixed viewport dimensions: 960×540 pixels (hardcoded, NOT responsive)
 * - Fixed scale: 0.75 (960/1280 = 540/720 = 0.75)
 * - The 1280×720 canvas is scaled down uniformly to fit
 * 
 * Reference: scenes-stage.css
 *   #cc-scenes-stage .cc-stage-viewport { width: 960px; height: 540px; }
 *   #cc-scenes-stage .cc-stage-canvas { width: 1280px; height: 720px; transform: scale(0.75); }
 * 
 * This ensures BOTH stages look IDENTICAL regardless of browser width,
 * DevTools position, or WordPress admin sidebar state.
 * 
 * CRITICAL SCALING CHAIN:
 * 1. Authoring: 1280×720 (logical pixels)
 * 2. Content Block Stage: 960×540 viewport, scale 0.75 (THIS FILE)
 * 3. Scenes & Containers Stage: 960×540 viewport, scale 0.75 (scenes-stage.css)
 * 4. Roku Render: 1280×720 or 1920×1080 (maintains aspect ratio)
 */

/** 
 * Authoring dimensions (Roku Safe Zone)
 */
export const AUTHORING_WIDTH = 1280;
export const AUTHORING_HEIGHT = 720;
export const ASPECT_RATIO = AUTHORING_WIDTH / AUTHORING_HEIGHT; // 16:9

/**
 * FIXED viewport dimensions - MUST match Scenes & Containers stage exactly
 * See: scenes-stage.css #cc-scenes-stage .cc-stage-viewport
 * 
 * DO NOT CHANGE THESE - they match the Scenes & Containers stage
 */
export const VIEWPORT_WIDTH = 960;
export const VIEWPORT_HEIGHT = 540;
export const FIXED_SCALE = VIEWPORT_WIDTH / AUTHORING_WIDTH; // 0.75

/**
 * Viewport state - read-only snapshot of current scaling
 */
export class ViewportState {
    constructor(fitScale, appliedScale, relativeZoom) {
        this.fitScale = fitScale;
        this.appliedScale = appliedScale;
        this.relativeZoom = relativeZoom;
        this.logicalWidth = AUTHORING_WIDTH;
        this.logicalHeight = AUTHORING_HEIGHT;
        this.visualWidth = VIEWPORT_WIDTH;
        this.visualHeight = VIEWPORT_HEIGHT;
    }
}

/**
 * StageViewport - FIXED DIMENSIONS SCALING
 * 
 * Uses FIXED 960×540 viewport with 0.75 scale, exactly matching Scenes & Containers.
 * NO responsive calculations - always the same size regardless of browser/DevTools.
 */
export class StageViewport {
    constructor(options = {}) {
        this.frameSelector = options.frameSelector || '#block-stage-wrapper';
        this.hostClass = options.hostClass || 'ccve-scale-host';
        this.stageOuterClass = options.stageOuterClass || 'ccve-stage-outer';
        
        // Fixed scale - no calculation needed
        this._fitScale = FIXED_SCALE;
        this._relativeZoom = 1;
        this._appliedScale = FIXED_SCALE;
        
        this.onScaleChange = options.onScaleChange || null;
        this.onResize = options.onResize || null;
        this.debugMode = options.debugMode || false;
    }
    
    /**
     * Initialize the viewport with FIXED dimensions
     */
    init() {
        console.log('[StageViewport] FIXED DIMENSIONS Init - 960x540 @ 0.75 scale');
        
        const frame = document.querySelector(this.frameSelector);
        if (!frame) {
            console.warn('[StageViewport] Frame not found:', this.frameSelector);
            return false;
        }
        
        // Apply FIXED dimensions to the frame (matches scenes-stage.css)
        this._applyFixedStyling(frame);
        
        // Ensure scale host exists
        const host = this._ensureScaleHost(frame);
        if (!host) {
            console.warn('[StageViewport] Could not create scale host');
            return false;
        }
        
        // Apply the fixed scale (one-time, no recalculation needed)
        this.applyScale();
        
        console.log('[StageViewport] FIXED DIMENSIONS Initialized - 960x540 @ 0.75');
        return true;
    }
    
    /**
     * Apply FIXED dimensions styling to the frame container
     * This matches scenes-stage.css exactly - NOT responsive
     */
    _applyFixedStyling(frame) {
        // FIXED dimensions - NOT responsive
        // This MUST match: #cc-scenes-stage .cc-stage-viewport { width: 960px; height: 540px; }
        frame.style.width = VIEWPORT_WIDTH + 'px';
        frame.style.height = VIEWPORT_HEIGHT + 'px';
        frame.style.margin = '0 auto'; // Center horizontally
        frame.style.position = 'relative';
        frame.style.overflow = 'visible'; // Allow rulers outside
        frame.style.background = '#0b1220';
        frame.style.borderRadius = '10px';
        
        // CRITICAL: Remove any responsive properties that might interfere
        frame.style.maxWidth = '';
        frame.style.aspectRatio = '';
        
        console.log(`[StageViewport] FIXED styling: ${VIEWPORT_WIDTH}x${VIEWPORT_HEIGHT}px`);
    }
    
    /**
     * Ensure scale host wrapper exists
     */
    _ensureScaleHost(frame) {
        let host = frame.querySelector(`.${this.hostClass}`);
        if (host) return host;
        
        let stageOuter = frame.querySelector(`.${this.stageOuterClass}`);
        if (!stageOuter) {
            const legacyStage = frame.querySelector('#block-stage');
            if (legacyStage) {
                stageOuter = document.createElement('div');
                stageOuter.className = this.stageOuterClass;
                legacyStage.parentNode.insertBefore(stageOuter, legacyStage);
                stageOuter.appendChild(legacyStage);
            }
        }
        
        if (!stageOuter) return null;
        
        host = document.createElement('div');
        host.className = this.hostClass;
        
        // The host contains the 1280×720 stage at logical size
        // CSS transform will scale it down to 960×540 visually
        host.style.width = AUTHORING_WIDTH + 'px';
        host.style.height = AUTHORING_HEIGHT + 'px';
        host.style.transformOrigin = 'top left';
        host.style.position = 'absolute';
        host.style.top = '0';
        host.style.left = '0';
        
        frame.insertBefore(host, frame.firstChild);
        host.appendChild(stageOuter);
        
        return host;
    }
    
    /**
     * Apply the FIXED scale transform
     * 
     * FIXED DIMENSIONS approach:
     * - Scale is always 0.75 (matches Scenes & Containers)
     * - No responsive calculation
     * - Only debug mode zoom modifies the scale
     */
    applyScale(forceRecalc = false) {
        const frame = document.querySelector(this.frameSelector);
        if (!frame) return;
        
        const host = frame.querySelector(`.${this.hostClass}`);
        if (!host) return;
        
        // Apply relative zoom (debug mode only)
        const relZoom = this.debugMode ? this._relativeZoom : 1;
        const appliedScale = FIXED_SCALE * relZoom;
        
        // Update state
        this._fitScale = FIXED_SCALE;
        this._appliedScale = appliedScale;
        
        // Apply transform to scale host
        host.style.transform = `scale(${appliedScale})`;
        
        // Data attributes for debugging
        frame.setAttribute('data-fit-scale', FIXED_SCALE.toFixed(4));
        frame.setAttribute('data-applied-scale', appliedScale.toFixed(4));
        frame.setAttribute('data-viewport-size', `${VIEWPORT_WIDTH}x${VIEWPORT_HEIGHT}`);
        
        // Notify listeners
        if (this.onScaleChange) {
            this.onScaleChange(this.getState());
        }
        
        console.log('[StageViewport] FIXED Scale Applied:', {
            viewportSize: `${VIEWPORT_WIDTH}x${VIEWPORT_HEIGHT}`,
            fixedScale: FIXED_SCALE.toFixed(4),
            appliedScale: appliedScale.toFixed(4)
        });
    }
    
    /**
     * Set relative zoom (debug mode only)
     */
    setRelativeZoom(zoom) {
        this._relativeZoom = Math.max(0.35, Math.min(1.0, zoom));
        if (this.debugMode) {
            this.applyScale(true);
            try { localStorage.setItem('ccveBlockStageZoomRel', String(this._relativeZoom)); } catch(_) {}
        }
    }
    
    getRelativeZoom() { return this._relativeZoom; }
    getState() { return new ViewportState(this._fitScale, this._appliedScale, this._relativeZoom); }
    getScale() { return this._appliedScale; }
    getFitScale() { return this._fitScale; }
    
    /**
     * Convert screen coordinates to logical (1280×720) coordinates
     */
    screenToLogical(screenX, screenY) {
        const scale = this._appliedScale || FIXED_SCALE;
        return {
            x: Math.round(screenX / scale),
            y: Math.round(screenY / scale)
        };
    }
    
    /**
     * Convert logical coordinates to screen coordinates
     */
    logicalToScreen(logicalX, logicalY) {
        const scale = this._appliedScale || FIXED_SCALE;
        return {
            x: Math.round(logicalX * scale),
            y: Math.round(logicalY * scale)
        };
    }
    
    isWithinBounds(x, y) {
        return x >= 0 && x <= AUTHORING_WIDTH && y >= 0 && y <= AUTHORING_HEIGHT;
    }
    
    enableDebugMode() {
        this.debugMode = true;
        try {
            const stored = parseFloat(localStorage.getItem('ccveBlockStageZoomRel'));
            if (!isNaN(stored) && stored > 0) this._relativeZoom = Math.min(stored, 1);
        } catch(_) {}
        this.applyScale(true);
    }
    
    disableDebugMode() {
        this.debugMode = false;
        this._relativeZoom = 1;
        try { localStorage.setItem('ccveBlockStageZoomRel', '1'); } catch(_) {}
        this.applyScale(true);
    }
    
    destroy() {
        // No resize observer to clean up - fixed dimensions don't need it
        console.log('[StageViewport] Destroyed');
    }
}

export function createStageViewport(options = {}) {
    return new StageViewport(options);
}

export const ZOOM_STEPS = [35, 50, 60, 75, 90, 100];

export function getZoomOptions() {
    return ZOOM_STEPS.map(pct => ({
        value: pct,
        label: `${pct}%`,
        scale: pct / 100
    }));
}
