/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const payload = JSON.stringify({ version: 1, name: 'Dusk', appearance: 'dark', colors: { accent: '#336699' }, notes: '語'.repeat(90000) });
const warning = 'That file is 264 KB. Theme files are only a few KB, so this one was not read (limit 256 KB).';

test('Pasted theme JSON obeys the same UTF-8 byte limit as a file', WEB, async ({ t3, app, screen, browser }) => {
  await t3.project('demo');
  await t3.open('/settings/appearance');
  await screen.getByRole('button', 'Add theme', { exact: true }).tap();
  const dialog = screen.getByRole('dialog', 'Add a theme');
  await browser.evaluate((text) => {
    const input = document.querySelector('input[type="file"]') as HTMLInputElement;
    const files = new DataTransfer();
    files.items.add(new File([text], 'dusk.json', { type: 'application/json' }));
    input.files = files.files;
    input.dispatchEvent(new Event('change', { bubbles: true }));
  }, payload);
  await dialog.getByText(warning, { exact: true }).waitFor();
  await app.screenshot('oversized-utf8-file-rejected');
  await dialog.getByRole('button', 'Cancel', { exact: true }).tap();
  await dialog.waitFor({ state: 'hidden' });
  await screen.getByRole('button', 'Add theme', { exact: true }).tap();
  await dialog.getByRole('textbox', 'Theme JSON').tap();
  await browser.evaluate(async (text) => { await navigator.clipboard.writeText(text); }, payload);
  await browser.keyboard.press('Control+V');
  await dialog.getByRole('button', 'Add theme', { exact: true }).tap();
  try {
    await expect(dialog.getByText(warning, { exact: true })).toBeVisible();
    await expect.poll(() => browser.evaluate(() => JSON.parse(localStorage.getItem('t3code:themes:v1') ?? '[]').length)).toBe(0);
  } finally {
    await browser.evaluate(() => {
      const dusk = [...document.querySelectorAll('button')].find((button) => button.getAttribute('aria-label')?.startsWith('Use Dusk theme'));
      dusk?.scrollIntoView({ block: 'center' });
    });
    await app.screenshot('after-pasted-utf8-theme-submit');
  }
});
