import { cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { AppShell } from '@add-ideas/toolbox-shell-react';
import type {
  ToolboxAppManifest,
  ToolboxCatalog,
} from '@add-ideas/toolbox-contract';
import { toolboxApp } from '../src/toolboxApp';

afterEach(cleanup);

const pdfApp: ToolboxAppManifest = {
  ...toolboxApp,
  id: 'de.add-ideas.pdf-tools',
  name: 'PDF Workbench',
  version: '0.3.4',
  description: 'Local PDF page operations in your browser.',
  categories: ['documents', 'pdf'],
  tags: ['merge', 'split', 'rotate', 'reorder'],
  requirements: {
    ...toolboxApp.requirements,
    workers: true,
    indexedDb: true,
  },
};

const catalog: ToolboxCatalog = {
  schemaVersion: 1,
  id: 'integration-test',
  name: 'Integration test toolbox',
  home: './',
  theme: {
    mode: 'system',
    brand: 'Test Toolbox',
  },
  apps: [
    {
      manifest: './apps/xslt/toolbox-app.json',
      enabled: true,
    },
    {
      manifest: './apps/pdf/toolbox-app.json',
      enabled: true,
    },
  ],
};

describe('toolbox shell integration', () => {
  it('keeps the app usable standalone with its XSLT Help action', () => {
    render(
      <AppShell
        app={toolboxApp}
        contextOptions={{ location: 'https://example.test/deep/nested/app/' }}
        appActions={<button type="button">Help</button>}
      >
        <p>XSLT workbench</p>
      </AppShell>
    );

    expect(screen.getByText('XSLT workbench')).toBeTruthy();
    expect(screen.getByRole('button', { name: 'Help' })).toBeTruthy();
    expect(
      screen.getByRole('link', { name: 'Source' }).getAttribute('href')
    ).toBe('https://git.add-ideas.de/zemion/xslt-tools/src/tag/v0.3.2');
    expect(
      screen.queryByRole('navigation', { name: 'Toolbox applications' })
    ).toBeNull();
  });

  it('loads a same-origin catalogue and carries context through switcher links', async () => {
    const location =
      'https://example.test/deep/nested/app/?toolbox=/toolbox.catalog.json';
    const fetch = vi.fn(createCatalogFetch());
    const { container } = render(
      <AppShell
        app={toolboxApp}
        manifestUrl="https://example.test/deep/nested/app/toolbox-app.json"
        contextOptions={{ location, fetch }}
      >
        <p>XSLT workbench</p>
      </AppShell>
    );

    const navigation = await screen.findByRole('navigation', {
      name: 'Toolbox applications',
    });
    expect(navigation).toBeTruthy();
    expect(
      container.firstElementChild?.getAttribute('data-toolbox-context')
    ).toBe('connected');
    expect(
      screen.getByRole('link', { name: 'Test Toolbox' }).getAttribute('href')
    ).toBe('https://example.test/');

    const pdfLink = screen.getByRole('link', { name: 'PDF Workbench' });
    const pdfUrl = new URL(pdfLink.getAttribute('href') ?? '');
    expect(pdfUrl.pathname).toBe('/apps/pdf/');
    expect(pdfUrl.searchParams.get('toolbox')).toBe(
      'https://example.test/toolbox.catalog.json'
    );
    expect(fetch).toHaveBeenCalledTimes(3);

    await waitFor(() => {
      expect(
        screen
          .getByRole('link', { name: 'XSLT tools' })
          .getAttribute('aria-current')
      ).toBe('page');
    });
  });
});

function createCatalogFetch() {
  return async (input: string | URL | Request): Promise<Response> => {
    const url = new URL(
      typeof input === 'string'
        ? input
        : input instanceof URL
          ? input.href
          : input.url
    );
    const documents = new Map<string, unknown>([
      ['/toolbox.catalog.json', catalog],
      ['/apps/xslt/toolbox-app.json', toolboxApp],
      ['/apps/pdf/toolbox-app.json', pdfApp],
    ]);
    const document = documents.get(url.pathname);

    if (document === undefined) {
      return {
        ok: false,
        status: 404,
        json: async () => ({}),
      } as Response;
    }

    return {
      ok: true,
      status: 200,
      json: async () => document,
    } as Response;
  };
}
