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

const files = [
  { name: "deploy.sh", type: "application/x-shellscript", text: 'echo "Deployment ready"\n', marker: "Deployment ready" },
  { name: "script.rb", type: "application/x-ruby", text: 'puts "Ruby ready"\n', marker: "Ruby ready" },
  { name: "index.php", type: "application/x-php", text: '<?php echo "PHP ready";\n', marker: "PHP ready" },
  { name: "init.fish", type: "application/x-fishscript", text: 'echo "Fish ready"\n', marker: "Fish ready" },
  { name: "main.dart", type: "application/vnd.dart", text: 'void main() { print("Dart ready"); }\n', marker: "Dart ready" },
  { name: "App.tsx", type: "application/x-tiled-tsx", text: 'export default () => <h1>TSX ready</h1>;\n', marker: "TSX ready" },
  { name: "guide.mdx", type: "application/x-genesis-32x-rom", text: '# Guide ready\n\nA **Markdown** attachment.\n', marker: "Guide ready" },
  { name: "game.32x", type: "application/x-genesis-32x-rom", text: "", marker: "No preview for this file" },
  { name: "control.js", type: "text/javascript", text: 'console.log("JavaScript ready");\n', marker: "JavaScript ready" },
  { name: "control.md", type: "text/markdown", text: '# Markdown ready\n', marker: "Markdown ready" },
];

test("Linux MIME attachments preview source and MDX while ROM stays unsupported", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Attachment preview");
  const seed = (model: string) => t3.thread({ project, title: "Linux attachment previews", messages: ["Start"], model });
  const thread = await seed("default").catch((error) => {
    if (!String(error).includes("Model default is not advertised")) throw error;
    return seed("showcase");
  });
  await t3.open(thread);
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({state: "attached"});
  // Feed the exact File.type values Chromium reports with the Linux MIME glob database.
  await browser.evaluate(({input, files}) => {
    const picker = document.querySelector<HTMLInputElement>(input)!;
    const transfer = new DataTransfer();
    for (const file of files) {
      const content = file.name === "game.32x" ? crypto.getRandomValues(new Uint8Array(256)) : file.text;
      transfer.items.add(new File([content], file.name, {type: file.type}));
    }
    picker.files = transfer.files;
    picker.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  }, {input, files});
  const outcomes: Record<string, boolean> = {};
  for (const file of files) {
    await screen.getByRole("button", `File attachment, ${file.name},`, {exact:false}).tap();
    await browser.locator('[role="dialog"]').waitFor();
    await browser.locator('[role="dialog"] button[aria-label="Close"]').waitFor();
    await browser.locator('[role="dialog"] [aria-label="Loading file"]').waitFor({state: "hidden"});
    await screen.getByText("Loading code...", {exact:true}).waitFor({state: "hidden"});
    await expect.poll(() => browser.evaluate((marker) => {
      const dialog = document.querySelector('[role="dialog"]')!;
      const source = dialog.querySelector("diffs-container")?.shadowRoot;
      const text = (source?.textContent ?? "") + (dialog.textContent ?? "");
      return text.includes(marker) || text.includes("No preview for this file");
    }, file.marker)).toBe(true);
    // Capture every type before the aggregate assertion so base and head have matching evidence.
    await app.screenshot(file.name);
    outcomes[file.name] = await browser.evaluate((file) => {
      const dialog = document.querySelector('[role="dialog"]')!;
      if (file.name.endsWith('.mdx') || file.name === 'control.md') {
        return [...dialog.querySelectorAll('h1')].some(el => el.textContent === file.marker);
      }
      const source = dialog.querySelector("diffs-container")?.shadowRoot;
      return (source?.textContent ?? dialog.textContent ?? "").includes(file.marker);
    }, file);
    await browser.locator('[role="dialog"] button[aria-label="Close"]').click();
  }
  await expect(outcomes).toEqual(Object.fromEntries(files.map(file => [file.name, true])));
});
