import { describe, it, expect, beforeEach } from 'vitest';
import { typewriter } from './typewriter.js';
import { mountHost, connectTrait, spyEvent, resetDOM, wait } from '../test-helpers.js';

describe('typewriter', () => {
  beforeEach(resetDOM);

  it('starts with empty content + active attribute on connect', () => {
    const host = mountHost();
    host.textContent = 'Hello';
    connectTrait(typewriter, host, { speed: 5 });
    host.setAttribute('data-typewriter-speed', '5');
    // Re-connect after setting speed (setup reads on connect)
    typewriter().connect(host);
    expect(host.hasAttribute('data-typewriter-active')).toBe(true);
  });

  it('reveals full text and fires typewriter-done', async () => {
    const host = mountHost();
    host.textContent = 'Hi';
    host.setAttribute('data-typewriter-speed', '5');
    const spy = spyEvent(host, 'typewriter-done');
    typewriter().connect(host);
    await wait(80);
    expect(host.textContent).toBe('Hi');
    expect(spy.count).toBeGreaterThanOrEqual(1);
  });

  it('disconnect mid-reveal restores original text', async () => {
    const host = mountHost();
    host.textContent = 'A long sentence to reveal';
    host.setAttribute('data-typewriter-speed', '20');
    const inst = typewriter();
    inst.connect(host);
    await wait(40);
    inst.disconnect(host);
    expect(host.textContent).toBe('A long sentence to reveal');
    expect(host.hasAttribute('data-typewriter-active')).toBe(false);
  });

  it('respects data-typewriter-speed default (50ms)', () => {
    const host = mountHost();
    host.textContent = 'X';
    typewriter().connect(host);
    expect(host.hasAttribute('data-typewriter-active')).toBe(true);
  });
});
