/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { APP_DIR } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Copy as PNG preserves native checkbox states and accent contrast", WEB, async ({t3, app, browser, screen}) => {
  const markdown = '| Task | Done |\n| --- | --- |\n| Ship it (disabled checked) | <input type="checkbox" checked> |\n| Test it (disabled unchecked) | <input type="checkbox"> |\n| Mixed (indeterminate) | <input type="checkbox"> |\n| Enabled blue | <input type="checkbox" checked> |\n| Enabled white accent | <input type="checkbox" checked> |\n| Fieldset disabled | <input type="checkbox" checked> |';
  const project = await t3.project('checkbox-demo');
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, 'utf8');
  const transcript = [
    {type:'expect_outbound',frame:{kind:'request',method:'session/prompt',params:{}}},
    {type:'emit_inbound',frame:{kind:'notification',method:'session/update',params:{sessionId:'replay',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:markdown}}}}},
    {type:'emit_inbound',frame:{kind:'response',method:'session/prompt',result:{stopReason:'end_turn'}}},
  ].map(entry => JSON.stringify(entry)).join('\n');
  let thread;
  try {
    await writeFile(fixture, transcript);
    thread = await t3.thread({project, title:'Table export', model:'showcase', messages:['Reply with exactly this Markdown table:\n' + markdown]});
  } finally { await writeFile(fixture, original); }
  await browser.addInitScript(() => {
    const captured = Promise.withResolvers<Blob>();
    Object.assign(window, { checkboxPng: captured.promise });
    navigator.clipboard.write = async ([item]) => captured.resolve(await item!.getType('image/png'));
  });
  await t3.open(thread);
  await screen.getByRole('button', 'Copy table').waitFor();
  await browser.evaluate(() => {
    const table = document.querySelector<HTMLTableElement>('.chat-markdown-table-container table')!;
    const inputs = [...table.querySelectorAll<HTMLInputElement>('input[type=checkbox]')];
    if (inputs.length !== 6) throw new Error(`Expected six native checkboxes, got ${inputs.length}`);
    inputs[2]!.disabled = false;
    inputs[2]!.indeterminate = true;
    inputs[2]!.style.accentColor = '#2563eb';
    inputs[3]!.disabled = false;
    inputs[3]!.style.accentColor = '#2563eb';
    inputs[4]!.disabled = false;
    inputs[4]!.style.accentColor = 'white';
    inputs[5]!.disabled = false;
    const fieldset = document.createElement('fieldset');
    fieldset.disabled = true;
    fieldset.style.cssText = 'border:0;padding:0;margin:0';
    inputs[5]!.replaceWith(fieldset);
    fieldset.append(inputs[5]!);
  });
  await screen.getByText('Syncing messages...', {exact:true}).waitFor({state:'hidden'});
  await app.screenshot('visible-checkbox-states');
  await screen.getByRole('button', 'Copy table').tap();
  await screen.getByRole('menuitem', 'Copy as PNG', {exact:true}).tap();
  const ink = await browser.evaluate(async () => {
    const blob = await (window as unknown as {checkboxPng:Promise<Blob>}).checkboxPng;
    const image = new Image();
    image.src = URL.createObjectURL(blob);
    await image.decode();
    const table = document.querySelector<HTMLTableElement>('.chat-markdown-table-container table')!;
    const bounds = table.getBoundingClientRect();
    const canvas = document.createElement('canvas');
    canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
    const ctx = canvas.getContext('2d')!; ctx.drawImage(image,0,0);
    const scale = canvas.width / (bounds.width + 32);
    const counts = [...table.querySelectorAll<HTMLInputElement>('input')].map(input => {
      const r = input.getBoundingClientRect();
      const x = Math.round((r.left-bounds.left+16)*scale), y = Math.round((r.top-bounds.top+16)*scale);
      const w = Math.round(r.width*scale), h = Math.round(r.height*scale);
      const bg = ctx.getImageData(Math.max(0,x-4),y,1,1).data;
      const pixels = ctx.getImageData(x,y,w,h).data;
      let count=0;
      for(let i=0;i<pixels.length;i+=4) if(Math.abs(pixels[i]!-bg[0]!)+Math.abs(pixels[i+1]!-bg[1]!)+Math.abs(pixels[i+2]!-bg[2]!)>50) count++;
      return count;
    });
    const panel = document.createElement('div');
    panel.id='export-proof';
    panel.style.cssText='position:fixed;inset:0;z-index:99999;background:#18181b;color:white;padding:48px;font:18px sans-serif;overflow:auto';
    const heading=document.createElement('h1');heading.textContent='Actual clipboard PNG — native checkbox states';panel.append(heading);
    const description=document.createElement('p');description.textContent='Disabled checked / unchecked, indeterminate, enabled blue, white accent, fieldset disabled';panel.append(description);
    image.style.cssText='display:block;width:1014px;max-width:100%;image-rendering:auto;border:1px solid #555;margin-top:24px';
    panel.append(image); document.body.append(panel);
    return counts;
  });
  await app.screenshot('clipboard-png-checkbox-states');
  await browser.evaluate(() => document.getElementById('export-proof')?.remove());
  expect(ink.every(count => count > 8), `Every checkbox must have visible pixels in the actual exported PNG: ${ink}`).toBe(true);
});
