import { describe, it, expect, beforeEach, vi } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import { renderWithProviders } from '../test/utils';

vi.mock('../lib/api', () => ({
  api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
  ApiError: class extends Error {},
}));

const drive = vi.fn();
vi.mock('driver.js', () => ({ driver: vi.fn(() => ({ drive })) }));
vi.mock('driver.js/dist/driver.css', () => ({}));

import { driver } from 'driver.js';
import { api } from '../lib/api';
import { useAuthStore } from '../stores/authStore';
import AppointmentsPage from './AppointmentsPage';
import { appointmentsTour } from '../lib/tour/tours/appointments';
import { resolveSteps } from '../lib/tour/resolveSteps';

const get = api.get as ReturnType<typeof vi.fn>;
const driverMock = driver as unknown as ReturnType<typeof vi.fn>;

/** پاسخ‌های ثابت صفحه؛ فقط وضعیت تور بین تست‌ها فرق می‌کند. */
function mockApi(seen: Record<string, number>) {
  get.mockImplementation((url: string) => {
    if (url.includes('/my/tours')) return Promise.resolve({ success: true, data: { seen } });
    if (url.includes('today-stats')) return Promise.resolve({ success: true, data: { total: 7, completed: 3, waiting: 2, cancelled: 1 } });
    if (url.includes('appointment-slots')) return Promise.resolve({ success: true, data: { sessions: [], empty_reason: 'holiday' } });
    if (url.includes('/my/appointments')) return Promise.resolve({ success: true, data: [], meta: { totalRecords: 0, totalPages: 0, currentPage: 1 } });
    return Promise.resolve({ success: true, data: [] });
  });
}

beforeEach(() => {
  get.mockReset();
  drive.mockReset();
  driverMock.mockClear();
  useAuthStore.setState({ primaryRole: 'doctor', dbUuid: 'doc1', doctorUuid: 'doc1' } as any);
});

describe('AppointmentsPage — راهنمای صفحه', () => {
  it('دکمهٔ راهنما کنار عنوان است', async () => {
    mockApi({});
    renderWithProviders(<AppointmentsPage />);

    expect(await screen.findByRole('button', { name: 'راهنمای این صفحه' })).toBeInTheDocument();
  });

  it('برای کاربری که تور را ندیده، خودکار اجرا می‌شود', async () => {
    mockApi({});
    renderWithProviders(<AppointmentsPage />);

    await waitFor(() => expect(drive).toHaveBeenCalledTimes(1), { timeout: 3000 });
  });

  it('برای کاربری که تور را دیده، خودکار اجرا نمی‌شود', async () => {
    mockApi({ appointments: appointmentsTour.version });
    renderWithProviders(<AppointmentsPage />);

    await screen.findByText('این روز تعطیل است');
    await new Promise((r) => setTimeout(r, 500));

    expect(drive).not.toHaveBeenCalled();
  });

  it('پزشک مستقل تب پزشکان ندارد، پس آن استپ از تور حذف می‌شود', async () => {
    mockApi({});
    renderWithProviders(<AppointmentsPage />);

    await waitFor(() => expect(drive).toHaveBeenCalled(), { timeout: 3000 });

    const anchors = driverMock.mock.calls[0][0].steps.map((s: { element: string }) => s.element);
    expect(anchors).not.toContain('[data-tour="appointments-doctors"]');
    expect(anchors).toContain('[data-tour="appointments-stats"]');
    // شمارندهٔ تور همان تعداد استپِ واقعاً موجود است، نه کل تعریف
    expect(anchors).toHaveLength(resolveSteps(appointmentsTour.steps).length);
    expect(anchors.length).toBeLessThan(appointmentsTour.steps.length);
  });
});
