
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { InstallPrompt } from './install-prompt';

// Mock BeforeInstallPromptEvent
class BeforeInstallPromptEvent extends Event {
    prompt: () => Promise<void>;
    userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>;

    constructor() {
        super('beforeinstallprompt');
        this.prompt = vi.fn().mockResolvedValue(undefined);
        this.userChoice = Promise.resolve({ outcome: 'accepted' });
    }
}

describe('InstallPrompt Component', () => {
    afterEach(() => {
        vi.restoreAllMocks();
    });

    it('should not render initially', () => {
        render(<InstallPrompt />);
        expect(screen.queryByText(/Install App/i)).toBeNull();
    });

    it('should appear when beforeinstallprompt event fires', async () => {
        render(<InstallPrompt />);

        // Simulate event
        const event = new BeforeInstallPromptEvent();
        window.dispatchEvent(event);

        await waitFor(() => {
            expect(screen.getByText(/Install Test01/i)).toBeInTheDocument();
        });
    });

    it('scrolls call prompt() when "Install" is clicked', async () => {
        render(<InstallPrompt />);

        // Trigger show
        const event = new BeforeInstallPromptEvent();
        window.dispatchEvent(event);

        // Find button and click
        const button = await screen.findByRole('button', { name: /Install/i });
        fireEvent.click(button);

        // Verify prompt was called on the stashed event
        expect(event.prompt).toHaveBeenCalled();
    });

    it('should dismiss when "Not Now" is clicked', async () => {
        render(<InstallPrompt />);

        // Trigger show
        const event = new BeforeInstallPromptEvent();
        window.dispatchEvent(event);

        // Find dismiss button
        const closeButton = await screen.findByRole('button', { name: /Not Now/i });
        fireEvent.click(closeButton);

        // Verify it disappears
        await waitFor(() => {
            expect(screen.queryByText(/Install Test01/i)).toBeNull();
        });
    });
});
