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

import type { OneNotePageDto } from '../onenote/model/dto.js';
import { PageReader } from './PageReader.js';

const page: OneNotePageDto = {
  id: 'page-1',
  title: 'Visual page',
  text: 'Styled link\nA\tB',
  textPreview: 'Styled link A B',
  blocks: [
    {
      kind: 'text',
      id: 'text-1',
      sourceText: 'Styled link',
      text: 'Styled link',
      paragraphStyle: {},
      layout: {},
      runs: [
        {
          start: 0,
          end: 7,
          text: 'Styled ',
          style: {
            bold: true,
            highlight: { kind: 'rgb', red: 255, green: 255, blue: 0 },
          },
        },
        {
          start: 7,
          end: 11,
          text: 'link',
          style: { underline: true },
          href: 'https://example.com/',
        },
      ],
    },
    {
      kind: 'table',
      id: 'table-1',
      rows: [
        {
          id: 'row-1',
          cells: [
            { id: 'cell-a', blocks: [textBlock('A', 'text-a')] },
            { id: 'cell-b', blocks: [textBlock('B', 'text-b')] },
          ],
        },
      ],
      columnWidths: [2, 3],
      lockedColumns: [false, false],
      bordersVisible: true,
      layout: {},
    },
    {
      kind: 'image',
      id: 'image-1',
      resourceId: 'resource-image',
      altText: 'Embedded diagram',
      isBackground: false,
      layout: {},
    },
    {
      kind: 'attachment',
      id: 'attachment-1',
      resourceId: 'resource-file',
      filename: 'notes.txt',
      size: 12,
      layout: {},
    },
  ],
  diagnostics: [],
};

describe('PageReader structured content', () => {
  beforeEach(() => {
    vi.stubGlobal('URL', {
      ...URL,
      createObjectURL: vi.fn(() => 'blob:local-image'),
      revokeObjectURL: vi.fn(),
    });
  });

  it('renders semantic formatting, links, tables, and a signed image resource', async () => {
    const loadResource = vi.fn(async () => ({
      id: 'resource-image',
      kind: 'image' as const,
      mediaType: 'image/png',
      browserRenderable: true,
      size: 8,
      bytes: Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10).buffer,
    }));

    render(
      <PageReader page={page} loading={false} loadResource={loadResource} />
    );

    expect(screen.getByText('Styled').parentElement).toHaveStyle({
      fontWeight: '700',
    });
    expect(screen.getByRole('link', { name: 'link' })).toHaveAttribute(
      'href',
      'https://example.com/'
    );
    expect(screen.getByRole('table')).toHaveTextContent('AB');
    await waitFor(() =>
      expect(
        screen.getByRole('img', { name: 'Embedded diagram' })
      ).toHaveAttribute('src', 'blob:local-image')
    );
  });

  it('downloads an attachment only after an explicit user action', async () => {
    const downloadResource = vi.fn(async () => undefined);
    render(
      <PageReader
        page={page}
        loading={false}
        loadResource={async () => {
          throw new Error('not renderable');
        }}
        downloadResource={downloadResource}
      />
    );

    await userEvent.click(
      screen.getByRole('button', { name: 'Download attachment' })
    );
    expect(downloadResource).toHaveBeenCalledWith('resource-file', 'notes.txt');
  });
});

function textBlock(text: string, id: string) {
  return {
    kind: 'text' as const,
    id,
    sourceText: text,
    text,
    runs: [{ start: 0, end: text.length, text, style: {} }],
    paragraphStyle: {},
    layout: {},
  };
}
