import { warnOnce } from '../core/app-dom.js';

const toggles = document.querySelectorAll('[data-color-default-toggle]');

const syncToggle = (toggle) => {
  const targetSelector = toggle.dataset.colorTarget || '';
  if (!targetSelector) {
    warnOnce('UI_EL_MISSING', 'Missing data-color-target', { module: 'color-default-toggle' });
    return;
  }
  const target = document.querySelector(targetSelector);
  if (!target) {
    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;
    }
  }
};

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

  toggle.addEventListener('change', () => syncToggle(toggle));

  if (target) {
    target.addEventListener('input', () => {
      if (toggle.checked) {
        toggle.checked = false;
        target.removeAttribute('disabled');
      }
    });
  }

  syncToggle(toggle);
});
