import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

test(
  "A notebook with a Julia kernelspec shows Julia code cells",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const notebook = {
      nbformat: 4,
      nbformat_minor: 5,
      metadata: { kernelspec: { name: "julia-1.11", display_name: "Julia 1.11" } },
      cells: [
        {
          id: "total",
          cell_type: "code",
          source: ["sum(1:10)"],
          metadata: {},
          execution_count: null,
          outputs: [],
        },
      ],
    };
    await t3.project("demo", { "calculations.ipynb": JSON.stringify(notebook) });
    await t3.open();
    await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
    await screen.getByTestId("composer-editor").waitFor();
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("calculations.ipynb");
    await screen.getByRole("option", "calculations.ipynb", { exact: false }).tap();
    const cell = screen.getByRole("region", "Cell 1");
    const languageLabel = cell.getByText(/^.+ · 1$/);
    await languageLabel.waitFor({ timeout: 120_000 });
    await cell.getByRole("status", "Loading code...").waitFor({ state: "hidden", timeout: 60_000 });
    const tokenColors = () =>
      browser.evaluate(() => {
        const source = document.querySelector('section[aria-label="Cell 1"] diffs-container');
        const spans = source?.shadowRoot?.querySelectorAll("[data-line] span") ?? [];
        return new Set(Array.from(spans, (span) => getComputedStyle(span).color)).size;
      });
    // A cell labeled Julia waits for its highlighting; a plain-text cell has none to wait for.
    await expect
      .poll(
        async () =>
          !/julia/i.test((await languageLabel.textContent()) ?? "") || (await tokenColors()) > 1,
        { timeout: 30_000 },
      )
      .toBe(true);
    await app.screenshot("julia-cell");
    expect(await languageLabel.textContent()).toMatch(/julia · 1/i);
    expect(await tokenColors()).toBeGreaterThan(1);
  },
);
