/**
 * Scene Presets — capture, activate, edit, delete system state snapshots.
 * Rendered as a CardSection inside the Automations tab, plus dashboard compact cards.
 */

import { fetchWithAuth, escapeHtml } from '../core/api.ts';
import { t } from '../core/i18n.ts';
import { showToast, showConfirm } from '../core/ui.ts';
import { Modal } from '../core/modal.ts';
import { CardSection } from '../core/card-sections.ts';
import {
    ICON_CAPTURE, ICON_START, ICON_EDIT, ICON_REFRESH, ICON_TARGET, ICON_TRASH, ICON_LINK,
} from '../core/icons.ts';
import { renderDeviceIcon, renderDeviceIconSvg } from '../core/device-icons.ts';
import { scenePresetsCache, outputTargetsCache, automationsCacheObj, devicesCache } from '../core/state.ts';
import { TagInput, renderTagChips } from '../core/tag-input.ts';
import { wrapCard, cardColorStyle } from '../core/card-colors.ts';
import type { ModCardOpts, ModChipOpts, LedState } from '../core/mod-card.ts';
import { EntityPalette } from '../core/entity-palette.ts';
import { navigateToCard } from '../core/navigation.ts';
import { isActiveTab } from '../core/tab-registry.ts';
import { makeCardIconFields } from '../core/card-icon.ts';
import { registerIconEntityType, makeSimpleIconAdapter } from './icon-picker.ts';
import type { ScenePreset } from '../types.ts';

registerIconEntityType('scene_preset', makeSimpleIconAdapter<ScenePreset>({
    cache: scenePresetsCache,
    endpointPrefix: '/scene-presets',
    reload: async () => {
        scenePresetsCache.invalidate();
        if (typeof (window as any).loadAutomations === 'function') {
            await (window as any).loadAutomations();
        }
    },
    typeLabelKey: 'device.icon.entity.scene_preset',
    typeLabelFallback: 'Scene preset',
    cardSelectors: (id) => [`[data-scene-id="${CSS.escape(id)}"]`],
}));

let _editingId: string | null = null;
let _allTargets: any[] = [];  // fetched on capture/edit open
let _deviceMap: Record<string, any> = {};  // primed alongside _allTargets so target rows can resolve device-derived icons synchronously
let _sceneTagsInput: TagInput | null = null;

// ── Target row rendering ──
//
// Three call sites (capture-open / edit-open / clone-open + the user's
// "+ Add Target" pick) all need the same patch-bay channel markup, so
// render it once here. Edit/clone used to emit a stripped row without
// the icon — funneling everything through this helper fixes that.

function _targetTypeLabel(tgt: any): string {
    return tgt?.target_type === 'ha_light' ? 'HA · LIGHT' : 'LED';
}

function _resolveTargetIconSvg(tgt: any): string {
    let svg = renderDeviceIconSvg(tgt.icon, { size: 18 });
    if (!svg && tgt.target_type === 'led' && tgt.device_id) {
        svg = renderDeviceIconSvg(_deviceMap[tgt.device_id]?.icon, { size: 18 });
    }
    return svg || ICON_TARGET;
}

function _renderSceneTargetRowHtml(tgt: any): string {
    const removeLabel = t('common.remove') || 'Remove';
    return `
        <div class="scene-target-icon" aria-hidden="true">${_resolveTargetIconSvg(tgt)}</div>
        <div class="scene-target-id">
            <span class="scene-target-name">${escapeHtml(tgt.name)}</span>
            <span class="scene-target-type">${_targetTypeLabel(tgt)}</span>
        </div>
        <button type="button" class="scene-target-remove" data-action="remove-scene-target" title="${escapeHtml(removeLabel)}" aria-label="${escapeHtml(removeLabel)}">${ICON_TRASH}</button>
    `;
}

function _appendSceneTargetItem(tgt: any, listEl: HTMLElement): void {
    const item = document.createElement('div');
    item.className = 'scene-target-item';
    item.dataset.targetId = tgt.id;
    item.innerHTML = _renderSceneTargetRowHtml(tgt);
    listEl.appendChild(item);
}

async function _primeTargetSelector(): Promise<void> {
    const [targets, devices] = await Promise.all([
        outputTargetsCache.fetch().catch((): any[] => []),
        devicesCache.fetch().catch((): any[] => []),
    ]);
    _allTargets = targets;
    _deviceMap = {};
    for (const d of devices) _deviceMap[d.id] = d;
}

function _setSceneTargetListEmptyHint(listEl: HTMLElement): void {
    listEl.dataset.empty = t('scenes.targets.empty') || 'No targets selected';
}

// ── Auto-name ──

let _spNameManuallyEdited = false;

function _autoGenerateScenePresetName() {
    if (_spNameManuallyEdited) return;
    if ((document.getElementById('scene-preset-editor-id') as HTMLInputElement).value) return;
    const items = document.querySelectorAll('#scene-target-list .scene-target-item');
    const count = items.length;
    const label = count > 0 ? `${t('scenes.title')} · ${count} ${count === 1 ? 'target' : 'targets'}` : t('scenes.title');
    (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value = label;
}

class ScenePresetEditorModal extends Modal {
    constructor() { super('scene-preset-editor-modal'); }
    onForceClose() {
        if (_sceneTagsInput) { _sceneTagsInput.destroy(); _sceneTagsInput = null; }
    }
    snapshotValues() {
        const items = [...document.querySelectorAll('#scene-target-list .scene-target-item')]
            .map(el => (el as HTMLElement).dataset.targetId).sort().join(',');
        return {
            name: (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value,
            description: (document.getElementById('scene-preset-editor-description') as HTMLInputElement).value,
            targets: items,
            tags: JSON.stringify(_sceneTagsInput ? _sceneTagsInput.getValue() : []),
        };
    }
}
const scenePresetModal = new ScenePresetEditorModal();

export const csScenes = new CardSection('scenes', {
    titleKey: 'scenes.title',
    gridClass: 'devices-grid',
    addCardOnclick: "openScenePresetCapture()",
    keyAttr: 'data-scene-id',
    emptyKey: 'section.empty.scenes',
    bulkActions: [{
        key: 'delete', labelKey: 'bulk.delete', icon: ICON_TRASH, style: 'danger', confirm: 'bulk.confirm_delete',
        handler: async (ids) => {
            const results = await Promise.allSettled(ids.map(id =>
                fetchWithAuth(`/scene-presets/${id}`, { method: 'DELETE' })
            ));
            const failed = results.filter(r => r.status === 'rejected' || (r.value && !r.value.ok)).length;
            if (failed) showToast(`${ids.length - failed}/${ids.length} deleted`, 'warning');
            else showToast(t('scenes.deleted'), 'success');
            scenePresetsCache.invalidate();
            if (window.loadAutomations) window.loadAutomations();
        },
    }],
});

export function createSceneCard(preset: ScenePreset) {
    const targetCount = (preset.targets || []).length;

    const automations = automationsCacheObj.data || [];
    const usedByCount = automations.filter(a => a.scene_preset_id === preset.id).length;

    const updated = preset.updated_at ? new Date(preset.updated_at).toLocaleString() : '';

    // ── Badge: SCN · XX (last 2 hex chars of id, mirrors AUTO · 07 in
    //    automations.ts and SCN · 04 in cards-redesign-demo-v2). ──
    const shortId = (preset.id || '').replace(/^scn_/i, '').slice(-2).toUpperCase() || 'NA';

    // ── Meta line: target count + last-updated timestamp. The "used by
    //    N automations" hint moves down into a chip so it reads as a
    //    crosslink, not a count. ──
    const metaParts: string[] = [];
    if (targetCount > 0) metaParts.push(`${targetCount} ${t('scenes.targets_count')}`);
    if (updated) metaParts.push(updated);
    const metaHtml = metaParts.length ? metaParts.map(escapeHtml).join(' · ') : undefined;

    // ── Chips: usage crosslink + target count quick-jump. ──
    const chips: ModChipOpts[] = [];
    if (usedByCount > 0) {
        chips.push({
            icon: ICON_LINK,
            text: t('scene_preset.used_by').replace('%d', String(usedByCount)),
            variant: 'tag',
        });
    }

    // ── 2 dim LEDs in the bezel — scenes are stored snapshots, never
    //    "running"; the two-LED cluster mirrors the demo. ──
    const leds: LedState[] = ['off', 'off'];

    const mod: ModCardOpts = {
        head: {
            badge: { text: `SCN · ${shortId}` },
            name: preset.name,
            metaHtml,
            leds,
            ...makeCardIconFields('scene_preset', preset.id, preset),
            menu: {
                duplicateOnclick: `cloneScenePreset('${preset.id}')`,
                hideOnclick: `toggleCardHidden('scenes','${preset.id}')`,
                deleteOnclick: `deleteScenePreset('${preset.id}')`,
            },
        },
        body: {
            desc: preset.description || undefined,
            chips: chips.length ? chips : undefined,
        },
        foot: {
            patchState: 'idle',
            patchLabel: t('scenes.status.preset'),
            primaryAction: {
                label: t('scenes.action.activate'),
                icon: ICON_START,
                onclick: `activateScenePreset('${preset.id}')`,
                title: t('scenes.activate'),
                variant: 'go',
            },
            secondaryActions: [{
                label: t('scenes.action.recapture'),
                icon: ICON_REFRESH,
                onclick: `recaptureScenePreset('${preset.id}')`,
                title: t('scenes.recapture'),
            }],
            iconActions: [{
                icon: ICON_EDIT,
                onclick: `editScenePreset('${preset.id}')`,
                title: t('scenes.edit'),
            }],
        },
    };

    const cardHtml = wrapCard({
        dataAttr: 'data-scene-id',
        id: preset.id,
        mod,
    });
    const tagsHtml = renderTagChips(preset.tags);
    return tagsHtml ? cardHtml.replace(/<\/div>\s*$/, `${tagsHtml}</div>`) : cardHtml;
}

// ===== Dashboard section (compact cards) =====

export async function loadScenePresets(): Promise<ScenePreset[]> {
    return scenePresetsCache.fetch();
}

export function renderScenePresetsSection(presets: ScenePreset[]): string | { headerExtra: string; content: string } {
    if (!presets || presets.length === 0) return '';

    const captureBtn = `<button class="btn btn-sm btn-primary dashboard-stop-all" data-action="capture-scene" title="${t('scenes.capture')}">${ICON_CAPTURE} ${t('scenes.capture')}</button>`;
    const cards = presets.map(p => _renderDashboardPresetCard(p)).join('');

    return { headerExtra: captureBtn, content: `<div class="dashboard-autostart-grid">${cards}</div>` };
}

function _renderDashboardPresetCard(preset: ScenePreset): string {
    const targetCount = (preset.targets || []).length;
    const metaParts = [
        targetCount > 0 ? `${targetCount} ${t('scenes.targets_count')}` : null,
        preset.description ? escapeHtml(preset.description) : null,
    ].filter(Boolean);
    const short = (preset.id || '').replace(/^scn_/, '').slice(0, 2).toUpperCase() || 'SC';
    const activateLabel = t('scenes.activate') || 'Activate';

    const pStyle = cardColorStyle(preset.id);
    const iconId = preset.icon || '';
    const iconColor = preset.icon_color || '';
    const iconStyle = iconColor
        ? ` style="--ch:${escapeHtml(iconColor)};color:${escapeHtml(iconColor)}"`
        : '';
    const iconPlate = iconId
        ? `<div class="mod-icon"${iconStyle}>${renderDeviceIconSvg(iconId, { size: 24 })}</div>`
        : '';
    const headCls = iconPlate ? 'mod-head mod-head--with-icon' : 'mod-head';
    return `<div class="dashboard-target dashboard-scene-preset dashboard-card-link" data-scene-id="${preset.id}" data-action="navigate-scene" data-id="${preset.id}"${pStyle ? ` style="${pStyle}"` : ''}>
        <div class="${headCls}">
            ${iconPlate}
            <div class="mod-id">
                <span class="mod-badge">SCN \u00b7 ${escapeHtml(short)}</span>
                <div class="mod-name"><span>${escapeHtml(preset.name)}</span></div>
                ${metaParts.length ? `<div class="mod-meta">${metaParts.join(' \u00b7 ')}</div>` : ''}
            </div>
            <div class="mod-leds" aria-hidden="true">
                <span class="led"></span>
            </div>
        </div>
        <div class="mod-foot">
            <div class="mod-patch"><span class="patch-dot"></span><span>${escapeHtml(t('patch.preset'))}</span></div>
            <button class="mod-btn mod-btn-go" data-action="activate-scene" data-id="${preset.id}" title="${activateLabel}" onclick="event.stopPropagation();">${ICON_START} <span>${activateLabel}</span></button>
        </div>
    </div>`;
}

// ===== Capture (create) =====

export async function openScenePresetCapture(): Promise<void> {
    _editingId = null;
    (document.getElementById('scene-preset-editor-id') as HTMLInputElement).value = '';
    (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value = '';
    (document.getElementById('scene-preset-editor-description') as HTMLInputElement).value = '';

    (document.getElementById('scene-preset-editor-error') as HTMLElement).style.display = 'none';

    const titleEl = document.querySelector('#scene-preset-editor-title span[data-i18n]');
    if (titleEl) { titleEl.setAttribute('data-i18n', 'scenes.add'); titleEl.textContent = t('scenes.add'); }

    // Fetch targets and populate selector
    const selectorGroup = document.getElementById('scene-target-selector-group');
    const targetList = document.getElementById('scene-target-list');
    if (selectorGroup && targetList) {
        selectorGroup.style.display = '';
        targetList.innerHTML = '';
        _setSceneTargetListEmptyHint(targetList);
        try {
            await _primeTargetSelector();
            _refreshTargetSelect();
        } catch { /* ignore */ }
    }

    if (_sceneTagsInput) { _sceneTagsInput.destroy(); _sceneTagsInput = null; }
    _sceneTagsInput = new TagInput(document.getElementById('scene-tags-container'), { placeholder: t('tags.placeholder') });
    _sceneTagsInput.setValue([]);

    // Auto-name wiring
    _spNameManuallyEdited = false;
    (document.getElementById('scene-preset-editor-name') as HTMLElement).oninput = () => { _spNameManuallyEdited = true; };
    _autoGenerateScenePresetName();

    scenePresetModal.open();
    scenePresetModal.snapshot();
}

// ===== Edit metadata =====

export async function editScenePreset(presetId: string): Promise<void> {
    const preset = scenePresetsCache.data.find(p => p.id === presetId);
    if (!preset) return;

    _editingId = presetId;
    (document.getElementById('scene-preset-editor-id') as HTMLInputElement).value = presetId;
    (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value = preset.name;
    (document.getElementById('scene-preset-editor-description') as HTMLInputElement).value = preset.description || '';
    (document.getElementById('scene-preset-editor-error') as HTMLElement).style.display = 'none';

    const titleEl = document.querySelector('#scene-preset-editor-title span[data-i18n]');
    if (titleEl) { titleEl.setAttribute('data-i18n', 'scenes.edit'); titleEl.textContent = t('scenes.edit'); }

    // Show target selector and pre-populate with existing targets
    const selectorGroup = document.getElementById('scene-target-selector-group');
    const targetList = document.getElementById('scene-target-list');
    if (selectorGroup && targetList) {
        selectorGroup.style.display = '';
        targetList.innerHTML = '';
        _setSceneTargetListEmptyHint(targetList);
        try {
            await _primeTargetSelector();

            const presetTargetIds = (preset.targets || []).map(pt => pt.target_id || pt.id);
            for (const tid of presetTargetIds) {
                const tgt = _allTargets.find(t => t.id === tid);
                if (!tgt) continue;
                _appendSceneTargetItem(tgt, targetList);
            }
            _refreshTargetSelect();
        } catch { /* ignore */ }
    }

    if (_sceneTagsInput) { _sceneTagsInput.destroy(); _sceneTagsInput = null; }
    _sceneTagsInput = new TagInput(document.getElementById('scene-tags-container'), { placeholder: t('tags.placeholder') });
    _sceneTagsInput.setValue(preset.tags || []);

    scenePresetModal.open();
    scenePresetModal.snapshot();
}

// ===== Save (create or update) =====

export async function saveScenePreset(): Promise<void> {
    const name = (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value.trim();
    const description = (document.getElementById('scene-preset-editor-description') as HTMLInputElement).value.trim();
    const errorEl = document.getElementById('scene-preset-editor-error')!;

    if (!name) {
        errorEl.textContent = t('scenes.error.name_required');
        errorEl.style.display = 'block';
        return;
    }

    const tags = _sceneTagsInput ? _sceneTagsInput.getValue() : [];

    try {
        let resp;
        if (_editingId) {
            const target_ids = [...document.querySelectorAll('#scene-target-list .scene-target-item')]
                .map(el => (el as HTMLElement).dataset.targetId);
            resp = await fetchWithAuth(`/scene-presets/${_editingId}`, {
                method: 'PUT',
                body: JSON.stringify({ name, description, target_ids, tags }),
            });
        } else {
            const target_ids = [...document.querySelectorAll('#scene-target-list .scene-target-item')]
                .map(el => (el as HTMLElement).dataset.targetId);
            resp = await fetchWithAuth('/scene-presets', {
                method: 'POST',
                body: JSON.stringify({ name, description, target_ids, tags }),
            });
        }

        if (!resp.ok) {
            const err = await resp.json();
            errorEl.textContent = err.detail || t('scenes.error.save_failed');
            errorEl.style.display = 'block';
            return;
        }

        scenePresetModal.forceClose();
        showToast(_editingId ? t('scenes.updated') : t('scenes.captured'), 'success');
        scenePresetsCache.invalidate();
        _reloadScenesTab();
    } catch (error) {
        if (error.isAuth) return;
        errorEl.textContent = t('scenes.error.save_failed');
        errorEl.style.display = 'block';
    }
}

export async function closeScenePresetEditor(): Promise<void> {
    await scenePresetModal.close();
}

// ===== Target selector helpers =====

function _getAddedTargetIds(): Set<string> {
    return new Set(
        [...document.querySelectorAll('#scene-target-list .scene-target-item')]
            .map(el => (el as HTMLElement).dataset.targetId)
            .filter(Boolean) as string[]
    );
}

function _refreshTargetSelect(): void {
    // Update add button disabled state
    const addBtn = document.getElementById('scene-target-add-btn') as HTMLButtonElement | null;
    if (addBtn) {
        const added = _getAddedTargetIds();
        addBtn.disabled = _allTargets.every(t => added.has(t.id));
    }
}

function _addTargetToList(tgt: any): void {
    const list = document.getElementById('scene-target-list');
    if (!list) return;
    _appendSceneTargetItem(tgt, list);
    _refreshTargetSelect();
}

// Picker icon — keeps the `<svg class="icon">` shape EntityPalette expects.
function _resolveTargetPickerIcon(tgt: any): string {
    let icon = renderDeviceIcon(tgt.icon);
    if (!icon && tgt.target_type === 'led' && tgt.device_id) {
        icon = renderDeviceIcon(_deviceMap[tgt.device_id]?.icon);
    }
    return icon || ICON_TARGET;
}

export async function addSceneTarget(): Promise<void> {
    const added = _getAddedTargetIds();
    const available = _allTargets.filter(t => !added.has(t.id));
    if (available.length === 0) return;

    const items = available.map(t => ({
        value: t.id,
        label: t.name,
        icon: _resolveTargetPickerIcon(t),
    }));

    const picked = await EntityPalette.pick({
        items,
        placeholder: t('scenes.targets.search_placeholder'),
    });
    if (!picked) return;

    const tgt = _allTargets.find(t => t.id === picked);
    if (tgt) {
        _addTargetToList(tgt);
        _autoGenerateScenePresetName();
    }
}

// removeSceneTarget is now handled via event delegation on the modal

// ===== Activate =====

export async function activateScenePreset(presetId: string): Promise<void> {
    try {
        const resp = await fetchWithAuth(`/scene-presets/${presetId}/activate`, {
            method: 'POST',
        });
        if (!resp.ok) {
            const errData = await resp.json().catch(() => ({}));
            const detail = errData.detail || errData.message || '';
            const detailStr = Array.isArray(detail) ? detail.map(d => d.msg || d).join('; ') : String(detail);
            showToast(detailStr || t('scenes.error.activate_failed'), 'error');
            return;
        }
        const result = await resp.json();
        if (result.status === 'activated') {
            showToast(t('scenes.activated'), 'success');
        } else {
            showToast(`${t('scenes.activated_partial')}: ${result.errors.length} ${t('scenes.errors')}`, 'warning');
        }
        if (typeof window.loadDashboard === 'function') window.loadDashboard(true);
    } catch (error: any) {
        if (error.isAuth) return;
        showToast(t('scenes.error.activate_failed'), 'error');
    }
}

// ===== Recapture =====

export async function recaptureScenePreset(presetId: string): Promise<void> {
    const preset = scenePresetsCache.data.find(p => p.id === presetId);
    const name = preset ? preset.name : presetId;
    const confirmed = await showConfirm(t('scenes.recapture_confirm', { name }));
    if (!confirmed) return;

    try {
        const resp = await fetchWithAuth(`/scene-presets/${presetId}/recapture`, {
            method: 'POST',
        });
        if (resp.ok) {
            showToast(t('scenes.recaptured'), 'success');
            scenePresetsCache.invalidate();
            _reloadScenesTab();
        } else {
            const errData = await resp.json().catch(() => ({}));
            const detail = errData.detail || errData.message || '';
            const detailStr = Array.isArray(detail) ? detail.map(d => d.msg || d).join('; ') : String(detail);
            showToast(detailStr || t('scenes.error.recapture_failed'), 'error');
        }
    } catch (error) {
        if (error.isAuth) return;
        showToast(error.message || t('scenes.error.recapture_failed'), 'error');
    }
}

// ===== Clone =====

export async function cloneScenePreset(presetId: string): Promise<void> {
    const preset = scenePresetsCache.data.find(p => p.id === presetId);
    if (!preset) return;

    // Open the capture modal in create mode, prefilled from the cloned preset
    _editingId = null;
    (document.getElementById('scene-preset-editor-id') as HTMLInputElement).value = '';
    (document.getElementById('scene-preset-editor-name') as HTMLInputElement).value = (preset.name || '') + ' (Copy)';
    (document.getElementById('scene-preset-editor-description') as HTMLInputElement).value = preset.description || '';
    (document.getElementById('scene-preset-editor-error') as HTMLElement).style.display = 'none';

    const titleEl = document.querySelector('#scene-preset-editor-title span[data-i18n]');
    if (titleEl) { titleEl.setAttribute('data-i18n', 'scenes.add'); titleEl.textContent = t('scenes.add'); }

    // Fetch targets and populate selector, then pre-add the cloned preset's targets
    const selectorGroup = document.getElementById('scene-target-selector-group');
    const targetList = document.getElementById('scene-target-list');
    if (selectorGroup && targetList) {
        selectorGroup.style.display = '';
        targetList.innerHTML = '';
        _setSceneTargetListEmptyHint(targetList);
        try {
            await _primeTargetSelector();

            const clonedTargetIds = (preset.targets || []).map(pt => pt.target_id || pt.id);
            for (const tid of clonedTargetIds) {
                const tgt = _allTargets.find(t => t.id === tid);
                if (!tgt) continue;
                _appendSceneTargetItem(tgt, targetList);
            }
            _refreshTargetSelect();
        } catch { /* ignore */ }
    }

    if (_sceneTagsInput) { _sceneTagsInput.destroy(); _sceneTagsInput = null; }
    _sceneTagsInput = new TagInput(document.getElementById('scene-tags-container'), { placeholder: t('tags.placeholder') });
    _sceneTagsInput.setValue(preset.tags || []);

    scenePresetModal.open();
    scenePresetModal.snapshot();
}

// ===== Delete =====

export async function deleteScenePreset(presetId: string): Promise<void> {
    const preset = scenePresetsCache.data.find(p => p.id === presetId);
    const name = preset ? preset.name : presetId;
    const confirmed = await showConfirm(t('scenes.delete_confirm', { name }));
    if (!confirmed) return;

    try {
        const resp = await fetchWithAuth(`/scene-presets/${presetId}`, {
            method: 'DELETE',
        });
        if (resp.ok) {
            showToast(t('scenes.deleted'), 'success');
            scenePresetsCache.invalidate();
            _reloadScenesTab();
        } else {
            const errData = await resp.json().catch(() => ({}));
            const detail = errData.detail || errData.message || '';
            const detailStr = Array.isArray(detail) ? detail.map(d => d.msg || d).join('; ') : String(detail);
            showToast(detailStr || t('scenes.error.delete_failed'), 'error');
        }
    } catch (error) {
        if (error.isAuth) return;
        showToast(error.message || t('scenes.error.delete_failed'), 'error');
    }
}

// ===== Event delegation for scene preset card actions =====

const _sceneCardActions: Record<string, (id: string) => void> = {
    'delete-scene': deleteScenePreset,
    'clone-scene': cloneScenePreset,
    'edit-scene': editScenePreset,
    'recapture-scene': recaptureScenePreset,
    'activate-scene': activateScenePreset,
};

export function initScenePresetDelegation(container: HTMLElement): void {
    container.addEventListener('click', (e: MouseEvent) => {
        const btn = (e.target as HTMLElement).closest<HTMLElement>('[data-action]');
        if (!btn) return;

        const action = btn.dataset.action;
        const id = btn.dataset.id;
        if (!action) return;

        if (action === 'capture-scene') {
            e.stopPropagation();
            openScenePresetCapture();
            return;
        }

        if (action === 'navigate-scene') {
            // Only navigate if click wasn't on a child button
            if ((e.target as HTMLElement).closest('button')) return;
            navigateToCard('automations', 'scenes', 'scenes', 'data-scene-id', id!);
            return;
        }

        if (action === 'remove-scene-target') {
            const item = btn.closest('.scene-target-item');
            if (item) {
                item.remove();
                _refreshTargetSelect();
                _autoGenerateScenePresetName();
            }
            return;
        }

        if (!id) return;

        const handler = _sceneCardActions[action];
        if (handler) {
            e.stopPropagation();
            handler(id);
        }
    });
}

// ===== Helpers =====

function _reloadScenesTab(): void {
    // Reload automations tab (which includes scenes section)
    if (isActiveTab('automations')) {
        if (typeof window.loadAutomations === 'function') window.loadAutomations();
    }
    // Also refresh dashboard (scene presets section)
    if (typeof window.loadDashboard === 'function') window.loadDashboard(true);
}

// ===== Modal event delegation (for target list remove buttons) =====

const _sceneEditorModal = document.getElementById('scene-preset-editor-modal');
if (_sceneEditorModal) {
    _sceneEditorModal.addEventListener('click', (e: MouseEvent) => {
        const btn = (e.target as HTMLElement).closest<HTMLElement>('[data-action="remove-scene-target"]');
        if (!btn) return;
        const item = btn.closest('.scene-target-item');
        if (item) {
            item.remove();
            _refreshTargetSelect();
            _autoGenerateScenePresetName();
        }
    });
}
