import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { hapticFeedback } from './haptic-feedback.js';
import { mountHost, connectTrait, resetDOM } from '../test-helpers.js';

describe('haptic-feedback', () => {
  let originalVibrate;

  beforeEach(() => {
    resetDOM();
    originalVibrate = navigator.vibrate;
  });

  afterEach(() => {
    if (originalVibrate) navigator.vibrate = originalVibrate;
    else delete navigator.vibrate;
  });

  it('without navigator.vibrate: no-op cleanup, no crash', () => {
    delete navigator.vibrate;
    const host = mountHost();
    expect(() => connectTrait(hapticFeedback, host)).not.toThrow();
  });

  it('with navigator.vibrate: press fires vibrate with parsed pattern', () => {
    const vibrate = vi.fn();
    navigator.vibrate = vibrate;
    const host = mountHost('div', { 'data-haptic-pattern': '20,10,20' });
    connectTrait(hapticFeedback, host);
    expect(host.hasAttribute('data-haptic-feedback-active')).toBe(true);
    host.dispatchEvent(new CustomEvent('press', { bubbles: true }));
    expect(vibrate).toHaveBeenCalledWith([20, 10, 20]);
  });

  it('default pattern is [10] when no data-haptic-pattern set', () => {
    const vibrate = vi.fn();
    navigator.vibrate = vibrate;
    const host = mountHost();
    connectTrait(hapticFeedback, host);
    host.dispatchEvent(new CustomEvent('press', { bubbles: true }));
    expect(vibrate).toHaveBeenCalledWith([10]);
  });

  it('disconnect removes the press listener', () => {
    const vibrate = vi.fn();
    navigator.vibrate = vibrate;
    const host = mountHost();
    const inst = connectTrait(hapticFeedback, host);
    inst.disconnect(host);
    host.dispatchEvent(new CustomEvent('press', { bubbles: true }));
    expect(vibrate).not.toHaveBeenCalled();
  });
});
