"""Card shortcuts reuse the description/photo modal without a data editor."""
from pathlib import Path
import shutil
import subprocess

import pytest


@pytest.mark.parametrize('mode', ['description', 'images', 'image_upload', 'close', 'error', 'refresh_error'])
def test_media_modal_entry_and_save(mode):
    node = shutil.which('node')
    if not node:
        pytest.skip('Node unavailable')
    root = Path(__file__).resolve().parents[2]
    source = root / 'InvestmentManager/static/js/offers_edit.js'
    template = (root / 'InvestmentManager/templates/investmentmanager/components/offers.html').read_text(encoding='utf8')
    assert 'id="tab-details"' not in template
    assert 'id="edit-modal"' not in template
    assert template.count('min-h-0 overflow-y-auto p-5') == 1
    assert 'min-h-0 flex-1 overflow-hidden p-5' in template
    assert 'flex h-[95vh]' in template
    assert template.count('flex shrink-0 items-center justify-between') == 2
    for kind in ('description', 'images'):
        assert f'id="offer-{kind}-modal"' in template
        assert f'id="offer-{kind}-close-top"' in template
        assert f'id="offer-{kind}-close"' in template
    script = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
const mode=process.argv[2],nodes={};
class Element {
 constructor(id){this.id=id;this.style={};this.dataset={};this.value='';this.offsetHeight=400;
  const classes=new Set(['hidden','bg-gray-200','text-gray-700']);
  this.classList={contains:v=>classes.has(v),add:(...vs)=>vs.forEach(v=>classes.add(v)),remove:(...vs)=>vs.forEach(v=>classes.delete(v)),replace:(a,b)=>{classes.delete(a);classes.add(b)}};
 }
 set innerHTML(value){this.html=value;if(['offer-description-form','offer-images-content'].includes(this.id)){
  const ids=this.id==='offer-description-form'?['markdown-editor','markdown-preview']:['images-list','images-drop-zone','upload-image'];
  for(const id of ids)delete nodes[id];
  for(const id of ids)if(value.includes('id="'+id+'"'))nodes[id]=new Element(id);
 }}
 get innerHTML(){return this.html||'';}
 addEventListener(){}
 removeEventListener(){}
 replaceChildren(){this.innerHTML='';}
 focus(){global.focused=this;}
 querySelector(){return null;}
}
for(const kind of ['description','images'])for(const suffix of ['modal','close','close-top'])nodes[`offer-${kind}-${suffix}`]=new Element(`offer-${kind}-${suffix}`);
for(const id of ['offer-description-form','offer-images-content','offer-description-save'])nodes[id]=new Element(id);
global.editById=id=>nodes[id]||null;global.currentOffer=null;global.offersEditCore={state:{}};
const notices=[],requests=[],refreshes=[];let disposed=0,summaries=0,galleries=0,uploads=0;
global.document={getElementById:id=>nodes[id]||null,querySelector:()=>({refreshInlineSummary(){summaries++;},refreshInlineGallery(){galleries++;}})};
global.uploadOfferImage=async(id,file)=>{assert.equal(id,17);uploads++;return true;};
global.window={OffersCore:{state:{},byId:id=>nodes[id]||null},showOfferToast:(...args)=>notices.push(args),addEventListener(){},removeEventListener(){}};
global.notifyOfferEdit=(...args)=>notices.push(args);
global.refreshOffersPanel=args=>refreshes.push(args);
global.requestAnimationFrame=fn=>fn();
global.EasyMDE=class{constructor(){this.codemirror={on(){}};}value(){return 'edited description';}toTextArea(){disposed++;}};
global.FormData=class{entries(){return [['Opis_oferty','textarea content']][Symbol.iterator]();}};
global.fetch=async(url,options={})=>{
 requests.push({url,options});
 if(url.includes('/description/'))return {ok:mode!=='error',status:mode==='error'?500:200,text:async()=>'original description'};
 if(url.includes('/images/'))return {ok:true,json:async()=>[]};
 if(url.includes('/update/'))return {ok:true,json:async()=>({success:true})};
 if(url==='/crm/offers/all'){
  if(mode==='refresh_error')throw Error('read failure');
  return {ok:true,json:async()=>[{ID:17,Portal_sync:{no:{is_published:1,needs_update:1}}}]};
 }
 throw Error('Unexpected request '+url);
};
const source=fs.readFileSync(process.argv[1],'utf8');
assert(!source.includes("editById('tab-details')"));
vm.runInThisContext(source);
uploadOfferImage=async(id,file)=>{assert.equal(id,17);uploads++;return true;};
(async()=>{
 const offer={ID:17,Typ_nieruchomosci:'Dom',Cena:123};
 if(mode.startsWith('image'))await openOfferImagesModal(offer);else await openOfferDescriptionModal(offer);
 const kind=mode.startsWith('image')?'images':'description';
 assert(!nodes[`offer-${kind}-modal`].classList.contains('hidden'));
 assert.equal(global.focused,nodes[`offer-${kind}-close-top`]);
 assert.equal(requests.length,1);assert(!requests.some(r=>r.options.method==='POST'));
 if(mode==='error'){assert.equal(notices.at(-1)[1],'error');assert.equal(nodes['offer-description-save'].disabled,true);return;}
 if(!mode.startsWith('image')){
  const form=nodes['offer-description-form'];assert(form.className.includes('h-full'));assert(form.className.includes('md:grid-cols-2'));
  assert(!form.innerHTML.includes('min-h-[460px]'));assert(!form.innerHTML.includes('resize-y'));
  assert.equal(nodes['markdown-preview'].style.height,undefined);
 }
 if(mode==='close'){
  for(const suffix of ['close','close-top']){
   nodes[`offer-description-${suffix}`].onclick();assert(nodes['offer-description-modal'].classList.contains('hidden'));
   await openOfferDescriptionModal(offer);
  }
  nodes['offer-description-modal'].onkeydown({key:'Escape',stopPropagation(){}});
  assert(nodes['offer-description-modal'].classList.contains('hidden'));assert.equal(window.easyMDE,null);
  assert(!requests.some(r=>r.options.method==='POST'));return;
 }
 if(mode.startsWith('image')){
  assert(nodes['images-list']);assert(!nodes['offer-images-save']);
  if(mode==='image_upload'){
   await nodes['upload-image'].onchange({target:{files:[{name:'synthetic.jpg'}]}});
   assert.equal(uploads,1);assert.equal(summaries,1);assert.equal(galleries,1);assert.equal(refreshes.length,0);
   assert(!nodes['offer-images-modal'].classList.contains('hidden'));return;
  }
  nodes['offer-images-close-top'].onclick();assert(nodes['offer-images-modal'].classList.contains('hidden'));
  await openOfferDescriptionModal(offer);assert(nodes['markdown-editor']);
 }else{
  assert(nodes['markdown-editor']);assert.equal(nodes['offer-description-save'].disabled,false);
  await openOfferImagesModal(offer);assert.equal(disposed,1);assert.equal(window.easyMDE,null);
  assert(nodes['offer-description-modal'].classList.contains('hidden'));
  await openOfferDescriptionModal(offer);
 }
 await nodes['offer-description-save'].onclick();
 const posts=requests.filter(r=>r.options.method==='POST');assert.equal(posts.length,1);
 assert.equal(posts[0].url,'/crm/offers/update/17');
 assert.deepEqual(JSON.parse(posts[0].options.body),{Opis_oferty:'edited description'});
 assert(nodes['offer-description-modal'].classList.contains('hidden'));assert.equal(refreshes.length,0);
 assert.equal(summaries,mode==='refresh_error'?0:1);assert.equal(galleries,0);
 if(mode==='refresh_error')assert.equal(notices.at(-1)[1],'error');
 else assert.equal(offer.Portal_sync.no.needs_update,1);
 assert(!requests.some(r=>/options|export-package|transport/.test(r.url)));
})().catch(error=>{console.error(error);process.exit(1)});
'''
    result = subprocess.run([node, '-e', script, str(source), mode], capture_output=True,
                            text=True, encoding='utf8', timeout=15)
    assert result.returncode == 0, result.stderr
