/**
 * Color Strip Sources — Mapped zone helpers.
 * Extracted from color-strips.ts to reduce file size.
 */

import { escapeHtml } from '../../core/api.ts';
import { t } from '../../core/i18n.ts';
import { getColorStripIcon, ICON_TRASH } from '../../core/icons.ts';
import { EntitySelect } from '../../core/entity-palette.ts';

/* ── State ────────────────────────────────────────────────────── */

let _mappedZones: any[] = [];
let _mappedAvailableSources: any[] = [];
let _mappedZoneEntitySelects: any[] = [];

/* ── Source management ────────────────────────────────────────── */

export function mappedSetAvailableSources(sources: any[]) {
    _mappedAvailableSources = sources;
}

function _getMappedSourceItems() {
    return _mappedAvailableSources.map(s => ({
        value: s.id,
        label: s.name,
        icon: getColorStripIcon(s.source_type),
    }));
}

/* ── Destroy ──────────────────────────────────────────────────── */

function _mappedDestroyEntitySelects() {
    _mappedZoneEntitySelects.forEach(es => es.destroy());
    _mappedZoneEntitySelects = [];
}

/* ── Rendering ────────────────────────────────────────────────── */

export function mappedRenderList() {
    const list = document.getElementById('mapped-zones-list') as HTMLElement | null;
    if (!list) return;
    _mappedDestroyEntitySelects();
    list.innerHTML = _mappedZones.map((zone, i) => {
        const srcOptions = _mappedAvailableSources.map(s =>
            `<option value="${s.id}"${zone.source_id === s.id ? ' selected' : ''}>${escapeHtml(s.name)}</option>`
        ).join('');
        return `
            <div class="segment-row">
                <div class="segment-row-header">
                    <span class="segment-index-label">#${i + 1}</span>
                    <button type="button" class="btn-icon-inline btn-danger-text"
                            onclick="mappedRemoveZone(${i})" title="${t('common.delete')}">${ICON_TRASH}</button>
                </div>
                <div class="segment-row-fields">
                    <select class="mapped-zone-source" data-idx="${i}">${srcOptions}</select>
                    <div class="segment-range-fields">
                        <label>${t('color_strip.mapped.zone_start')}</label>
                        <input type="number" class="mapped-zone-start" data-idx="${i}"
                               min="0" value="${zone.start}" placeholder="0">
                        <label>${t('color_strip.mapped.zone_end')}</label>
                        <input type="number" class="mapped-zone-end" data-idx="${i}"
                               min="0" value="${zone.end}" placeholder="0 = auto">
                    </div>
                    <label class="segment-reverse-label">
                        <input type="checkbox" class="mapped-zone-reverse" data-idx="${i}"${zone.reverse ? ' checked' : ''}>
                        <span>${t('color_strip.mapped.zone_reverse')}</span>
                    </label>
                </div>
            </div>
        `;
    }).join('');

    // Attach EntitySelect to each zone's source dropdown
    list.querySelectorAll<HTMLSelectElement>('.mapped-zone-source').forEach(sel => {
        _mappedZoneEntitySelects.push(new EntitySelect({
            target: sel,
            getItems: _getMappedSourceItems,
            placeholder: t('color_strip.mapped.select_source'),
        }));
    });
}

/* ── Actions ──────────────────────────────────────────────────── */

export function mappedAddZone() {
    _mappedZonesSyncFromDom();
    _mappedZones.push({
        source_id: _mappedAvailableSources.length > 0 ? _mappedAvailableSources[0].id : '',
        start: 0,
        end: 0,
        reverse: false,
    });
    mappedRenderList();
}

export function mappedRemoveZone(i: number) {
    _mappedZonesSyncFromDom();
    _mappedZones.splice(i, 1);
    mappedRenderList();
}

/* ── DOM sync ─────────────────────────────────────────────────── */

function _mappedZonesSyncFromDom() {
    const list = document.getElementById('mapped-zones-list') as HTMLElement | null;
    if (!list) return;
    const srcs = list.querySelectorAll<HTMLSelectElement>('.mapped-zone-source');
    const starts = list.querySelectorAll<HTMLInputElement>('.mapped-zone-start');
    const ends = list.querySelectorAll<HTMLInputElement>('.mapped-zone-end');
    const reverses = list.querySelectorAll<HTMLInputElement>('.mapped-zone-reverse');
    if (srcs.length === _mappedZones.length) {
        for (let i = 0; i < srcs.length; i++) {
            _mappedZones[i].source_id = srcs[i].value;
            _mappedZones[i].start = parseInt(starts[i].value) || 0;
            _mappedZones[i].end = parseInt(ends[i].value) || 0;
            _mappedZones[i].reverse = reverses[i].checked;
        }
    }
}

export function mappedGetZones() {
    _mappedZonesSyncFromDom();
    return _mappedZones.map(z => ({
        source_id: z.source_id,
        start: z.start,
        end: z.end,
        reverse: z.reverse,
    }));
}

export function loadMappedState(css: any) {
    const raw = css && css.zones;
    _mappedZones = (raw && raw.length > 0)
        ? raw.map((z: any) => ({
            source_id: z.source_id || '',
            start: z.start || 0,
            end: z.end || 0,
            reverse: z.reverse || false,
        }))
        : [];
    mappedRenderList();
}

export function resetMappedState() {
    _mappedZones = [];
    mappedRenderList();
}

/** Get raw zones array (for snapshot). */
export function getMappedZones(): any[] {
    return _mappedZones;
}
