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

test("Usage exposes every chart value and share without hover", WEB, async ({t3,app,browser,screen}) => {
  await browser.emulateMedia({colorScheme:"dark"});
  await t3.project("Synthetic usage");
  await t3.open("/usage");
  await screen.getByRole("button", "Cost", {exact:true}).tap();
  await screen.getByText("claude-sonnet-4-5", {exact:true}).tap();
  await browser.keyboard.press("Escape");
  const findings: any[] = [];
  const capture = async (label: string) => {
    const result = await browser.evaluate(() => {
      const root = [...document.querySelectorAll('[role="dialog"]')].at(-1) ?? document.querySelector('main') ?? document.body;
      const tables = [...root.querySelectorAll('table')].filter(t=>/by provider/.test(t.querySelector('caption')?.textContent??''));
      const chart = tables.map(t=>({caption:t.querySelector('caption')?.textContent, headers:[...t.querySelectorAll('thead th')].map(e=>e.textContent), rows:[...t.querySelectorAll('tbody tr')].map(r=>[...r.children].map(e=>e.textContent))}));
      const bars = ['Cost by type','Tokens by type','Cost by speed'].map(label=>{
        const list = root.querySelector(`ul[aria-label="${label}"]`);
        const image = root.querySelector(`[role="img"][aria-label^="${label}:"]`);
        return {label, items:list?[...list.children].map(e=>e.textContent):[], oldImage:image?.getAttribute('aria-label')??null};
      });
      const images=[...root.querySelectorAll('[role="img"]')].map(e=>e.getAttribute('aria-label'));
      return {chart,bars,images};
    });
    findings.push({label,...result});
    await app.screenshot(label);
    await browser.evaluate((result) => {
      const panel=document.createElement('pre'); panel.id='accessibility-inspection';
      panel.style.cssText='position:fixed;inset:20px;z-index:2147483647;background:#101820;color:#f5f5f5;border:2px solid #63d6bc;padding:24px;font:14px/1.4 monospace;white-space:pre-wrap;overflow:auto';
      panel.textContent='DOM ACCESSIBILITY INSPECTION — no hover\nRead-only extract of app semantics (not a screen reader simulation)\n\n'+
        (result.chart.length?result.chart.map(t=>`TABLE: ${t.caption}\nColumns: ${t.headers.join(' | ')}\n${t.rows.filter(r=>r.slice(1).some(v=>v!=='$0.00'&&v!=='0')).slice(-3).map(r=>r.join(' | ')).join('\n')}\n(${t.rows.length} period rows)`).join('\n'):'NO CHART DATA TABLE. Chart images: '+result.images.join('; '))+
        '\n\n'+result.bars.map(b=>b.label+':\n'+(b.items.length?b.items.join('\n'):b.oldImage??'absent')).join('\n\n');
      document.body.append(panel);
    },result);
    await app.screenshot(label+'-semantics');
    await browser.evaluate(()=>document.getElementById('accessibility-inspection')?.remove());
  };
  await capture('daily-cost');
  await screen.getByRole('button','Tokens',{exact:true}).tap();
  await capture('daily-tokens');
  await screen.getByText('claude-sonnet-4-5',{exact:true}).tap();
  await capture('model-tokens');
  await browser.keyboard.press('Escape');
  await screen.getByRole('button','Cost',{exact:true}).tap();
  await screen.getByText('claude-sonnet-4-5',{exact:true}).tap();
  await capture('model-cost');
  await browser.keyboard.press('Escape');
  await screen.getByRole('button','Past 24h',{exact:true}).tap();
  await capture('hourly-cost');
  await screen.getByRole('button','Tokens',{exact:true}).tap();
  await capture('hourly-tokens');
  await screen.getByText('claude-sonnet-4-5',{exact:true}).tap();
  await capture('model-hourly-tokens');
  await browser.keyboard.press('Escape');
  writeFileSync(`${process.env.CLAUDE_CONFIG_DIR}/../inspection-${Date.now()}.json`,JSON.stringify(findings,null,2));
  expect(findings.map(f=>({label:f.label,table:f.chart.length>0,shares:f.bars.filter((b:any)=>b.oldImage||b.items.length).every((b:any)=>b.items.length>0&&b.items.every((i:string)=>/\d.*%/.test(i)))}))).toEqual([
    {label:'daily-cost',table:true,shares:true},
    {label:'daily-tokens',table:true,shares:true},
    {label:'model-tokens',table:true,shares:true},
    {label:'model-cost',table:true,shares:true},
    {label:'hourly-cost',table:true,shares:true},
    {label:'hourly-tokens',table:true,shares:true},
    {label:'model-hourly-tokens',table:true,shares:true},
  ]);
});
