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',
      pictureWidth: 8,
      pictureHeight: 4,
      href: 'https://example.com/diagram',
      isBackground: false,
      layout: {},
    },
    {
      kind: 'attachment',
      id: 'attachment-1',
      resourceId: 'resource-file',
      filename: 'notes.txt',
      size: 12,
      layout: {},
    },
    {
      kind: 'ink',
      id: 'ink-1',
      strokes: [
        {
          points: [
            { x: 10, y: 20 },
            { x: 15, y: 25 },
            { x: 30, y: 40 },
          ],
          width: 2,
          color: 0xff0000,
          transparency: 255,
        },
      ],
      children: [],
      boundingBox: { x: 10, y: 20, width: 20, height: 20 },
      layout: {},
    },
  ],
  diagnostics: [],
};

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

  it('renders semantic formatting, links, tables, and a signed image resource', async () => {
    const previewResource = 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}
        previewResource={previewResource}
      />
    );

    expect(screen.getByText('Styled')).toHaveStyle({
      fontWeight: '700',
    });
    expect(screen.getByRole('link', { name: 'link' })).toHaveAttribute(
      'href',
      'https://example.com/'
    );
    expect(screen.getByRole('table')).toHaveTextContent('AB');
    expect(
      screen.getByRole('img', { name: '1 handwritten or drawn stroke' })
    ).toHaveAttribute('viewBox', '-60 -50 160 160');
    expect(document.querySelector('.onenote-ink path')).toHaveAttribute(
      'd',
      'M 10 20 L 15 25 30 40'
    );
    expect(document.querySelector('.onenote-ink path')).toHaveAttribute(
      'stroke-opacity',
      '0'
    );
    await waitFor(() =>
      expect(
        screen.getByRole('img', { name: 'Embedded diagram' })
      ).toHaveAttribute('src', 'blob:local-image')
    );
    expect(screen.getByRole('img', { name: 'Embedded diagram' })).toHaveStyle({
      width: '384px',
      height: 'auto',
    });
    expect(
      screen.getByRole('link', { name: 'Embedded diagram' })
    ).toHaveAttribute('href', 'https://example.com/diagram');
  });

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

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

  it('does not turn a rejected image preview into an implicit download', async () => {
    const previewResource = vi.fn(async () => {
      throw new Error(
        'This image can be downloaded but is not approved for automatic preview.'
      );
    });
    const downloadResource = vi.fn(async () => undefined);
    render(
      <PageReader
        page={page}
        loading={false}
        previewResource={previewResource}
        downloadResource={downloadResource}
      />
    );

    expect(
      await screen.findByText(/not approved for automatic preview/i)
    ).toBeVisible();
    expect(previewResource).toHaveBeenCalledWith('resource-image');
    expect(downloadResource).not.toHaveBeenCalled();

    await userEvent.click(
      screen.getByRole('button', { name: 'Download original image' })
    );
    expect(downloadResource).toHaveBeenCalledWith('resource-image', undefined);
  });

  it('shows an explicit notice when the display projection is truncated', () => {
    render(
      <PageReader
        page={{
          ...page,
          blocks: [textBlock('First', 'first'), textBlock('Second', 'second')],
        }}
        loading={false}
        renderLimits={{ maxBlocks: 1 }}
      />
    );

    expect(screen.getByText('First')).toBeInTheDocument();
    expect(screen.queryByText('Second')).not.toBeInTheDocument();
    expect(screen.getByRole('status')).toHaveTextContent(
      'safe browser display budget'
    );
  });
});

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: {},
  };
}
