import * as fs from "node:fs/promises";
import { T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

// Provider transcripts are generated synthetic usage, isolated from the host.
test("Usage clock preference stays explicit across French German Spanish and English", WEB, async ({t3, app, screen, browser}) => {
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  const claudeHome = `${T3_HOME}/synthetic-claude`;
  const codexHome = `${T3_HOME}/synthetic-codex`;
  await fs.mkdir(`${claudeHome}/projects/demo`, {recursive:true});
  await fs.mkdir(codexHome, {recursive:true});
  const hour = Math.floor(Date.now()/3600000)*3600000;
  const lines = Array.from({length:24},(_,i)=>JSON.stringify({type:"assistant",timestamp:new Date(hour-i*3600000).toISOString(),requestId:`req-${i}`,sessionId:"clock-demo",message:{id:`msg-${i}`,model:"claude-sonnet-4-6",usage:{input_tokens:10000,output_tokens:2000}}}));
  await fs.writeFile(`${claudeHome}/projects/demo/session.jsonl`,lines.join("\n")+"\n");
  settings.providerInstances.claudeAgent.config = {homePath: claudeHome};
  settings.providerInstances.codex.config.homePath = codexHome;
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const project = await t3.project("Clock preference demo");
  await t3.thread({project, title: "Synthetic usage demo", messages: ["Hello"]});
  await t3.open("/settings/general");
  await screen.getByRole("combobox", "Timestamp format", {exact:true}).tap();
  await screen.getByRole("option", "12-hour", {exact:true}).tap();
  const locales = [
    {id:"fr",name:"Français",language:"Langue",format:"Format de l’horodatage",hour:"Heure",heading:"Coût par heure",h24:"24 heures"},
    {id:"de",name:"Deutsch",language:"Sprache",format:"Zeitstempelformat",hour:"Stunde",heading:"Kosten pro Stunde",h24:"24-Stunden-Format"},
    {id:"es",name:"Español",language:"Idioma",format:"Formato de marca de tiempo",hour:"Hora",heading:"Coste por hora",h24:"24 horas"},
    {id:"en",name:"English",language:"Language",format:"Timestamp format",hour:"Hour",heading:"Hourly cost",h24:"24-hour"},
    {id:"fr24",name:"Français",language:"Langue",format:"Format de l’horodatage",hour:"Heure",heading:"Coût par heure",h24:"24 heures"},
  ];
  const results: Array<{label:string; text:string; twelve:boolean}> = [];
  let languageLabel = "Language";
  for (const locale of locales) {
    await t3.open("/settings/general");
    await screen.getByRole("combobox", languageLabel, {exact:true}).tap();
    await screen.getByRole("option", locale.name, {exact:true}).tap();
    languageLabel = locale.language;
    if (locale.id === "fr") await app.screenshot("fr-12-hour-settings");
    for (const twelve of [locale.id !== "fr24"]) {
      if (!twelve) {
        await t3.open("/settings/general");
        await screen.getByRole("combobox",locale.format,{exact:true}).tap();
        await screen.getByRole("option",locale.h24,{exact:true}).tap();
      }
      await browser.evaluate(() => { localStorage.setItem("t3code:usage-page-preferences:v1", JSON.stringify({metric:"cost",windowDays:1})); return null; });
      await t3.open("/usage");
      await screen.getByText(locale.heading,{exact:true}).waitFor({timeout:60000});
      await browser.evaluate(async () => {
        await new Promise<void>((resolve) => {
          const ready = () => !document.querySelector('[aria-busy="true"]');
          if (ready()) return resolve();
          const observer = new MutationObserver(() => {
            if (ready()) { observer.disconnect(); resolve(); }
          });
          observer.observe(document.body, {attributes:true, subtree:true});
        });
        await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
        return null;
      });
      const mode = twelve ? "12" : "24";
      const axis = await browser.evaluate(() => Array.from(document.querySelectorAll('[aria-hidden].justify-between span')).map(e=>e.textContent).join(" | "));
      results.push({label:`${locale.id} ${mode} axis`,text:axis,twelve});
      const range = await browser.evaluate(() => document.querySelector('header span[class*="@7xl/usage-header:block"]')?.textContent ?? "");
      results.push({label:`${locale.id} ${mode} range`,text:range,twelve});
      // The plot is a real pointer target; hover the same hour on both commits.
      const point = await browser.evaluate(() => {
        const plot = document.querySelector('svg.preserve-aspect-ratio') ?? document.querySelector('svg[preserveAspectRatio="none"]');
        if (!plot) throw new Error("Hourly plot missing");
        const r = plot.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2};
      });
      await browser.mouse.move(point.x,point.y);
      await screen.getByText("Claude Code",{exact:true}).first().waitFor();
      await app.screenshot(`${locale.id}-${mode}-hour-chart-tooltip`);
      const tooltip = await browser.evaluate(() => document.querySelector('[style*="--usage-tooltip-left"] .mb-1')?.textContent ?? "");
      results.push({label:`${locale.id} ${mode} tooltip`,text:tooltip,twelve});
      await browser.mouse.move(60,100);
      await screen.getByRole("button",locale.hour,{exact:true}).tap();
      await screen.getByRole("button",locale.hour,{exact:true}).scrollIntoView();
      await app.screenshot(`${locale.id}-${mode}-hour-breakdown`);
      const rows = await browser.evaluate(() => Array.from(document.querySelectorAll('td')).map(e=>e.textContent).join(" | "));
      results.push({label:`${locale.id} ${mode} breakdown`,text:rows,twelve});
    }

  }
  for (const result of results) {
    if (result.twelve) expect(result.text, result.label).toMatch(/AM|PM|a\.\s*m\.|p\.\s*m\./i);
    else expect(result.text, result.label).not.toMatch(/AM|PM|a\.\s*m\.|p\.\s*m\./i);
  }
});
