import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Copied 1Password field edge spaces survive saving", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    await browser.evaluate(() => {
      const inputs = [...document.querySelectorAll<HTMLInputElement>('input[aria-label$=" reference"]')];
      inputs.at(-1)?.scrollIntoView({ block: "center" });
      let panel = document.getElementById("evidence-observation");
      if (!panel) {
        panel = document.createElement("pre");
        panel.id = "evidence-observation";
        panel.style.cssText = "position:fixed;left:48px;bottom:48px;z-index:99999;background:#fff;border:1px solid #bbb;border-radius:8px;padding:12px;color:#111;font:12px monospace;pointer-events:none;max-width:530px;white-space:pre-wrap";
        document.body.append(panel);
      }
      panel.textContent = "Driver observation — actual input DOM values\n" + inputs.map(input => `${input.getAttribute("aria-label")}\n${JSON.stringify(input.value)}; invalid=${input.getAttribute("aria-invalid")}`).join("\n");
    });
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 6; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  await t3.project("Secret references");
  await t3.open();
  await screen.getByRole("button", "Add project", { exact: true }).waitFor({ state: "visible" });
  await app.open("/settings/secrets");
  await screen.getByRole("button", "Add provider", { exact: true }).tap();
  await screen.getByLabel("Name", { exact: true }).fill("op");
  await screen.getByLabel("Account", { exact: true }).fill("fixture");
  await screen.getByRole("button", "Add provider", { exact: true }).tap();
  await app.open("/settings/providers");
  await screen.getByRole("button", "Select Codex", { exact: true }).tap();
  await screen.getByLabel("Binary path", { exact: true }).fill("/usr/bin/false");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Add variable", { exact: true }).tap();
  await screen.getByLabel("Environment variable name 1", { exact: true }).fill("TRAILING_FIELD");
  await screen.getByLabel("Environment variable value 1 source", { exact: true }).tap();
  await screen.getByRole("option", "op", { exact: true }).tap();
  const trailing = screen.getByLabel("Environment variable value 1 reference", { exact: true });
  await trailing.fill("op://vault/item/credential ");
  await browser.keyboard.press("Enter");
  await capture("trailing-space-committed");
  await screen.getByRole("button", "Add variable", { exact: true }).tap();
  await screen.getByLabel("Environment variable name 2", { exact: true }).fill("LEADING_FIELD");
  await screen.getByLabel("Environment variable value 2 source", { exact: true }).tap();
  await screen.getByRole("option", "op", { exact: true }).tap();
  const leading = screen.getByLabel("Environment variable value 2 reference", { exact: true });
  await leading.fill("op://vault/item/ credential");
  await browser.keyboard.press("Enter");
  await capture("leading-space-committed");
  const observed = { trailing: await trailing.inputValue(), leadingInvalid: await leading.getAttribute("aria-invalid") };
  await browser.reload();
  await screen.getByLabel("Environment variable value 1 reference", { exact: true }).waitFor({state: "visible"});
  await capture("saved-after-reload");
  await expect(observed).toEqual({ trailing: "op://vault/item/credential ", leadingInvalid: "false" });
  await expect(screen.getByLabel("Environment variable value 1 reference", { exact: true })).toHaveValue("op://vault/item/credential ");
  await expect(screen.getByLabel("Environment variable value 2 reference", { exact: true })).toHaveValue("op://vault/item/ credential");
});
