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

test("Notebook language labels fall back after sanitizing", WEB, async ({ t3, app, screen, browser }) => {
  const names = { empty: "", whitespace: "   ", cyrillic: "Питон", python: "python" };
  const files = Object.fromEntries(Object.entries(names).map(([file, name]) => [`${file}.ipynb`, JSON.stringify({
    nbformat: 4, nbformat_minor: 5, metadata: { language_info: { name } },
    cells: [{ id: "hello", cell_type: "code", source: ['print("hello")'], metadata: {}, execution_count: null, outputs: [] }],
  })]));
  const project = await t3.project("notebook-demo", files);
  const thread = await t3.thread({ project, title: "Review notebook languages", messages: ["Start"] });
  await browser.setViewport({ width: 1440, height: 900 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  await screen.getByRole("button", "Maximize panel", { exact: false }).tap();
  const observed: string[] = [];
  for (const file of Object.keys(names)) {
    await screen.getByRole("treeitem", `${file}.ipynb`).tap();
    await screen.getByText("Saved outputs only. Code is never executed.").waitFor();
    await browser.locator('section[aria-label="Cell 1"] [data-file]').waitFor();
    await app.screenshot(file);
    observed.push(await browser.evaluate(() => {
      const cell = document.querySelector('section[aria-label="Cell 1"]')!;
      const status = Array.from(document.querySelectorAll('[role="status"]')).find(el => el.textContent?.includes('1 cell'))!;
      return `${status.textContent?.replace(/\s+/g, ' ').trim()}|${cell.firstElementChild?.textContent?.trim()}`;
    }));
  }
  expect(observed.map(value => value.replace(/ · [^·|]+\|/, '|'))).toEqual([
    "1 cell · text|text · 1", "1 cell · text|text · 1", "1 cell · text|text · 1", "1 cell · python|python · 1",
  ]);
});
