/**
 * Shows/hides custom field option list based on field type selection.
 */
import { warnOnce } from '../core/app-dom.js';
import { syncControlState, createConditionalToggleInit } from '../core/app-conditional-controls.js';

const TYPES_WITH_OPTIONS = new Set(['select', 'multiselect']);
const FILTERABLE_TYPES = new Set(['select', 'multiselect', 'boolean', 'date']);

const syncFilterableAvailability = (source, target) => {
  const selectedType = String(source.value || '').trim().toLowerCase();
  const filterableAllowed = FILTERABLE_TYPES.has(selectedType);
  const checkbox = target.querySelector('[data-custom-field-filterable-input]');

  if (!(checkbox instanceof HTMLInputElement)) {
    warnOnce('UI_EL_MISSING', 'Missing filterable checkbox in custom field group', {
      module: 'custom-field-options-toggle',
    });
    return;
  }

  if (!checkbox.dataset.initialDisabled) {
    checkbox.dataset.initialDisabled = checkbox.hasAttribute('disabled') ? '1' : '0';
  }

  if (!filterableAllowed) {
    checkbox.checked = false;
    checkbox.setAttribute('disabled', 'disabled');
    target.setAttribute('aria-disabled', 'true');
    return;
  }

  target.removeAttribute('aria-disabled');
  if (checkbox.dataset.initialDisabled === '1') {
    checkbox.setAttribute('disabled', 'disabled');
    return;
  }

  checkbox.removeAttribute('disabled');
};

const initRoot = (source) => {
  if (!(source instanceof HTMLSelectElement)) {
    return null;
  }

  const group = String(source.dataset.customFieldGroup || '').trim();
  if (!group) {
    warnOnce('UI_EL_MISSING', 'Missing data-custom-field-group', { module: 'custom-field-options-toggle' });
    return null;
  }

  const target = document.querySelector(
    `[data-custom-field-options-target][data-custom-field-group="${group}"]`
  );
  if (!(target instanceof HTMLElement)) {
    warnOnce('UI_EL_MISSING', `Missing custom field options target for group: ${group}`, {
      module: 'custom-field-options-toggle',
    });
    return null;
  }

  const filterableTarget = document.querySelector(
    `[data-custom-field-filterable-target][data-custom-field-group="${group}"]`
  );
  if (!(filterableTarget instanceof HTMLElement)) {
    warnOnce('UI_EL_MISSING', `Missing custom field filterable target for group: ${group}`, {
      module: 'custom-field-options-toggle',
    });
    return null;
  }

  const onChange = () => {
    const selectedType = String(source.value || '').trim().toLowerCase();
    syncControlState(target, TYPES_WITH_OPTIONS.has(selectedType));
    syncFilterableAvailability(source, filterableTarget);
  };
  source.addEventListener('change', onChange);
  onChange();

  return () => {
    source.removeEventListener('change', onChange);
  };
};

export const initCustomFieldOptionsToggle = createConditionalToggleInit({
  rootSelector: '[data-custom-field-type-source]',
  boundKey: 'customFieldOptionsBound',
  initRoot,
});
