/**
 * Toggles color input between custom value and default/inherited color.
 */
import { warnOnce, resolveHost } from '../core/app-dom.js';

const syncToggle = (toggle, scope) => {
  const targetSelector = toggle.dataset.colorTarget || '';
  if (!targetSelector) {
    warnOnce('UI_EL_MISSING', 'Missing data-color-target', { module: 'color-default-toggle' });
    return;
  }
  const target = scope.querySelector(targetSelector);
  if (!(target instanceof HTMLInputElement)) {
    warnOnce('UI_EL_MISSING', `Missing color target: ${targetSelector}`, { module: 'color-default-toggle' });
    return;
  }
  const defaultValue = toggle.dataset.colorDefault || '#2fa4a4';
  if (toggle.checked) {
    if (!target.dataset.customValue) {
      target.dataset.customValue = target.value;
    }
    target.value = defaultValue;
    target.setAttribute('disabled', 'disabled');
  } else {
    target.removeAttribute('disabled');
    if (target.dataset.customValue) {
      target.value = target.dataset.customValue;
    }
  }
};

export function initColorDefaultToggle(root = document, options = {}) {
  const host = resolveHost(root);
  const selector = String(options.selector || '[data-color-default-toggle]').trim() || '[data-color-default-toggle]';
  const toggles = Array.from(host.querySelectorAll(selector)).filter(
    (toggle) => toggle instanceof HTMLInputElement
  );
  if (!toggles.length) {
    return { destroy: () => {} };
  }

  const cleanupFns = [];
  toggles.forEach((toggle) => {
    if (toggle.dataset.colorDefaultToggleBound === '1') {
      return;
    }
    toggle.dataset.colorDefaultToggleBound = '1';

    const scope = document;
    const targetSelector = toggle.dataset.colorTarget || '';
    const target = targetSelector ? scope.querySelector(targetSelector) : null;
    if (targetSelector && !target) {
      warnOnce('UI_EL_MISSING', `Missing color target: ${targetSelector}`, { module: 'color-default-toggle' });
    }

    const onToggleChange = () => syncToggle(toggle, scope);
    toggle.addEventListener('change', onToggleChange);
    cleanupFns.push(() => toggle.removeEventListener('change', onToggleChange));

    if (target instanceof HTMLInputElement) {
      const onTargetInput = () => {
        if (toggle.checked) {
          toggle.checked = false;
          target.removeAttribute('disabled');
        }
      };
      target.addEventListener('input', onTargetInput);
      cleanupFns.push(() => target.removeEventListener('input', onTargetInput));
    }

    syncToggle(toggle, scope);
    cleanupFns.push(() => {
      delete toggle.dataset.colorDefaultToggleBound;
    });
  });

  const destroy = () => {
    cleanupFns.forEach((cleanup) => cleanup());
  };

  return { destroy };
}
