/// <reference lib="dom" />
import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { readdirSync } from "node:fs";
import { join } from "node:path";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Double Home opens the app switcher", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Device demo");
  const thread = await t3.thread({project, title:"Home shortcut", messages:["ready"]});
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{
      enableDeviceSupport:true, deviceOnboardingCompleted:true, simlockDeviceHostsEnabled:true,
      simlockDeviceHosts:[{kind:"simlock",id:"proof-pool",label:"Simulator pool",gatewayUrl:new URL(process.env.SIMLOCK_AGENT_DEVICE_URL!).origin,agentToken:"",maxLeases:1,maxLeaseMinutes:30}]
    }});
    yield* client["device.configure"]({enabled:true,onboardingCompleted:true});
    yield* client["device.list"]({});
  }).pipe(Effect.scoped));
  await browser.addInitScript(() => {
    (window as any).homeCommands=[];
    const original=WebSocket.prototype.send;
    WebSocket.prototype.send=function(data) {
      if(data instanceof Uint8Array && data[0]===4) {
        try { (window as any).homeCommands.push(JSON.parse(new TextDecoder().decode(data.slice(1))).button); } catch {}
      }
      return original.call(this,data);
    };
  });
  await t3.open(thread);
  await screen.getByRole("button","Toggle right panel",{exact:true}).tap();
  await screen.getByRole("button","Device M",{exact:true}).tap();
  const android=process.env.PROOF_PLATFORM === "android";
  await screen.getByRole("button", android ? "Start Pixel 9" : "Start iPhone 18 Pro", {exact:true}).tap();
  const home=screen.getByRole("button","Home",{exact:true});
  await expect(home).toBeEnabled({timeout:120_000});
  const poolDir=join(T3_HOME,"userdata/device/simlock/proof-pool");
  const suffix=readdirSync(poolDir).find(name=>!name.startsWith("."))!;
  const env={...process.env};
  for(const key of ["AGENT_DEVICE_DAEMON_BASE_URL","AGENT_DEVICE_DAEMON_AUTH_TOKEN","AGENT_DEVICE_CONFIG","AGENT_DEVICE_STATE_DIR","AGENT_DEVICE_SESSION"]) delete env[key];
  execFileSync("agent-device",["open",android ? "com.android.settings" : "com.apple.Preferences","--session",`t3-${suffix}`,"--config",join(poolDir,suffix,"agent-device.json")],{cwd:project,env});
  await screen.getByText("Connecting video…",{exact:true}).waitFor({state:"hidden",timeout:60_000});
  await new Promise(resolve=>setTimeout(resolve,6000));
  await app.screenshot("settings-before-home");
  await browser.evaluate(async()=>{
    const home=document.querySelector<HTMLButtonElement>('button[aria-label="Home"]')!;
    home.click();
    await new Promise(resolve=>setTimeout(resolve,120));
    home.click();
  });
  await new Promise(resolve=>setTimeout(resolve,6000));
  await app.screenshot("double-home-result");
  const commands=await browser.evaluate(()=>(window as any).homeCommands);
  execFileSync("agent-device",["open",android ? "com.android.settings" : "com.apple.Preferences","--session",`t3-${suffix}`,"--config",join(poolDir,suffix,"agent-device.json")],{cwd:project,env});
  await new Promise(resolve=>setTimeout(resolve,2000));
  await browser.evaluate(async()=>{
    const home=document.querySelector<HTMLButtonElement>('button[aria-label="Home"]')!;
    for(let i=0;i<3;i++) { home.click(); if(i<2) await new Promise(resolve=>setTimeout(resolve,120)); }
  });
  await new Promise(resolve=>setTimeout(resolve,6000));
  await app.screenshot("triple-home-result");
  const allCommands=await browser.evaluate(()=>(window as any).homeCommands);
  expect({double:commands,triple:allCommands.slice(2)}).toEqual({double:["home","app_switcher"],triple:["home","app_switcher","home"]});
});
