import { DatabaseSync } from "node:sqlite";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Translated sidebar search times stay on one line", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo-project");
  const titles = ["Refactor sidebar search ranking for remote sessions", "Sidebar row height audit", "Fix sidebar layout in settings"];
  const threads = [];
  for (const title of titles) threads.push(await t3.thread({ project, title, messages: ["Start"] }));
  // Age only this scenario's synthetic records before the browser loads its initial snapshot.
  const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, { timeout: 30000 });
  db.exec("BEGIN IMMEDIATE");
  const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'orchestration_v2_projection_%'").all() as { name: string }[];
  for (const [index, thread] of threads.entries()) {
    const stamp = new Date(Date.now() - [2, 3, 16][index] * 3600000 - 5 * 60000).toISOString();
    const age = (value: unknown): unknown => {
      if (typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:/.test(value)) return stamp;
      if (Array.isArray(value)) return value.map(age);
      if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([k,v]) => [k, age(v)]));
      return value;
    };
    for (const { name } of tables) {
      const columns = db.prepare(`PRAGMA table_info("${name}")`).all() as { name: string; pk: number }[];
      if (!columns.some(c => c.name === "thread_id")) continue;
      const rows = db.prepare(`SELECT * FROM "${name}" WHERE thread_id = ?`).all(thread.threadId);
      for (const row of rows) {
        const updates = columns.filter(c => c.name.endsWith("_at") || c.name === "payload_json");
        if (!updates.length) continue;
        const values = updates.map(c => c.name === "payload_json" ? JSON.stringify(age(JSON.parse(String(row[c.name])))) : row[c.name] == null ? null : stamp);
        db.prepare(`UPDATE "${name}" SET ${updates.map(c => `"${c.name}" = ?`).join(",")} WHERE ${columns.filter(c => c.pk).map(c => `"${c.name}" = ?`).join(" AND ")}`).run(...values, ...columns.filter(c => c.pk).map(c => row[c.name]));
      }
    }
  }
  db.exec("COMMIT");
  db.close();
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).tap();
  await screen.getByText("中文（简体）", { exact: true }).tap();
  await t3.open(threads[0]);
  await screen.getByRole("combobox", "搜索会话").fill("sidebar");
  await browser.locator('#sidebar-thread-search-results [role="option"]').first().waitFor();
  await app.screenshot("translated-search-times");
  const dimensions = await browser.evaluate<{text: string; height: number; lineHeight: number; rowHeight: number}[]>(`(() => [...document.querySelectorAll('#sidebar-thread-search-results [role="option"]')].map(row => { const time = [...row.querySelectorAll('span')].find(el => el.classList.contains('tabular-nums')); return { text: time?.textContent, height: time?.getBoundingClientRect().height, lineHeight: parseFloat(getComputedStyle(time).lineHeight), rowHeight: row.getBoundingClientRect().height }; }))()`);
  expect(dimensions.map(d => d.text).sort()).toEqual(["16 小时", "2 小时", "3 小时"]);
  for (const label of dimensions) expect(label.height).toBeLessThanOrEqual(label.lineHeight);
});
