import { defineTrait } from '../define.js';

/**
 * Listens for the host's enclosing form's `reset` event and snaps the host's
 * value back to its initial value (captured on connect). Useful when the host
 * is not a native form-associated control but still wants reset semantics —
 * filter chips, search inputs, custom date pickers, segmented controls.
 *
 * If the host is not inside a form, the trait is a no-op (still registers
 * the active attribute and returns a clean cleanup).
 */
export const resettable = defineTrait({
  name: 'resettable',
  category: 'forms-data',
  description: 'Snaps the host value back to its initial value on form reset',
  attributes: ['data-resettable-active'],
  events: ['reset-applied'],
  config: [],
  setup({ host }) {
    // Boolean controls (switch-ui, check-ui, radio-ui) carry their state on
    // a `checked` reactive prop, not `value`. Detect at connect time so the
    // captured initial + reset write target the right field.
    //
    // Native HTMLInputElement always exposes a `checked` getter regardless
    // of type, so we can't bareword-check `'checked' in host`. Discriminate
    // by tag name + native-input type. Custom AdiaUI elements only declare
    // `checked` when it's their primary state — switch-ui, check-ui,
    // radio-ui — so the bareword check is safe there.
    const tag  = host.tagName?.toLowerCase?.() || '';
    const type = host.getAttribute?.('type') || '';
    const isNativeInput = tag === 'input';
    const isNativeCheckable = isNativeInput && (type === 'checkbox' || type === 'radio');
    const isCustomCheckable = !isNativeInput
      && 'checked' in host
      && typeof host.checked === 'boolean';
    const isCheckable = isNativeCheckable || isCustomCheckable;

    const initialValue = isCheckable
      ? host.checked
      : (host.value ?? host.getAttribute('value') ?? '');

    const form = host.closest?.('form');

    function onReset() {
      if (isCheckable) {
        host.checked = initialValue;
      } else if ('value' in host) {
        host.value = initialValue;
      } else {
        host.setAttribute('value', initialValue);
      }
      host.dispatchEvent(new CustomEvent('reset-applied', {
        bubbles: true,
        detail: { initialValue },
      }));
    }

    host.setAttribute('data-resettable-active', '');
    form?.addEventListener('reset', onReset);

    return () => {
      form?.removeEventListener('reset', onReset);
      host.removeAttribute('data-resettable-active');
    };
  },
});
