/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Restore device defaults restores sidebar rows and thread details", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      await Promise.allSettled(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished));
    });
    await app.screenshot(label);
  };
  const project = await t3.project("Restore defaults demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter(event => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some(provider => provider.instanceId === "devReplay" && provider.models?.some(model => model.slug === "multi-turn"));
      }), Stream.runHead,
    );
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Appearance example", messages: ["Hello"] });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Customize", { exact: true }).tap();
  const dialog = screen.getByRole("dialog", "Sidebar thread rows");
  await dialog.getByRole("button", "Move Time and status", { exact: true }).press("ArrowDown");
  await dialog.getByRole("button", "Move Time and status", { exact: true }).press("ArrowDown");
  await dialog.getByRole("button", "Move Time and status", { exact: true }).press("ArrowDown");
  await dialog.getByRole("button", "Done", { exact: true }).tap();
  await screen.getByRole("button", "Thread details: 10 of 14 on", { exact: true }).tap();
  await screen.getByRole("menuitemcheckbox", "Open in editor", { exact: true }).tap();
  await browser.keyboard.press("Escape");
  await capture("customized-appearance");
  await t3.open("/settings/general");
  await screen.getByRole("button", "Restore device defaults", { exact: true }).waitFor();
  const enabledWithAppearanceOnly = await browser.evaluate(() => {
    const button = [...document.querySelectorAll<HTMLButtonElement>("button")].find(b => b.textContent?.includes("Restore device defaults"));
    if (!button) throw new Error("Restore button missing");
    return !button.disabled;
  });
  await capture("restore-availability");
  await screen.getByRole("switch", "In-app notifications", { exact: true }).tap();
  await screen.getByRole("button", "Restore device defaults", { exact: true }).tap();
  await screen.getByRole("button", "Confirm", { exact: true }).waitFor();
  const confirmation = await browser.evaluate(() => document.body.innerText);
  await capture("restore-confirmation");
  await screen.getByRole("button", "Confirm", { exact: true }).tap();
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Customize", { exact: true }).waitFor();
  await browser.evaluate(() => document.querySelector('[aria-label^="Thread details:"]')?.scrollIntoView({ block: "center", behavior: "instant" }));
  await capture("appearance-after-restore");
  const restored = await browser.evaluate(() => ({
    details: document.querySelector('[aria-label="Thread details: 10 of 14 on"]') !== null,
    resetRows: document.querySelector('[aria-label="Reset sidebar thread rows to default"]') !== null,
    resetDetails: document.querySelector('[aria-label="Reset thread details to default"]') !== null,
  }));
  expect({ enabledWithAppearanceOnly, listsRows: confirmation.includes("Sidebar thread rows"), listsDetails: confirmation.includes("Thread details"), ...restored }).toEqual({ enabledWithAppearanceOnly: true, listsRows: true, listsDetails: true, details: true, resetRows: false, resetDetails: false });
});
