/**
 * Container Preset Dropdown UI
 * 
 * Provides a dropdown to quickly apply container preset geometries (lower-third, upper-third, etc.)
 * Works alongside the existing "Add Layer" button.
 * Shares the same preset definitions as the double-click modal in block-stage-geometry.js
 * 
 * @module container-preset-ui
 * @since 5.2.1
 */

import { applyPreset as bindingsApplyPreset } from './bindings-layout.js';
import { PRESET_GEOMETRY, normalizePresetKey } from './util-preset-geometry.js';

/**
 * Shared preset definitions - single source of truth for both toolbar dropdown and modal
 * All geometry is in 1280×720 authoring space (Roku's native resolution)
 */
const PRESET_DEFINITIONS = {
    // Thirds (1280×240)
    'lower-third':    { label: 'Lower Third',    dims: '1280×240', group: 'Thirds' },
    'upper-third':    { label: 'Upper Third',    dims: '1280×240', group: 'Thirds' },
    'center-third':   { label: 'Center Third',   dims: '1280×240', group: 'Thirds' },
    // Halves
    'left-half':      { label: 'Left Half',      dims: '640×720',  group: 'Halves' },
    'right-half':     { label: 'Right Half',     dims: '640×720',  group: 'Halves' },
    'top-half':       { label: 'Top Half',       dims: '1280×360', group: 'Halves' },
    'bottom-half':    { label: 'Bottom Half',    dims: '1280×360', group: 'Halves' },
    // Quarters (640×360 - quarter of 1280×720)
    'upper-left-quarter':  { label: 'Upper Left Quarter',  dims: '640×360', group: 'Quarters' },
    'upper-right-quarter': { label: 'Upper Right Quarter', dims: '640×360', group: 'Quarters' },
    'lower-left-quarter':  { label: 'Lower Left Quarter',  dims: '640×360', group: 'Quarters' },
    'lower-right-quarter': { label: 'Lower Right Quarter', dims: '640×360', group: 'Quarters' },
    // Horizontal Quarters (1280×180 strips)
    'horizontal-first-quarter':  { label: 'Horizontal 1st Quarter',  dims: '1280×180', group: 'Horizontal Quarters' },
    'horizontal-second-quarter': { label: 'Horizontal 2nd Quarter', dims: '1280×180', group: 'Horizontal Quarters' },
    'horizontal-third-quarter':  { label: 'Horizontal 3rd Quarter',  dims: '1280×180', group: 'Horizontal Quarters' },
    'horizontal-fourth-quarter': { label: 'Horizontal 4th Quarter', dims: '1280×180', group: 'Horizontal Quarters' },
    // Featured + Grid (hero area with smaller items below)
    'featured-grid-hero':   { label: 'Featured Hero',      dims: '1280×480', group: 'Featured + Grid' },
    'featured-grid-item-1': { label: 'Grid Item 1 (left)', dims: '320×240',  group: 'Featured + Grid' },
    'featured-grid-item-2': { label: 'Grid Item 2',        dims: '320×240',  group: 'Featured + Grid' },
    'featured-grid-item-3': { label: 'Grid Item 3',        dims: '320×240',  group: 'Featured + Grid' },
    'featured-grid-item-4': { label: 'Grid Item 4 (right)',dims: '320×240',  group: 'Featured + Grid' },
    // Full
    'full-screen':    { label: 'Full Screen',    dims: '1280×720', group: 'Full' }
};

/**
 * Attach container preset dropdown to the button
 * Uses simple list style matching the double-click modal
 * 
 * @param {Object} editor - Canvas editor instance
 */
export function attachContainerPresetDropdown(editor) {
    const mainButton = document.getElementById('ccve-container-preset-btn');
    if (!mainButton) {
        console.warn('[Container Preset UI] Button #ccve-container-preset-btn not found in DOM');
        return;
    }
    
    // Create dropdown container wrapper
    const dropdownContainer = document.createElement('div');
    dropdownContainer.className = 'ccve-container-preset-dropdown';
    dropdownContainer.style.position = 'relative';
    dropdownContainer.style.display = 'inline-block';
    
    // Wrap the existing button
    mainButton.parentNode.insertBefore(dropdownContainer, mainButton);
    dropdownContainer.appendChild(mainButton);
    
    // Create dropdown menu - styled to match the precision dialog modal
    const dropdown = document.createElement('div');
    dropdown.className = 'ccve-container-preset-menu';
    dropdown.style.cssText = `
        position: absolute;
        top: 100%;
        left: 0;
        margin-top: 4px;
        background: #1f2937;
        border: 1px solid #334155;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        min-width: 220px;
        max-height: 380px;
        overflow-y: auto;
        z-index: 1000;
        display: none;
        color: #fff;
        font: 13px system-ui, sans-serif;
    `;
    
    // Build menu structure - simple list like modal select
    dropdown.innerHTML = buildSimplePresetMenu();
    
    // Toggle dropdown on button click
    mainButton.addEventListener('click', (e) => {
        e.stopPropagation();
        const isVisible = dropdown.style.display === 'block';
        dropdown.style.display = isVisible ? 'none' : 'block';
    });
    
    // Close dropdown when clicking outside or pressing Escape
    document.addEventListener('click', (e) => {
        if (!dropdownContainer.contains(e.target)) {
            dropdown.style.display = 'none';
        }
    });
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') dropdown.style.display = 'none';
    });
    
    // Handle menu item clicks
    dropdown.addEventListener('click', (e) => {
        const menuItem = e.target.closest('.ccve-preset-option');
        if (!menuItem) return;
        
        const presetKey = menuItem.dataset.presetKey;
        if (presetKey) {
            handleApplyPreset(editor, presetKey);
            dropdown.style.display = 'none';
        }
    });
    
    dropdownContainer.appendChild(dropdown);
    
    // Store reference on editor
    editor._containerPresetDropdown = dropdownContainer;
}

/**
 * Build simple preset menu HTML matching the modal's select dropdown style
 * 
 * @returns {string} Menu HTML
 */
function buildSimplePresetMenu() {
    const groups = ['Thirds', 'Halves', 'Quarters', 'Horizontal Quarters', 'Featured + Grid', 'Full'];
    
    let html = `<style>
        .ccve-container-preset-menu .ccve-preset-group-label {
            padding: 6px 10px 4px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #94a3b8;
            background: #0f172a;
            border-bottom: 1px solid #334155;
        }
        .ccve-container-preset-menu .ccve-preset-option {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            cursor: pointer;
            transition: background 0.1s;
            border-bottom: 1px solid #334155;
        }
        .ccve-container-preset-menu .ccve-preset-option:hover {
            background: #374151;
        }
        .ccve-container-preset-menu .ccve-preset-option:last-child {
            border-bottom: none;
        }
        .ccve-container-preset-menu .ccve-preset-label {
            font-weight: 500;
            color: #f1f5f9;
        }
        .ccve-container-preset-menu .ccve-preset-dims {
            font-size: 11px;
            color: #64748b;
            font-family: monospace;
        }
    </style>`;
    
    for (const groupName of groups) {
        const groupPresets = Object.entries(PRESET_DEFINITIONS).filter(([k, v]) => v.group === groupName);
        if (groupPresets.length === 0) continue;
        
        html += `<div class="ccve-preset-group-label">${groupName}</div>`;
        
        for (const [key, info] of groupPresets) {
            html += `<div class="ccve-preset-option" data-preset-key="${key}">
                <span class="ccve-preset-label">${info.label}</span>
                <span class="ccve-preset-dims">${info.dims}</span>
            </div>`;
        }
    }
    
    return html;
}

/**
 * Handle applying a preset
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {string} presetKey - Preset key to apply (hyphenated format)
 */
function handleApplyPreset(editor, presetKey) {
    console.log('[Container Preset UI] Applying preset:', presetKey);
    
    // Use the bindings-layout applyPreset function (handles both hyphenated and underscored keys)
    try {
        // Ensure current layout object up to date before applying preset
        try { editor.updateLayoutConfig && editor.updateLayoutConfig(); } catch(_) {}
        
        bindingsApplyPreset(editor, presetKey);
        
        // Also update the intended container dropdown if it exists
        const intendedSelect = document.getElementById('canvas-intended-container');
        if (intendedSelect) {
            // Try both formats
            intendedSelect.value = presetKey;
            if (!intendedSelect.value) {
                intendedSelect.value = normalizePresetKey(presetKey);
            }
        }
        
        // Force immediate geometry refresh & flash wrap for feedback (from intendedHandler)
        try {
            const wrap = editor.previewContainer?.querySelector('.cc-block-editor-wrap');
            if (wrap) {
                wrap.classList.add('ccve-geom-flash');
                setTimeout(() => wrap.classList.remove('ccve-geom-flash'), 500);
            }
        } catch(_) {}
        try {
            const pc = editor.previewContainer || document.getElementById('canvas-preview-container');
            if (pc) {
                pc.classList.add('ccve-preset-flash');
                clearTimeout(editor._presetFlashTimer);
                editor._presetFlashTimer = setTimeout(() => pc.classList.remove('ccve-preset-flash'), 600);
            }
        } catch(_) {}
        
        // Update container boundary visual to reflect new preset
        try { editor.updateBlockEditorRectFromConfig && editor.updateBlockEditorRectFromConfig(); } catch(_) {}
        try { editor._ensureContainerBoundary && editor._ensureContainerBoundary(); } catch(_) {}
        
        // Re-render layers with new container offset
        try { editor._renderUnifiedLayers && editor._renderUnifiedLayers(); } catch(_) {}
        
        // Double-tap geometry refresh after rAF to ensure DOM is settled
        requestAnimationFrame(() => {
            try { editor.updateBlockEditorRectFromConfig && editor.updateBlockEditorRectFromConfig(); } catch(_) {}
            try { editor._ensureContainerBoundary && editor._ensureContainerBoundary(); } catch(_) {}
        });
        
        try { editor.logGeometryDiagnostics && editor.logGeometryDiagnostics('container-preset-change'); } catch(_) {}
        editor.triggerPreview();
        editor.markUnsaved();
        
        // Show notification
        const info = PRESET_DEFINITIONS[presetKey];
        if (editor.showNotification && info) {
            editor.showNotification(`Applied "${info.label}" preset (${info.dims})`, 'success');
        }
    } catch (e) {
        console.error('[Container Preset UI] Failed to apply preset:', e);
        if (editor.showNotification) {
            editor.showNotification('Failed to apply preset', 'error');
        }
    }
}

/**
 * Get preset definitions - exported for potential use by other modules
 * 
 * @returns {Object} Preset definitions map
 */
export function getPresetDefinitions() {
    return { ...PRESET_DEFINITIONS };
}
