"""Real panel script: keyboard/pointer diagnostics remain local and compact."""
import json
import shutil
import subprocess

import pytest

from tests.investmentmanager.test_export_package_panel import HARNESS, JS


def test_popover_pointer_keyboard_and_outside_close():
    node = shutil.which('node')
    if not node:
        pytest.skip('Node unavailable')
    setup = HARNESS[:HARNESS.index('(async()=>{')]
    script = setup + r'''
const assert=require('node:assert/strict');
let timeout;global.setTimeout=fn=>{timeout=fn;return 1};global.clearTimeout=()=>{timeout=null};
(async()=>{
 events['panel:shown']({detail:{panelId:'export-packages'}});await flush();
 const badges=els['packages-rows'].children[0].children[3].children[0].children;
 const a=badges[1],b=badges[2],before=calls.length;
 a.listeners.mouseenter();assert.equal(pageBody.children.length,1);
 let popup=pageBody.children[0];assert.equal(popup.parent,pageBody);
 assert(popup.textContent.includes('<img src=x onerror=alert(1)>'));
 assert(popup.textContent.includes('Jest nowsza paczka'));
 assert(popup.textContent.includes('Ostatnia weryfikacja'));
 assert.equal(popup.role,'dialog');assert.equal(a['aria-expanded'],'true');
 assert.equal(calls.length,before);
 a.listeners.mouseleave();timeout();assert.equal(pageBody.children.length,0);
 a.listeners.focus();assert.equal(pageBody.children.length,1);
 a.listeners.click();a.listeners.mouseleave();timeout();assert.equal(pageBody.children.length,1,'Pinned by click');
 events.click({target:new Element('outside')});assert.equal(pageBody.children.length,0);
 for(const key of ['Enter',' ']){
  let prevented=false;a.listeners.keydown({key,preventDefault(){prevented=true;}});
  assert(prevented);assert.equal(pageBody.children.length,1);
  events.keydown({key:'Escape'});assert.equal(pageBody.children.length,0);
 }
 a.listeners.focus();b.listeners.mouseenter();assert.equal(pageBody.children.length,1);
 assert(pageBody.children[0].textContent.includes('Domiporta'));
 b.listeners.blur({relatedTarget:new Element('outside')});assert.equal(pageBody.children.length,0);
 a.listeners.focus();popup=pageBody.children[0];popup.children.at(-1).listeners.click();
 assert.equal(pageBody.children.length,0);assert.equal(calls.length,before);
 assert(!els['packages-rows'].children[0].children[4].children.some(e=>e.tag==='details'));
})().catch(e=>{console.error(e);process.exit(1)});
'''
    result = subprocess.run([node, '-e', script, str(JS), json.dumps({'count': 3, 'fail': False})],
                            capture_output=True, text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
