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

export const dirtyState = defineTrait({
  name: 'dirty-state',
  category: 'forms-data',
  description: 'Tracks modified vs initial value',
  attributes: ['data-dirty-state-dirty', 'data-dirty-state-pristine'],
  events: [],
  config: [],
  setup({ host }) {
    const initialValue = host.value ?? host.getAttribute('value') ?? '';

    function check() {
      const currentValue = host.value ?? host.getAttribute('value') ?? '';
      if (currentValue !== initialValue) {
        host.setAttribute('data-dirty-state-dirty', '');
        host.removeAttribute('data-dirty-state-pristine');
      } else {
        host.setAttribute('data-dirty-state-pristine', '');
        host.removeAttribute('data-dirty-state-dirty');
      }
    }

    // Set initial state
    host.setAttribute('data-dirty-state-pristine', '');

    function onInput() { check(); }
    function onChange() { check(); }

    host.addEventListener('input', onInput);
    host.addEventListener('change', onChange);

    return () => {
      host.removeEventListener('input', onInput);
      host.removeEventListener('change', onChange);
      host.removeAttribute('data-dirty-state-dirty');
      host.removeAttribute('data-dirty-state-pristine');
    };
  },
});
