import puppeteer from 'puppeteer';
const url = 'file://' + process.argv[2];
const b = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });
const p = await b.newPage();
await p.setViewport({ width: 900, height: 760, deviceScaleFactor: 2 });
const errs = [];
p.on('pageerror', e => errs.push(String(e)));
await p.goto(url, { waitUntil: 'networkidle0' });
await new Promise(r => setTimeout(r, 400));

// sanity: how many tagged elements mounted?
const info = await p.evaluate(() => {
  const svg = document.querySelector('#svgbox svg');
  return {
    hasSvg: !!svg,
    nets: svg ? svg.querySelectorAll('[data-net]').length : 0,
    hotspots: svg ? svg.querySelectorAll('.adom-hotspot').length : 0,
    netNames: Object.keys((window.__PCB__ && window.__PCB__.meta.net_names) || {}).length,
  };
});
console.log('MOUNT', JSON.stringify(info));

// 1) highlight net 1 (+3.3V) and screenshot
await p.evaluate(() => window.AdomPcb.highlightNet('1'));
await new Promise(r => setTimeout(r, 200));
await p.screenshot({ path: process.argv[3] || '/tmp/pcbtest/hl_net1.png' });
const hl = await p.evaluate(() => document.querySelectorAll('#svgbox svg .hl').length);
console.log('NET1_HL_COUNT', hl);

// 2) hover a component hotspot (U1) → info card
const cardShown = await p.evaluate(async () => {
  const hs = [...document.querySelectorAll('.adom-hotspot')].find(h => h.getAttribute('data-ref') === 'U1')
          || document.querySelector('.adom-hotspot');
  if (!hs) return { ok: false };
  const r = hs.getBoundingClientRect();
  const ev = new MouseEvent('mousemove', { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 });
  hs.dispatchEvent(ev);
  await new Promise(r => setTimeout(r, 100));
  const card = document.querySelector('#card');
  return { ok: card && card.style.display === 'block', ref: hs.getAttribute('data-ref'), text: card ? card.innerText.slice(0, 120) : '' };
});
console.log('CARD', JSON.stringify(cardShown));
await p.screenshot({ path: '/tmp/pcbtest/hover_comp.png' });

console.log('ERRORS', JSON.stringify(errs));
await b.close();