import { renderHook, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { usePWA } from './usePWA';

// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
});

// Mock beforeinstallprompt
const mockPrompt = vi.fn();
Object.defineProperty(window, 'beforeinstallprompt', {
  writable: true,
  value: null,
});

describe('usePWA', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    // Reset beforeinstallprompt
    (window as any).beforeinstallprompt = null;
  });

  it('should return PWA hook', () => {
    const { result } = renderHook(() => usePWA());

    expect(result.current).toBeDefined();
    expect(result.current).toHaveProperty('isInstallable');
    expect(result.current).toHaveProperty('isInstalled');
    expect(result.current).toHaveProperty('install');
  });

  it('should detect if PWA is installable', () => {
    const { result } = renderHook(() => usePWA());

    expect(typeof result.current.isInstallable).toBe('boolean');
  });

  it('should detect if PWA is installed', () => {
    const { result } = renderHook(() => usePWA());

    expect(typeof result.current.isInstalled).toBe('boolean');
  });

  it('should provide install function', () => {
    const { result } = renderHook(() => usePWA());

    expect(typeof result.current.install).toBe('function');
  });

  it('should handle install when prompt is available', async () => {
    const mockEvent = {
      prompt: mockPrompt,
      userChoice: Promise.resolve({ outcome: 'accepted' }),
    };

    (window as any).beforeinstallprompt = mockEvent;

    const { result, rerender } = renderHook(() => usePWA());

    // Rerender to trigger effect
    rerender();

    if (result.current.isInstallable) {
      await act(async () => {
        await result.current.install();
      });

      expect(mockPrompt).toHaveBeenCalled();
    }
  });
});
