// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';

// error.tsx fires telemetry on mount — stub it so the chrome can render in isolation.
vi.mock('@/lib/telemetry', () => ({ trackEvent: vi.fn() }));

import GlobalError from '@/app/error';
import NotFound from '@/app/not-found';
import DashboardLoading from '@/app/(dashboard)/loading';

/**
 * UX-4 — page-chrome adoption guard. Verifies admin's error / not-found /
 * loading surfaces render the shared `@bytelyst/dashboard-components` chrome
 * and that the error retry handler is wired to Next's `reset`.
 */
describe('page chrome (dashboard-components)', () => {
  let container: HTMLDivElement;
  let root: Root;

  beforeEach(() => {
    (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
      true;
    container = document.createElement('div');
    document.body.appendChild(container);
    root = createRoot(container);
  });

  afterEach(() => {
    act(() => root.unmount());
    container.remove();
  });

  it('error.tsx renders ErrorPage with the message and a working retry', () => {
    const reset = vi.fn();
    act(() => {
      root.render(
        <GlobalError error={Object.assign(new Error('kaboom'), { digest: 'd1' })} reset={reset} />
      );
    });
    expect(container.textContent).toContain('Something went wrong');
    expect(container.textContent).toContain('kaboom');

    const retry = Array.from(container.querySelectorAll('button')).find(b =>
      /try again|retry/i.test(b.textContent ?? '')
    );
    expect(retry).toBeTruthy();
    act(() => retry!.dispatchEvent(new MouseEvent('click', { bubbles: true })));
    expect(reset).toHaveBeenCalledTimes(1);
  });

  it('not-found.tsx renders the NotFoundPage chrome', () => {
    act(() => {
      root.render(<NotFound />);
    });
    expect(container.querySelector('a[href="/"]')).toBeTruthy();
  });

  it('loading.tsx renders an accessible LoadingSpinner', () => {
    act(() => {
      root.render(<DashboardLoading />);
    });
    expect(container.querySelector('[role="status"]')).toBeTruthy();
  });
});
