/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 *
 * backgrounds.js
 * Background management subsystem (Phase 2.7 Step 15 extraction): setup UI, load & display
 * active/available backgrounds, CRUD actions, preview application, and canvas application.
 */

import { safeJson, stdHeaders } from './fetch-utils.js';

export function attachBackgroundManagement(editor) {
    if (editor.__backgroundsAttached) return;
    editor.__backgroundsAttached = true;

    editor.setupBackgroundManagement = function setupBackgroundManagement() {
        const sel = document.getElementById('background-type-select');
        if (sel) sel.addEventListener('change', e => this.showBackgroundConfigPanel(e.target.value));
        const gradToggle = document.getElementById('bg-gradient-enabled');
        if (gradToggle) gradToggle.addEventListener('change', e => {
            const gc = document.getElementById('gradient-controls'); if (gc) gc.style.display = e.target.checked ? 'block':'none';
        });
        document.getElementById('create-background-btn')?.addEventListener('click', () => this.createBackground());
        document.getElementById('preview-background-btn')?.addEventListener('click', () => this.previewBackground());
        document.getElementById('refresh-background-btn')?.addEventListener('click', () => this.loadBackgroundData());
        document.getElementById('upload-background-btn')?.addEventListener('click', () => this.uploadBackgroundImage());
        document.getElementById('add-rotation-image-btn')?.addEventListener('click', () => this.addRotationImage());
    };

    editor.loadBackgroundData = async function loadBackgroundData() {
        try { await this.loadActiveBackground(); await this.loadAvailableBackgrounds(); }
        catch(e){ console.error('Error loading background data:', e); this.showNotification('Error loading background data','error'); }
    };

    editor.loadActiveBackground = async function loadActiveBackground() {
        try {
            const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/backgrounds/active`, { method:'GET', headers: stdHeaders() });
            if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
            const active = await resp.json();
            this.displayActiveBackground(active); this.applyBackgroundToCanvas(active);
        } catch(e){ console.error('Error loading active background:', e); }
    };

    editor.loadAvailableBackgrounds = async function loadAvailableBackgrounds() {
        try {
            const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/backgrounds`, { method:'GET', headers: stdHeaders() });
            if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
            const list = await resp.json();
            this.displayAvailableBackgrounds(list);
        } catch(e){ console.error('Error loading available backgrounds:', e); }
    };

    editor.displayActiveBackground = function displayActiveBackground(background) {
        const container = document.getElementById('current-background-info'); if(!container) return;
        if (!background || background.id === 0) { container.innerHTML = '<div class="no-background">Default background active</div>'; return; }
        const previewStyle = this.getBackgroundPreviewStyle(background);
        container.innerHTML = `<div class="current-background-preview" style="${previewStyle}"><div class="background-info-text">${this.escapeHtml(background.name)} (${background.type})</div></div>`;
    };

    editor.displayAvailableBackgrounds = function displayAvailableBackgrounds(backgrounds) {
        const container = document.getElementById('available-backgrounds-list'); if(!container) return;
        if (!backgrounds || backgrounds.length===0){ container.innerHTML='<div class="no-backgrounds">No backgrounds available</div>'; return; }
        container.innerHTML = backgrounds.map(b => `
            <div class="background-item ${b.is_active?'active':''}" data-background-id="${b.id}">
              <div class="background-item-info">
                <div class="background-preview-small" style="${this.getBackgroundPreviewStyle(b)}"></div>
                <div class="background-item-details"><h6>${this.escapeHtml(b.name)}</h6><span>${b.type}${b.is_active?' (Active)':''}</span></div>
              </div>
              <div class="background-item-actions">
                <button type="button" class="activate-background-btn" data-background-id="${b.id}" ${b.is_active?'disabled':''}>${b.is_active?'Active':'Activate'}</button>
                <button type="button" class="edit-background-btn" data-background-id="${b.id}">⚙️</button>
                <button type="button" class="delete-background-btn" data-background-id="${b.id}">🗑️</button>
              </div>
            </div>`).join('');
        container.querySelectorAll('.activate-background-btn').forEach(btn => btn.addEventListener('click', e => this.activateBackground(e.target.dataset.backgroundId)));
        container.querySelectorAll('.delete-background-btn').forEach(btn => btn.addEventListener('click', e => this.deleteBackground(e.target.dataset.backgroundId)));
    };

    editor.getBackgroundPreviewStyle = function getBackgroundPreviewStyle(background) {
        if (!background.config) return 'background: #1e3c72;';
        switch(background.type){
            case 'color':
                if (background.config.gradient) { const colors = background.config.gradient_colors||[background.config.color,'#333']; const direction = background.config.gradient_direction||'135deg'; return `background: linear-gradient(${direction}, ${colors.join(', ')});`; }
                return `background: ${background.config.color};`;
            case 'static':
                if (background.config.image_url) return `background: url('${background.config.image_url}') center/cover no-repeat;`;
                return 'background: #333;';
            case 'video':
                return 'background: #000; background-image: url("data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\'><text y=\'50%\' x=\'50%\' text-anchor=\'middle\' dominant-baseline=\'middle\' fill=\'white\'>🎥</text></svg>");';
            default: return 'background: #1e3c72;';
        }
    };

    editor.applyBackgroundToCanvas = function applyBackgroundToCanvas(background) {
        const layer = document.getElementById('canvas-background-layer'); if(!layer) return;
        layer.className = 'canvas-background';
        if (!background || background.id===0){ layer.style.background='linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)'; return; }
        switch(background.type){
            case 'color':
                if (background.config.gradient){ const colors=background.config.gradient_colors||[background.config.color,'#333']; const direction=background.config.gradient_direction||'135deg'; layer.style.background=`linear-gradient(${direction}, ${colors.join(', ')})`; }
                else layer.style.background = background.config.color; break;
            case 'static':
                if (background.config.image_url){
                    layer.style.backgroundImage = `url('${background.config.image_url}')`;
                    layer.style.backgroundPosition = background.config.position || 'center';
                    layer.style.backgroundSize = background.config.fit || 'cover';
                    layer.style.backgroundRepeat = background.config.repeat || 'no-repeat';
                }
                break;
            case 'video': layer.style.background = '#000'; break;
        }
    };

    editor.showBackgroundConfigPanel = function showBackgroundConfigPanel(type) {
        document.querySelectorAll('.background-config-panel').forEach(p => p.style.display='none');
        if (type){ const panel=document.getElementById(`${type}-background-controls`); if(panel) panel.style.display='block'; }
    };

    editor.createBackground = async function createBackground() {
        const typeSelect = document.getElementById('background-type-select');
        const nameInput = document.getElementById('bg-name');
        if (!typeSelect?.value){ this.showNotification('Please select a background type','error'); return; }
        if (!nameInput?.value.trim()){ this.showNotification('Please enter a background name','error'); return; }
        const data = { name: nameInput.value.trim(), type: typeSelect.value, enabled:1 };
        switch(typeSelect.value){
            case 'color': data.color=document.getElementById('bg-color').value; data.gradient=document.getElementById('bg-gradient-enabled').checked; if(data.gradient){ data.gradient_colors=[document.getElementById('bg-color').value, document.getElementById('bg-gradient-color2').value]; data.gradient_direction=document.getElementById('bg-gradient-direction').value; } break;
            case 'static': data.image_url=document.getElementById('bg-image-url').value; data.fit=document.getElementById('bg-image-fit').value; break;
            case 'video': data.video_url=document.getElementById('bg-video-url').value; data.loop=document.getElementById('bg-video-loop').checked; data.muted=document.getElementById('bg-video-muted').checked; break;
        }
        try {
            const resp = await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/backgrounds`, { method:'POST', headers: stdHeaders(), body: JSON.stringify(data) });
            if(!resp.ok){ const err=await safeJson(resp); throw new Error(err?.message||`HTTP ${resp.status}`); }
            await resp.json();
            this.showNotification('Background created successfully','success');
            nameInput.value=''; typeSelect.value=''; this.showBackgroundConfigPanel('');
            await this.loadAvailableBackgrounds();
        } catch(e){ console.error('Error creating background:', e); this.showNotification(e.message||'Error creating background','error'); }
    };

    editor.activateBackground = async function activateBackground(backgroundId){
        try { const resp=await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/backgrounds/${backgroundId}/activate`, { method:'PUT', headers: stdHeaders() }); if(!resp.ok) throw new Error(`HTTP ${resp.status}`); await resp.json(); this.showNotification('Background activated successfully','success'); await this.loadBackgroundData(); }
        catch(e){ console.error('Error activating background:', e); this.showNotification('Error activating background','error'); }
    };

    editor.deleteBackground = async function deleteBackground(backgroundId){
        if (!confirm('Are you sure you want to delete this background?')) return;
        try { const resp=await fetch(`${castconductorCanvasAjax.rest_url}castconductor/v5/backgrounds/${backgroundId}`, { method:'DELETE', headers: stdHeaders() }); if(!resp.ok) throw new Error(`HTTP ${resp.status}`); this.showNotification('Background deleted successfully','success'); await this.loadAvailableBackgrounds(); }
        catch(e){ console.error('Error deleting background:', e); this.showNotification('Error deleting background','error'); }
    };

    editor.previewBackground = function previewBackground(){
        const typeSelect=document.getElementById('background-type-select');
        if(!typeSelect?.value){ this.showNotification('Please select a background type to preview','error'); return; }
        const temp={ type: typeSelect.value, config:{} };
        switch(typeSelect.value){
            case 'color': temp.config.color=document.getElementById('bg-color').value; temp.config.gradient=document.getElementById('bg-gradient-enabled').checked; if(temp.config.gradient){ temp.config.gradient_colors=[document.getElementById('bg-color').value, document.getElementById('bg-gradient-color2').value]; temp.config.gradient_direction=document.getElementById('bg-gradient-direction').value; } break;
            case 'static': temp.config.image_url=document.getElementById('bg-image-url').value; break;
        }
        this.applyBackgroundToCanvas(temp); this.showNotification('Background preview applied','info');
    };

    editor.uploadBackgroundImage = function uploadBackgroundImage(){ this.showNotification('Image upload feature will be implemented in the next phase','info'); };
    editor.addRotationImage = function addRotationImage(){ this.showNotification('Rotating background feature will be implemented in the next phase','info'); };
}

export default { attachBackgroundManagement };
