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

import { ICON_TRASH } from '../../core/icons.ts';
import { rgbArrayToHex, hexToRgbArray } from '../css-gradient-editor.ts';

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

const _DEFAULT_CYCLE_COLORS = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff'];
let _colorCycleColors = [..._DEFAULT_CYCLE_COLORS];

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

function _syncColorCycleFromDom() {
    const inputs = document.querySelectorAll<HTMLInputElement>('#color-cycle-colors-list input[type=color]');
    if (inputs.length > 0) {
        _colorCycleColors = Array.from(inputs).map(el => el.value);
    }
}

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

function _colorCycleRenderList() {
    const list = document.getElementById('color-cycle-colors-list') as HTMLElement | null;
    if (!list) return;
    const canRemove = _colorCycleColors.length > 2;
    list.innerHTML = _colorCycleColors.map((hex, i) => `
        <div class="color-cycle-item">
            <input type="color" value="${hex}">
            ${canRemove
                ? `<button type="button" class="btn btn-secondary color-cycle-remove-btn"
                           onclick="colorCycleRemoveColor(${i})">${ICON_TRASH}</button>`
                : `<div style="height:14px"></div>`}
        </div>
    `).join('') + `<div class="color-cycle-item"><button type="button" class="btn btn-secondary color-cycle-add-btn" onclick="colorCycleAddColor()">+</button></div>`;
}

/* ── Public actions ───────────────────────────────────────────── */

export function colorCycleAddColor() {
    _syncColorCycleFromDom();
    _colorCycleColors.push('#ffffff');
    _colorCycleRenderList();
}

export function colorCycleRemoveColor(i: number) {
    _syncColorCycleFromDom();
    if (_colorCycleColors.length <= 2) return;
    _colorCycleColors.splice(i, 1);
    _colorCycleRenderList();
}

export function colorCycleGetColors() {
    const inputs = document.querySelectorAll<HTMLInputElement>('#color-cycle-colors-list input[type=color]');
    return Array.from(inputs).map(el => hexToRgbArray(el.value));
}

/* ── Load / Reset ─────────────────────────────────────────────── */

export function loadColorCycleState(css: any) {
    const raw = css && css.colors;
    _colorCycleColors = (raw && raw.length >= 2)
        ? raw.map((c: any) => rgbArrayToHex(c))
        : [..._DEFAULT_CYCLE_COLORS];
    _colorCycleRenderList();
}
