/// <reference lib="dom" />
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { test, WEB, makeState, runPromise } from './t3.ts';

const svg = `<svg width="320" height="80" viewBox="0 0 320 80">
  <circle cx="20" cy="40" r="6" style="fill:var(--chart-1)"/>
  <path d="M20 40 C120 0 200 80 300 40" style="fill:none;stroke:var(--chart-1);stroke-width:2"/>
  <circle cx="300" cy="40" r="6" style="fill:var(--accent)"/>
</svg>`;

test('html_render lines and markers remain visible with a dark custom accent', WEB, async ({t3, app, screen, browser}) => {
  await browser.emulateMedia({colorScheme:'dark'});
  const project = await t3.project('diagram-demo');
  const seed = await t3.thread({project, title:'Theme setup', model:'default', messages:['Start']});
  await t3.open(seed);
  await browser.evaluate(async () => {
    const module = await import('/src/themePalette.ts');
    module.installCustomTheme({id:'dark-accent-proof', label:'Dark accent proof', appearance:'dark', colors:module.createVividThemeColors('dark','#161515','#21180e')});
  });
  await t3.open('/settings/appearance');
  await screen.getByRole('button','Use Dark accent proof theme',{exact:true}).tap();

  const settingsPath=path.join(T3_HOME,'userdata/settings.json');
  const settings=JSON.parse(await fs.readFile(settingsPath,'utf8'));
  settings.providerInstances.claudeAgent={driver:'claudeAgent',enabled:true};
  await fs.writeFile(settingsPath,JSON.stringify(settings));
  const {cli}=makeState(T3_HOME);
  let threadId='';
  for(let attempt=0;attempt<8&&!threadId;attempt++) {
    const result=await runPromise(cli(['thread','start',project,`Call html_render exactly once with title "Accent diagram", height 100 and this exact HTML unchanged. Do not call html_preview. Then reply "Done".\n${svg}`,'--title','Accent diagram','--provider','claudeAgent','--model','claude-haiku-5-5','--wait','--json'],[0,1]));
    try { threadId=JSON.parse(result.stdout).threadId ?? ''; } catch {}
  }
  if(!threadId) throw new Error('Could not start Claude thread');
  await t3.open({threadId});
  await browser.locator('iframe[title="Accent diagram"]').waitFor({timeout:120000});
  const variables = await browser.evaluate(() => {
    const iframe=document.querySelector('iframe[title="Accent diagram"]') as HTMLIFrameElement;
    const fragment=iframe.src.split('#t3-theme=')[1]?.split('&')[0];
    if(!fragment) throw new Error('Missing frame theme');
    return JSON.parse(decodeURIComponent(fragment)).variables;
  });
  if(variables['--background'].toLowerCase() !== '#161515') throw new Error('Custom dark canvas was not active: '+variables['--background']);
  await app.screenshot('dark-accent-diagram');
  function luminance(hex:string) {
    const rgb=hex.replace('#','').match(/../g)!.map(v=>parseInt(v,16)/255).map(v=>v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4);
    return rgb[0]*0.2126+rgb[1]*0.7152+rgb[2]*0.0722;
  }
  const background=luminance(variables['--background']);
  for(const name of ['--accent','--chart-1']) {
    const color=luminance(variables[name]);
    expect((Math.max(background,color)+0.05)/(Math.min(background,color)+0.05)).toBeGreaterThanOrEqual(3);
  }
});
