import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { useHapticsPreference } from '../useHapticsPreference';
import { HAPTICS_STORAGE_KEY } from '../../lib/haptics';

function TestHarness() {
  const { enabled, setEnabled } = useHapticsPreference();
  return (
    <button
      type="button"
      data-testid="toggle"
      onClick={() => setEnabled(!enabled)}
    >
      {enabled ? 'on' : 'off'}
    </button>
  );
}

describe('useHapticsPreference', () => {
  beforeEach(() => {
    window.localStorage.removeItem(HAPTICS_STORAGE_KEY);
    Object.defineProperty(navigator, 'vibrate', {
      configurable: true,
      value: vi.fn(),
    });
  });

  it('toggles and persists preference', () => {
    render(<TestHarness />);
    const button = screen.getByTestId('toggle');
    expect(button).toHaveTextContent('on');
    fireEvent.click(button);
    expect(button).toHaveTextContent('off');
    expect(window.localStorage.getItem(HAPTICS_STORAGE_KEY)).toBe('0');
  });
});
