/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 *
 * container-form-enhancements.js
 * Extracted helpers for container creation/edit form presets (Phase 2.7 Step 15).
 */

export function attachContainerFormEnhancements(editor) {
    if (editor.__containerFormEnhancementsAttached) return;
    editor.__containerFormEnhancementsAttached = true;

    editor.bindContainerFormEnhancements = function bindContainerFormEnhancements() {
        const applyPreset = (preset) => {
            const set = (id, v) => { const el = document.getElementById(id); if (el) el.value = String(v); };
            switch (preset) {
                // Authoring templates aligned to 1280×720 canvas
                case 'lower_third': set('cc-field-width',1280); set('cc-field-height',240); set('cc-field-x',0); set('cc-field-y',480); break; // y = 720 - 240
                case 'upper_third': set('cc-field-width',1280); set('cc-field-height',240); set('cc-field-x',0); set('cc-field-y',0); break;
                case 'full_screen': set('cc-field-width',1280); set('cc-field-height',720); set('cc-field-x',0); set('cc-field-y',0); break;
                case 'left_sidebar': set('cc-field-width',320); set('cc-field-height',720); set('cc-field-x',0); set('cc-field-y',0); break; // ~25% of 1280
                case 'right_sidebar': set('cc-field-width',320); set('cc-field-height',720); set('cc-field-x',960); set('cc-field-y',0); break; // 1280 - 320
            }
        };

        const positionSelect = document.getElementById('cc-field-position');
        if (positionSelect) {
            positionSelect.addEventListener('change', (e) => {
                const preset = e.target.value;
                applyPreset(preset);
                const snap = (xp,yp) => { const xP=document.getElementById('cc-field-x-preset'); const yP=document.getElementById('cc-field-y-preset'); if(xP) xP.value=xp; if(yP) yP.value=yp; };
                if (preset==='lower_third') snap('0','bottom');
                else if (preset==='upper_third'||preset==='full_screen') snap('0','0');
                else if (preset==='left_sidebar') snap('0','0');
                else if (preset==='right_sidebar') snap('right','0');
                const evt = new Event('change');
                document.getElementById('cc-field-x-preset')?.dispatchEvent(evt);
                document.getElementById('cc-field-y-preset')?.dispatchEvent(evt);
            });
        }

        const zPresetSelect = document.getElementById('cc-field-z-preset');
        if (zPresetSelect) {
            zPresetSelect.addEventListener('change', (e) => {
                const map = { background:0, content:10, overlay:200 };
                const el = document.getElementById('cc-field-z');
                if (el) el.value = String(map[e.target.value] ?? 10);
            });
        }

        const applyXY = () => {
            const w = parseInt(document.getElementById('cc-field-width')?.value||'0',10)||0;
            const h = parseInt(document.getElementById('cc-field-height')?.value||'0',10)||0;
            const xPreset = document.getElementById('cc-field-x-preset')?.value;
            const yPreset = document.getElementById('cc-field-y-preset')?.value;
            const xEl = document.getElementById('cc-field-x');
            const yEl = document.getElementById('cc-field-y');
            if (xEl && xPreset) {
                // 1280-wide authoring presets
                if (xPreset==='center') xEl.value = String(Math.max(0, Math.floor((1280-w)/2)));
                else if (xPreset==='right') xEl.value = String(Math.max(0, 1280-w));
                else xEl.value = String(parseInt(xPreset,10)||0);
            }
            if (yEl && yPreset) {
                // 720-high authoring presets
                if (yPreset==='center') yEl.value = String(Math.max(0, Math.floor((720-h)/2)));
                else if (yPreset==='bottom') yEl.value = String(Math.max(0, 720-h));
                else yEl.value = String(parseInt(yPreset,10)||0);
            }
        };
        document.getElementById('cc-field-x-preset')?.addEventListener('change', applyXY);
        document.getElementById('cc-field-y-preset')?.addEventListener('change', applyXY);
        document.getElementById('cc-field-width')?.addEventListener('input', applyXY);
        document.getElementById('cc-field-height')?.addEventListener('input', applyXY);

        // Optional: WP Media picker for Background Image in container forms
        const bindMediaPicker = (btnId, inputId) => {
            const btn = document.getElementById(btnId);
            const input = document.getElementById(inputId);
            if (!btn || !input) return;
            if (btn.__ccveBound) return; btn.__ccveBound = true;
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                try {
                    if (window.wp && window.wp.media) {
                        const frame = window.wp.media({ title: 'Select image', button: { text: 'Use this image' }, multiple: false });
                        frame.on('select', function() {
                            const attachment = frame.state().get('selection').first().toJSON();
                            input.value = attachment.url || '';
                        });
                        frame.open();
                    }
                } catch(_) { /* fallback: do nothing */ }
            });
        };
        bindMediaPicker('cc-bg-select-media', 'cc-bg-image-url');

        // Overlay / Navigation: Toggle field visibility based on display mode
        const overlayDisplayModeSelect = document.getElementById('cc-overlay-display-mode');
        if (overlayDisplayModeSelect) {
            const toggleOverlayFields = () => {
                const isOverlay = overlayDisplayModeSelect.value === 'overlay';
                document.querySelectorAll('.cc-overlay-fields').forEach(el => {
                    el.style.display = isOverlay ? 'block' : 'none';
                });
            };
            overlayDisplayModeSelect.addEventListener('change', toggleOverlayFields);
            // Initial state
            toggleOverlayFields();
        }
    };
}

export default { attachContainerFormEnhancements };
