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

import { _cachedValueSources } from '../../core/state.ts';
import { t } from '../../core/i18n.ts';
import { ICON_TRASH } from '../../core/icons.ts';
import * as P from '../../core/icon-paths.ts';
import { IconSelect, type IconSelectItem } from '../../core/icon-select.ts';
import { EntitySelect } from '../../core/entity-palette.ts';
import { BindableScalarWidget } from '../../core/bindable-scalar.ts';

const _icon = (d: any) => `<svg class="icon" viewBox="0 0 24 24">${d}</svg>`;

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

let _mathWaveSpeedWidget: BindableScalarWidget | null = null;
let _mathWaveGradientEntitySelect: EntitySelect | null = null;
let _mathWaveWaveformIconSelects: IconSelect[] = [];

/* ── Destroy (called from modal onForceClose) ─────────────────── */

export function destroyMathWaveWidgets() {
    // Waveform icon selects are destroyed in _mathWaveRenderLayers
    _mathWaveWaveformIconSelects.forEach(s => s.destroy());
    _mathWaveWaveformIconSelects = [];
}

/* ── Speed widget ─────────────────────────────────────────────── */

export function ensureMathWaveSpeedWidget(): BindableScalarWidget {
    if (!_mathWaveSpeedWidget) {
        _mathWaveSpeedWidget = new BindableScalarWidget({
            container: document.getElementById('css-editor-math-wave-speed-container')!,
            min: 0.1, max: 10.0, step: 0.1, default: 1.0,
            idPrefix: 'css-editor-math-wave-speed',
            valueSources: () => _cachedValueSources,
            format: (v) => v.toFixed(1),
        });
    }
    return _mathWaveSpeedWidget;
}

/* ── Gradient entity select ───────────────────────────────────── */

export function ensureMathWaveGradientEntitySelect(buildGradientEntityItems: () => any[], syncSelectOptions: (sel: HTMLSelectElement, items: any[]) => void) {
    const sel = document.getElementById('css-editor-math-wave-gradient') as HTMLSelectElement | null;
    if (!sel) return;
    const items = buildGradientEntityItems();
    syncSelectOptions(sel, items);
    if (_mathWaveGradientEntitySelect) { _mathWaveGradientEntitySelect.refresh(); return; }
    _mathWaveGradientEntitySelect = new EntitySelect({
        target: sel,
        getItems: buildGradientEntityItems,
        placeholder: t('palette.search'),
    });
}

export function refreshMathWaveGradientEntitySelect() {
    if (_mathWaveGradientEntitySelect) _mathWaveGradientEntitySelect.refresh();
}

export function getMathWaveGradientEntitySelect(): EntitySelect | null {
    return _mathWaveGradientEntitySelect;
}

/* ── Waveform items ───────────────────────────────────────────── */

function _buildMathWaveWaveformItems(): IconSelectItem[] {
    return [
        { value: 'sine',     icon: _icon(P.activity),          label: t('color_strip.math_wave.waveform.sine'),     desc: '' },
        { value: 'triangle', icon: _icon(P.trendingUp),        label: t('color_strip.math_wave.waveform.triangle'), desc: '' },
        { value: 'sawtooth', icon: _icon(P.rotateCw),          label: t('color_strip.math_wave.waveform.sawtooth'), desc: '' },
        { value: 'square',   icon: _icon(P.layoutDashboard),   label: t('color_strip.math_wave.waveform.square'),   desc: '' },
    ];
}

/* ── Layer rendering ──────────────────────────────────────────── */

export type MathWaveLayer = { waveform: string; frequency: number; amplitude: number; phase: number; offset: number };

export function mathWaveRenderLayers(waves: MathWaveLayer[]) {
    const container = document.getElementById('css-editor-math-wave-layers');
    if (!container) return;
    // Destroy old waveform icon selects
    _mathWaveWaveformIconSelects.forEach(s => s.destroy());
    _mathWaveWaveformIconSelects = [];

    container.innerHTML = '';
    waves.forEach((wave, idx) => {
        const row = document.createElement('div');
        row.className = 'math-wave-layer-row';
        row.style.cssText = 'border:1px solid var(--border-color,#444);border-radius:6px;padding:8px;margin-bottom:6px;position:relative';
        row.innerHTML = `
            <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px">
                <strong>#${idx + 1}</strong>
                <button type="button" class="btn btn-icon btn-danger btn-sm" onclick="mathWaveRemoveLayer(${idx})" title="${t('common.delete')}" style="margin-left:auto">${ICON_TRASH}</button>
            </div>
            <div class="form-group" style="margin-bottom:4px">
                <label style="font-size:0.85em" data-i18n="color_strip.math_wave.waveform">${t('color_strip.math_wave.waveform')}</label>
                <select class="mw-waveform" data-idx="${idx}">
                    <option value="sine">${t('color_strip.math_wave.waveform.sine')}</option>
                    <option value="triangle">${t('color_strip.math_wave.waveform.triangle')}</option>
                    <option value="sawtooth">${t('color_strip.math_wave.waveform.sawtooth')}</option>
                    <option value="square">${t('color_strip.math_wave.waveform.square')}</option>
                </select>
            </div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px">
                <div class="form-group" style="margin-bottom:0">
                    <label style="font-size:0.85em" data-i18n="color_strip.math_wave.frequency">${t('color_strip.math_wave.frequency')}</label>
                    <input type="number" class="mw-frequency" min="0.1" max="20" step="0.1" value="${wave.frequency}">
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <label style="font-size:0.85em" data-i18n="color_strip.math_wave.amplitude">${t('color_strip.math_wave.amplitude')}</label>
                    <input type="number" class="mw-amplitude" min="0.0" max="2.0" step="0.1" value="${wave.amplitude}">
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <label style="font-size:0.85em" data-i18n="color_strip.math_wave.phase">${t('color_strip.math_wave.phase')}</label>
                    <input type="number" class="mw-phase" min="0.0" max="6.28" step="0.1" value="${wave.phase}">
                </div>
                <div class="form-group" style="margin-bottom:0">
                    <label style="font-size:0.85em" data-i18n="color_strip.math_wave.offset">${t('color_strip.math_wave.offset')}</label>
                    <input type="number" class="mw-offset" min="-1.0" max="1.0" step="0.1" value="${wave.offset}">
                </div>
            </div>
        `;
        container.appendChild(row);

        // Set waveform value and attach IconSelect
        const wfSelect = row.querySelector('.mw-waveform') as HTMLSelectElement;
        wfSelect.value = wave.waveform || 'sine';
        const iconSel = new IconSelect({
            target: wfSelect,
            items: _buildMathWaveWaveformItems(),
            columns: 2,
        });
        _mathWaveWaveformIconSelects.push(iconSel);
    });
}

export function mathWaveGetLayers(): MathWaveLayer[] {
    const container = document.getElementById('css-editor-math-wave-layers');
    if (!container) return [];
    const rows = container.querySelectorAll('.math-wave-layer-row');
    return Array.from(rows).map(row => ({
        waveform: (row.querySelector('.mw-waveform') as HTMLSelectElement).value,
        frequency: parseFloat((row.querySelector('.mw-frequency') as HTMLInputElement).value) || 1.0,
        amplitude: parseFloat((row.querySelector('.mw-amplitude') as HTMLInputElement).value) || 1.0,
        phase: parseFloat((row.querySelector('.mw-phase') as HTMLInputElement).value) || 0.0,
        offset: parseFloat((row.querySelector('.mw-offset') as HTMLInputElement).value) || 0.0,
    }));
}

export function mathWaveAddLayer() {
    const current = mathWaveGetLayers();
    current.push({ waveform: 'sine', frequency: 1.0, amplitude: 1.0, phase: 0.0, offset: 0.0 });
    mathWaveRenderLayers(current);
}

export function mathWaveRemoveLayer(idx: number) {
    const current = mathWaveGetLayers();
    current.splice(idx, 1);
    mathWaveRenderLayers(current);
}
