import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';

import NpsModal from './NpsModal';

const mockPrompt = { type: 'day_7', day: 7 };

describe('NpsModal', () => {
    it('renders 11 score buttons with aria-labels', () => {
        render(<NpsModal nps_prompt={mockPrompt} />);
        for (let i = 0; i <= 10; i++) {
            const button = screen.getByRole('button', { name: new RegExp(`Score ${i} out of 10`) });
            expect(button).toBeInTheDocument();
        }
    });

    it('marks selected score with aria-pressed=true', async () => {
        const user = userEvent.setup();
        render(<NpsModal nps_prompt={mockPrompt} />);
        const btn8 = screen.getByRole('button', { name: /Score 8 out of 10/i });
        await user.click(btn8);
        expect(btn8).toHaveAttribute('aria-pressed', 'true');
        // Other buttons should have aria-pressed=false
        const btn7 = screen.getByRole('button', { name: /Score 7 out of 10/i });
        expect(btn7).toHaveAttribute('aria-pressed', 'false');
    });

    it('shows feedback textarea after score is selected', async () => {
        render(<NpsModal nps_prompt={mockPrompt} />);
        await userEvent.click(screen.getByRole('button', { name: /Score 9 out of 10/i }));
        expect(screen.getByLabelText(/main reason/i)).toBeInTheDocument();
    });

    it('submits score via router.post to nps.store', async () => {
        const { router } = await import('@inertiajs/react');
        render(<NpsModal nps_prompt={mockPrompt} />);
        await userEvent.click(screen.getByRole('button', { name: /Score 8 out of 10/i }));
        await userEvent.click(screen.getByRole('button', { name: /submit/i }));
        expect(router.post).toHaveBeenCalledWith(
            expect.stringContaining('nps'),
            expect.objectContaining({ score: 8 }),
            expect.any(Object),
        );
    });

    it('skip button dismisses the modal', async () => {
        render(<NpsModal nps_prompt={mockPrompt} />);
        await userEvent.click(screen.getByRole('button', { name: /skip/i }));
        expect(screen.queryByRole('button', { name: /Score 9 out of 10/i })).not.toBeInTheDocument();
    });

    it('does not render when nps_prompt is false', () => {
        const { container } = render(<NpsModal nps_prompt={false} />);
        expect(container).toBeEmptyDOMElement();
    });

    it('includes descriptive text in aria-labels', () => {
        render(<NpsModal nps_prompt={mockPrompt} />);
        expect(screen.getByRole('button', { name: /Score 0 out of 10 — Very unlikely/i })).toBeInTheDocument();
        expect(screen.getByRole('button', { name: /Score 5 out of 10 — Neutral/i })).toBeInTheDocument();
        expect(screen.getByRole('button', { name: /Score 10 out of 10 — Very likely/i })).toBeInTheDocument();
    });
});
