"""Inline editing uses the existing partial-update API; all requests are mocked."""
import json
from pathlib import Path
import shutil
import subprocess

import pytest


@pytest.mark.parametrize('scenario', [
    'blur', 'enter', 'select', 'cancel', 'noop', 'error', 'unknown',
    'refresh_error', 'nd', 'zero', 'region', 'region_error',
    'undo', 'select_undo', 'region_undo', 'undo_error', 'undo_nd', 'undo_changed', 'growing',
])
def test_inline_edit(scenario):
    node = shutil.which('node')
    if not node:
        pytest.skip('Node unavailable')
    source = Path(__file__).resolve().parents[2] / 'InvestmentManager/static/js/offers_edit.js'
    script = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
const scenario=process.argv[2];
const timers=[];global.setTimeout=(callback,delay)=>{timers.push({callback,delay});return timers.length;};
class Element {
 constructor(tag){this.tagName=tag.toUpperCase();this.children=[];this.listeners={};this.style={};this.value='';this.classList={add(){}};this.textContent='';}
 setAttribute(){}
 appendChild(x){this.children.push(x);x.parent=this;return x;}
 remove(){if(this.parent)this.parent.children.splice(this.parent.children.indexOf(this),1);}
 replaceChildren(...xs){this.children=[];xs.forEach(x=>this.appendChild(x));}
 addEventListener(t,f){(this.listeners[t]??=[]).push(f);}
 async fire(t,extra={}){for(const f of this.listeners[t]||[])await f({target:this,preventDefault(){},stopPropagation(){},...extra});}
 contains(x){return x===this||this.children.some(c=>c.contains(x));}
 closest(){return ['INPUT','TEXTAREA','SELECT','BUTTON'].includes(this.tagName)?this:null;}
 focus(){document.activeElement=this;}
 select(){}
}
global.document={createElement:t=>new Element(t)};
global.offersEditCore={state:{allOffers:{}}};global.offersEditFieldLabels={};
const source=fs.readFileSync(process.argv[1],'utf8');
vm.runInThisContext(source.slice(source.indexOf('const offerInlineEditors = new Map();'),source.indexOf('async function renderEditFieldsComplete(')));
const calls=[];let posts=0,reads=0,saved=0;
const offer={ID:17,Typ_nieruchomosci:'Dom',Tytul:'old',Ogrzewanie:'Gaz',Wojewodztwo:'old-region',Powiat:'old-district',Powierzchnia:12};
if(scenario==='undo_nd')offer.Tytul='nd';
const field=scenario.startsWith('region')?'Wojewodztwo':scenario.startsWith('select')?'Ogrzewanie':scenario==='zero'?'Powierzchnia':'Tytul';
const initial={...offer};
global.fetch=async(url,options={})=>{
 calls.push({url,options});
 if(url.includes('/options/'))return {ok:true,json:async()=>({Ogrzewanie:['Gaz','Inne'],Wojewodztwo:['old-region','new-region'],Powiat:['old-district']})};
 if(url.includes('/districts?')){
  if(scenario==='region_error')throw Error('district failure');
  return {ok:true,json:async()=>url.includes('old-region')?['old-district']:['new-district']};
 }
 if(options.method==='POST'){
  posts++;
  if(scenario==='unknown')throw Error('network lost');
  if(scenario==='undo_error'&&posts===2)throw Error('undo network lost');
  if(scenario==='error')return {ok:false,json:async()=>({error:'denied'})};
  const body=JSON.parse(options.body);assert.equal(body.Typ_nieruchomosci,'Dom');
  assert.deepEqual(Object.keys(body).sort(),(scenario.startsWith('region')?['Wojewodztwo','Powiat','Typ_nieruchomosci']:[field,'Typ_nieruchomosci']).sort());
  return {ok:true,json:async()=>({success:true})};
 }
 if(url==='/crm/offers/all'){
  reads++;if(scenario==='refresh_error'&&reads===1)throw Error('read failure');
  const posted=JSON.parse(calls.filter(c=>c.options.method==='POST').at(-1).options.body);
  return {ok:true,json:async()=>[{...offer,...posted}]};
 }
 throw Error('Unexpected request '+url);
};
const tick=()=>new Promise(resolve=>setImmediate(resolve));
(async()=>{
 const cell=new Element('div'),content=new Element('dd');content.textContent='old';cell.appendChild(content);
 enableOfferInlineEdit(cell,content,offer,field,()=>{saved++;content.replaceChildren();content.textContent=String(offer[field]);return cell;});
 assert.equal(calls.length,0);
 await cell.fire('click');await tick();
 const editor=content.children[0],input=editor.children[0],status=content.children[1],retry=content.children[2];
 assert.equal(posts,0);
 if(scenario==='cancel'){
  input.value='draft';await editor.fire('keydown',{key:'Escape'});await editor.fire('focusout',{relatedTarget:null});assert.equal(posts,0);assert.equal(content.textContent,'old');return;
 }
 if(scenario==='noop'){await editor.fire('focusout',{relatedTarget:null});assert.equal(posts,0);return;}
 if(scenario==='growing'){
  assert.equal(input.tagName,'TEXTAREA');assert.equal(input.rows,1);
  input.value='long text\nsecond line';input.scrollHeight=110;await input.fire('input');assert.equal(input.style.height,'110px');
  let prevented=false;await input.fire('keydown',{key:'Enter',shiftKey:true,preventDefault(){prevented=true;}});
  assert.equal(prevented,false);assert.equal(posts,0);
  input.value='short';input.scrollHeight=28;await input.fire('input');assert.equal(input.style.height,'28px');
  await input.fire('keydown',{key:'Enter'});await tick();assert.equal(posts,1);assert.equal(offer.Tytul,'short');return;
 }
 input.value=scenario==='nd'?'nd':scenario==='zero'?'0':scenario.startsWith('region')?'new-region':scenario.startsWith('select')?'Inne':'new';
 if(scenario.startsWith('region')){
  await input.fire('change');await tick();
  assert.equal(posts,0);const district=editor.children[1];
  assert.equal(district.value,'');
  if(scenario==='region_error'){
   await input.fire('keydown',{key:'Enter'});assert.equal(posts,0);assert.ok(status.textContent);return;
  }
  district.value='new-district';await district.fire('change');
 }else if(scenario.startsWith('select'))await input.fire('change');
 else if(scenario==='enter'){
  await input.fire('keydown',{key:'Enter'});await editor.fire('focusout',{relatedTarget:null});
 }else await editor.fire('focusout',{relatedTarget:null});
 await tick();
 if(scenario==='nd'){assert.equal(posts,0);assert.match(status.textContent,/nd/);return;}
 assert.equal(posts,1);
 if(['error','unknown'].includes(scenario)){
  assert.equal(input.value,'new');assert.equal(saved,0);assert.equal(retry.hidden,false);
  await editor.fire('focusout',{relatedTarget:null});assert.equal(posts,1);assert.ok(status.textContent);return;
 }
 if(scenario==='refresh_error'){
  assert.equal(saved,0);assert.equal(input.disabled,true);await retry.fire('click');await tick();assert.equal(posts,1);assert.equal(reads,2);
 }
 assert.equal(saved,1);assert.equal(offer[field],input.value);
 const firstFeedback=cell.inlineSaveFeedback;
 assert.equal(timers.at(-1).delay,2500);timers.at(-1).callback();
 assert.equal(firstFeedback.children[0].hidden,true);
 assert.notEqual(firstFeedback.children[1]?.hidden,true);
 if(scenario.includes('undo')){
  const feedback=cell.inlineSaveFeedback,undo=feedback.children[1];assert(undo);
  assert.equal(cell.style.position,'relative');assert.equal(cell.style.paddingRight,'35px');
  assert.equal(undo.style.position,'absolute');assert.equal(undo.style.right,'7px');
  assert.equal(undo.style.top,'50%');assert.equal(undo.style.transform,'translateY(-50%)');
  if(scenario==='undo_nd'){assert.equal(undo.disabled,true);return;}
  if(scenario==='undo_changed'){
   offer[field]='other change';await undo.fire('click');assert.equal(posts,1);assert.equal(undo.disabled,true);return;
  }
  const pending=undo.fire('click');await undo.fire('click');await pending;await tick();
  assert.equal(posts,2);
  if(scenario==='undo_error'){
   assert.equal(saved,1);assert.equal(offer[field],'new');
   const draft=content.children[0].children[0];assert.equal(draft.value,'old');
   await content.children[0].fire('focusout',{relatedTarget:null});assert.equal(posts,2);return;
  }
  assert.equal(saved,2);assert.equal(offer[field],initial[field]);
  if(scenario==='region_undo')assert.equal(offer.Powiat,initial.Powiat);
  const restored=JSON.parse(calls.filter(c=>c.options.method==='POST').at(-1).options.body);
  assert.equal(restored[field],initial[field]);
  assert.equal(cell.children.filter(c=>c===cell.inlineSaveFeedback).length,1);
  assert.equal(cell.inlineSaveFeedback.children.length,1);
  timers.at(-1).callback();assert.equal(cell.inlineSaveFeedback.hidden,true);
 }
 assert.ok(calls.every(c=>!c.url.includes('transport')&&!c.url.includes('export-package')));
})().catch(e=>{console.error(e);process.exit(1)});
'''
    result = subprocess.run([node, '-e', script, str(source), scenario], capture_output=True,
                            text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
