import { describe, it, expect, beforeEach } from 'vitest';
import { dirtyState } from './dirty-state.js';
import { mountHost, connectTrait, resetDOM } from '../test-helpers.js';

describe('dirty-state', () => {
  beforeEach(resetDOM);

  it('starts in pristine state', () => {
    const host = mountHost('input', { value: 'initial' });
    connectTrait(dirtyState, host);
    expect(host.hasAttribute('data-dirty-state-pristine')).toBe(true);
    expect(host.hasAttribute('data-dirty-state-dirty')).toBe(false);
  });

  it('input event with changed value flips to dirty', () => {
    const host = mountHost('input', { value: 'initial' });
    connectTrait(dirtyState, host);
    host.value = 'modified';
    host.dispatchEvent(new Event('input'));
    expect(host.hasAttribute('data-dirty-state-dirty')).toBe(true);
    expect(host.hasAttribute('data-dirty-state-pristine')).toBe(false);
  });

  it('reverting to initial value flips back to pristine', () => {
    const host = mountHost('input', { value: 'initial' });
    connectTrait(dirtyState, host);
    host.value = 'modified';
    host.dispatchEvent(new Event('input'));
    expect(host.hasAttribute('data-dirty-state-dirty')).toBe(true);
    host.value = 'initial';
    host.dispatchEvent(new Event('input'));
    expect(host.hasAttribute('data-dirty-state-pristine')).toBe(true);
    expect(host.hasAttribute('data-dirty-state-dirty')).toBe(false);
  });

  it('disconnect clears both state attributes', () => {
    const host = mountHost('input', { value: 'x' });
    const inst = connectTrait(dirtyState, host);
    host.value = 'changed';
    host.dispatchEvent(new Event('input'));
    inst.disconnect(host);
    expect(host.hasAttribute('data-dirty-state-dirty')).toBe(false);
    expect(host.hasAttribute('data-dirty-state-pristine')).toBe(false);
  });
});
