/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Stage Rulers Module (Refactored)
 * Overlay rulers that position OUTSIDE the stage canvas.
 * 
 * Key Design Decision:
 *  - Rulers use NEGATIVE positioning (top: -24px, left: -24px)
 *  - Host and stage dimensions are NOT modified
 *  - Rulers are purely visual overlay, do NOT affect layout
 *  - CSS handles ruler positioning, JS handles tick rendering
 * 
 * Responsibilities:
 *  - Create ruler DOM elements
 *  - Render tick marks at logical coordinates
 *  - Show/hide rulers
 *  - Update tick positions when bounds change
 */

import { AUTHORING_WIDTH, AUTHORING_HEIGHT } from './stage-viewport.js';

/** Default ruler thickness (matches CSS variable) */
const DEFAULT_THICKNESS = 24;

/**
 * Get ruler thickness from CSS variable
 */
function getRulerThickness() {
    try {
        const cs = getComputedStyle(document.documentElement);
        const value = parseInt(cs.getPropertyValue('--ccve-ruler-thickness') || '24', 10);
        return Number.isFinite(value) && value > 0 ? value : DEFAULT_THICKNESS;
    } catch (_) {
        return DEFAULT_THICKNESS;
    }
}

/**
 * StageRulers - manages overlay rulers for the content block stage
 */
export class StageRulers {
    constructor(options = {}) {
        // Configuration
        this.hostSelector = options.hostSelector || '.ccve-scale-host';
        this.stageSelector = options.stageSelector || '.ccve-stage-outer';
        
        // Tick rendering options
        this.minorStep = options.minorStep || 20;
        this.majorStep = options.majorStep || 100;
        
        // Logical dimensions (authoring space)
        this.logicalW = options.logicalW || AUTHORING_WIDTH;
        this.logicalH = options.logicalH || AUTHORING_HEIGHT;
        
        // DOM references
        this._horizontal = null;
        this._vertical = null;
        this._corner = null;
        
        // State
        this._visible = true;
        this._initialized = false;
    }
    
    /**
     * Initialize rulers - create DOM elements
     * @param {HTMLElement} frame - The frame element (block-stage-wrapper)
     */
    init(frame) {
        if (!frame) {
            console.warn('[StageRulers] Frame element required');
            return false;
        }
        
        // Find or wait for scale host
        let host = frame.querySelector(this.hostSelector);
        if (!host) {
            console.warn('[StageRulers] Scale host not found, rulers not initialized');
            return false;
        }
        
        // Create ruler elements if they don't exist
        this._horizontal = host.querySelector('.ccve-ruler-horizontal');
        this._vertical = host.querySelector('.ccve-ruler-vertical');
        this._corner = host.querySelector('.ccve-ruler-corner');
        
        if (!this._horizontal) {
            this._horizontal = document.createElement('div');
            this._horizontal.className = 'ccve-ruler-horizontal';
            host.appendChild(this._horizontal);
        }
        
        if (!this._vertical) {
            this._vertical = document.createElement('div');
            this._vertical.className = 'ccve-ruler-vertical';
            host.appendChild(this._vertical);
        }
        
        if (!this._corner) {
            this._corner = document.createElement('div');
            this._corner.className = 'ccve-ruler-corner';
            host.appendChild(this._corner);
        }
        
        // Apply base styles (CSS handles positioning via negative margins)
        this._applyBaseStyles();
        
        // Render tick marks
        this.renderTicks();
        
        this._initialized = true;
        console.debug('[StageRulers] Initialized');
        return true;
    }
    
    /**
     * Apply base styles to ruler elements
     * Note: Actual positioning is handled by CSS using negative top/left
     */
    _applyBaseStyles() {
        const thickness = getRulerThickness();
        
        // Horizontal ruler - positions via CSS
        if (this._horizontal) {
            this._horizontal.style.position = 'absolute';
            this._horizontal.style.pointerEvents = 'none';
            this._horizontal.style.zIndex = '50';
            this._horizontal.style.width = this.logicalW + 'px';
            this._horizontal.style.height = thickness + 'px';
        }
        
        // Vertical ruler - positions via CSS
        if (this._vertical) {
            this._vertical.style.position = 'absolute';
            this._vertical.style.pointerEvents = 'none';
            this._vertical.style.zIndex = '50';
            this._vertical.style.width = thickness + 'px';
            this._vertical.style.height = this.logicalH + 'px';
        }
        
        // Corner piece
        if (this._corner) {
            this._corner.style.position = 'absolute';
            this._corner.style.pointerEvents = 'none';
            this._corner.style.zIndex = '51';
            this._corner.style.width = thickness + 'px';
            this._corner.style.height = thickness + 'px';
        }
    }
    
    /**
     * Render tick marks on rulers
     */
    renderTicks() {
        if (!this._horizontal || !this._vertical) return;
        
        // Clear existing ticks
        this._horizontal.innerHTML = '';
        this._vertical.innerHTML = '';
        
        // Horizontal ruler ticks
        for (let x = 0; x <= this.logicalW; x += this.minorStep) {
            const isMajor = x % this.majorStep === 0;
            
            const tick = document.createElement('div');
            tick.className = 'ccve-ruler-tick';
            tick.style.position = 'absolute';
            tick.style.left = x + 'px';
            tick.style.bottom = '0';
            tick.style.width = '1px';
            tick.style.height = isMajor ? '100%' : '45%';
            tick.style.background = 'currentColor';
            tick.style.opacity = isMajor ? '0.6' : '0.3';
            this._horizontal.appendChild(tick);
            
            // Major tick labels
            if (isMajor) {
                const label = document.createElement('div');
                label.className = 'ccve-ruler-label';
                label.textContent = String(x);
                label.style.position = 'absolute';
                label.style.left = (x + 2) + 'px';
                label.style.top = '2px';
                label.style.fontSize = '9px';
                label.style.lineHeight = '1';
                label.style.color = 'currentColor';
                label.style.opacity = '0.7';
                this._horizontal.appendChild(label);
            }
        }
        
        // Vertical ruler ticks
        for (let y = 0; y <= this.logicalH; y += this.minorStep) {
            const isMajor = y % this.majorStep === 0;
            
            const tick = document.createElement('div');
            tick.className = 'ccve-ruler-tick';
            tick.style.position = 'absolute';
            tick.style.top = y + 'px';
            tick.style.right = '0';
            tick.style.height = '1px';
            tick.style.width = isMajor ? '100%' : '45%';
            tick.style.background = 'currentColor';
            tick.style.opacity = isMajor ? '0.6' : '0.3';
            this._vertical.appendChild(tick);
            
            // Major tick labels
            if (isMajor) {
                const label = document.createElement('div');
                label.className = 'ccve-ruler-label';
                label.textContent = String(y);
                label.style.position = 'absolute';
                label.style.top = (y + 2) + 'px';
                label.style.left = '2px';
                label.style.fontSize = '9px';
                label.style.lineHeight = '1';
                label.style.color = 'currentColor';
                label.style.opacity = '0.7';
                this._vertical.appendChild(label);
            }
        }
    }
    
    /**
     * Update logical bounds and re-render ticks
     * @param {number} w - New logical width
     * @param {number} h - New logical height
     */
    updateBounds(w, h) {
        if (typeof w === 'number') this.logicalW = w;
        if (typeof h === 'number') this.logicalH = h;
        
        this._applyBaseStyles();
        this.renderTicks();
    }
    
    /**
     * Show rulers
     */
    show() {
        this._visible = true;
        if (this._horizontal) this._horizontal.style.visibility = 'visible';
        if (this._vertical) this._vertical.style.visibility = 'visible';
        if (this._corner) this._corner.style.visibility = 'visible';
        
        // Add class to host for CSS targeting
        const host = this._horizontal?.closest('.ccve-scale-host');
        if (host) host.classList.add('rulers-active');
    }
    
    /**
     * Hide rulers
     */
    hide() {
        this._visible = false;
        if (this._horizontal) this._horizontal.style.visibility = 'hidden';
        if (this._vertical) this._vertical.style.visibility = 'hidden';
        if (this._corner) this._corner.style.visibility = 'hidden';
        
        // Remove class from host
        const host = this._horizontal?.closest('.ccve-scale-host');
        if (host) host.classList.remove('rulers-active');
    }
    
    /**
     * Toggle ruler visibility
     * @returns {boolean} New visibility state
     */
    toggle() {
        if (this._visible) {
            this.hide();
        } else {
            this.show();
        }
        return this._visible;
    }
    
    /**
     * Check if rulers are visible
     */
    isVisible() {
        return this._visible;
    }
    
    /**
     * Cleanup
     */
    destroy() {
        if (this._horizontal) this._horizontal.remove();
        if (this._vertical) this._vertical.remove();
        if (this._corner) this._corner.remove();
        
        this._horizontal = null;
        this._vertical = null;
        this._corner = null;
        this._initialized = false;
        
        console.debug('[StageRulers] Destroyed');
    }
}

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

/**
 * Legacy compatibility - init function that matches old API
 * @deprecated Use createStageRulers() instead
 */
export function initRulers(frame, logicalW = 1280, logicalH = 720) {
    const rulers = new StageRulers({ logicalW, logicalH });
    const success = rulers.init(frame);
    
    if (!success) return null;
    
    // Return API object matching old interface
    return {
        logicalW,
        logicalH,
        updateBounds: (w, h) => rulers.updateBounds(w, h),
        renderTicks: () => rulers.renderTicks(),
        setVisible: (on) => on ? rulers.show() : rulers.hide(),
        destroy: () => rulers.destroy()
    };
}
