// Focused interaction/race checks; live persistence is tested separately in Development.
const {chromium}=require('playwright');
const fs=require('node:fs');
const assert=require('node:assert/strict');
(async()=>{
const browser=await chromium.launch({headless:true});
try {
const page=await browser.newPage(); let reject=false; const writes=[];
await page.route('http://metrics.test/**',route=>{
if(route.request().method()==='POST'){
const body=route.request().postDataJSON(); writes.push(body);
return route.fulfill({status:reject?400:200,json:reject?{message:'Save rejected'}:{success:true,value:body.value}});
}
return route.fulfill({contentType:'text/html',body:'
'});
});
await page.goto('http://metrics.test');
await page.evaluate(()=>{window.Chart=class{constructor(c,config){window.chartConfig=config;}update(){}destroy(){window.destroyed=true;}};window.guards=[];document.addEventListener('context-panel-state',e=>guards.push(e.detail));});
for(const file of ['metric-curves','context-metrics'])await page.addScriptTag({content:fs.readFileSync(`PlotLine/wwwroot/js/${file}.js`,'utf8')});
await page.evaluate(()=>{
document.querySelector('main').innerHTML=``;
PlotDirectorContextLifecycles.metrics.mount(document.querySelector('main>div'));
});
assert.deepEqual(await page.evaluate(()=>chartConfig.data.datasets[0].data.map(p=>p.y)),[0,null]);
const input=page.locator('[type=range]');
await input.focus(); await page.keyboard.press('ArrowRight');
await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved');
assert.equal(writes[0].value,1); assert.equal(writes[0].sceneID,2);
reject=true;
await input.focus();await page.keyboard.press('ArrowRight');
await page.waitForFunction(()=>document.querySelector('[data-metrics-error]').textContent==='Save rejected');
assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),false);
await page.locator('[data-metrics-cancel]').click();
assert.equal(await input.inputValue(),'1');
assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),true);
// A pointer commit on the minimum must record zero even if the range value did not change.
reject=false;
await input.evaluate(el=>{el.value='0';el.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}));document.dispatchEvent(new PointerEvent('pointerup'));});
await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved');
assert.equal(writes.at(-1).value,0);
await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.dispose(document.querySelector('main>div')));
assert.equal(await page.evaluate(()=>destroyed),true);
console.log('PASS Context metric zero/unset, keyboard and pointer commit, failed save guard/discard and disposal');
}finally{await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});