import { render } from '@testing-library/svelte';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { setMockNavigating, setMockPage } from '../test/mocks/app-stores';

const afterNavigate = vi.fn();
const disableScrollHandling = vi.fn();

vi.mock('$app/navigation', () => ({
  afterNavigate: (callback: (args: { from: { url: URL } | null; to: { url: URL } | null }) => void) =>
    afterNavigate(callback),
  disableScrollHandling
}));

describe('root layout navigation behavior', () => {
  beforeEach(() => {
    afterNavigate.mockClear();
    disableScrollHandling.mockClear();
  });

  it('resets scroll position after route changes without hashes', async () => {
    const { default: Layout } = await import('./+layout.svelte');
    render(Layout);

    const navigateHandler = afterNavigate.mock.calls[0][0];
    const scrollToSpy = vi.spyOn(window, 'scrollTo');
    vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback: FrameRequestCallback) => {
      callback(0);
      return 0;
    });

    navigateHandler({
      from: { url: new URL('https://www.goodwalk.co.nz/about') },
      to: { url: new URL('https://www.goodwalk.co.nz/contact-us') }
    });

    expect(disableScrollHandling).toHaveBeenCalledTimes(1);
    expect(scrollToSpy).toHaveBeenCalledWith({ top: 0, left: 0, behavior: 'auto' });
  });

  it('does not reset scroll position for hash navigation', async () => {
    const { default: Layout } = await import('./+layout.svelte');
    render(Layout);

    const navigateHandler = afterNavigate.mock.calls[0][0];

    navigateHandler({
      from: { url: new URL('https://www.goodwalk.co.nz/about') },
      to: { url: new URL('https://www.goodwalk.co.nz/about#team') }
    });

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

  it('shows a route skeleton while navigating to a new page', async () => {
    setMockPage('https://www.goodwalk.co.nz/about');
    setMockNavigating('https://www.goodwalk.co.nz/contact-us', 'https://www.goodwalk.co.nz/about');

    const { default: Layout } = await import('./+layout.svelte');
    const { getByLabelText, container } = render(Layout);

    expect(getByLabelText('Loading page')).toBeInTheDocument();
    expect(container.querySelector('[data-skeleton-variant="contact"]')).toBeInTheDocument();
  });

  it('does not show the skeleton for hash-only navigation', async () => {
    setMockPage('https://www.goodwalk.co.nz/about');
    setMockNavigating('https://www.goodwalk.co.nz/about#team', 'https://www.goodwalk.co.nz/about');

    const { default: Layout } = await import('./+layout.svelte');
    const { queryByLabelText } = render(Layout);

    expect(queryByLabelText('Loading page')).not.toBeInTheDocument();
  });
});
