"""Offer details keep CRM actions, without domestic generation controls."""
from pathlib import Path
import shutil
import subprocess

import pytest

JS = Path(__file__).resolve().parents[2]/'InvestmentManager/static/js/offers_cards.js'


def test_three_column_layout_is_in_built_tailwind_css():
    root = JS.parents[3]
    css = (root/'InvestmentManager/static/css/output.css').read_text(encoding='utf8')
    template = (root/'InvestmentManager/templates/investmentmanager/base.html').read_text(encoding='utf8')
    assert "filename='css/output.css', v='package-generation-downloads'" in template
    assert '180px_minmax' in css


@pytest.mark.parametrize('master', [True, False])
@pytest.mark.parametrize('status', ['aktywna', 'nieaktywna', 'sprzedane'])
def test_catalog_details_have_no_generation_ui_and_keep_other_actions(master, status):
    executable = shutil.which('node')
    if not executable:
        pytest.skip('Node unavailable')
    harness = r'''
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict');
class Element {
 constructor(tag){this.tag=tag;this.children=[];this.listeners={};this.style={};this.dataset={};this.textContent='';
  const classes=new Set(['hidden']);this.classList={contains:x=>classes.has(x),add:(...x)=>x.forEach(v=>classes.add(v)),remove:(...x)=>x.forEach(v=>classes.delete(v)),toggle(){}};}
 appendChild(x){this.children.push(x)} append(...x){this.children.push(...x)}
 replaceChildren(...xs){this.children=[];xs.forEach(x=>this.appendChild(x))}
 addEventListener(t,f){this.listeners[t]=f} querySelector(){return null}
}
global.window={OffersCore:{state:{isMasterUser:process.argv[2]==='true'}}};
global.document={createElement:t=>new Element(t)};
const calls=[];global.fetch=async(url,options={})=>{calls.push({url,options});return {ok:true,text:async()=>'',json:async()=>[]}};

const source=fs.readFileSync(process.argv[1],'utf8');vm.runInThisContext(source);
assert.equal(typeof createDomesticPackageControls,'undefined');
assert(!source.includes('/export-package'),'Catalog must have no generation request path');
// Stub only unrelated gallery/animation; execute the real offer-details builder.
renderOfferGallery=()=>{};animateDetailsExpand=e=>e.classList.remove('hidden');
const details=new Element('div'),container={querySelector:()=>details};
toggleDetails(container,{ID:17,Status_oferty:process.argv[3],Typ_nieruchomosci:'działka',Portal_sync:{}},new Element('span'),new Element('img'),new Element('div'));
const walk=e=>[e,...e.children.flatMap(walk)];
const labelOf=e=>e.dataset.offerTabLabel||e.textContent;
const controls=walk(details).filter(e=>['button','a'].includes(e.tag));
const row=details.children[0],tabs=row.children[0];
assert.equal(row.children.length,3);
assert(row.className.includes('xl:grid-cols-[180px_minmax(0,1fr)_420px]'));
assert(tabs.className.includes('flex-col'));assert(!tabs.className.includes('overflow-x-auto'));
assert(walk(row.children[1]).some(e=>e.dataset.offerEditHint==='true'));
for(const label of ['Notatnik','Dokumenty','Karty ogłoszeń'])assert(walk(tabs).some(e=>labelOf(e)===label));
assert(!walk(details).some(e=>e.textContent==='Akcje'));
assert(walk(details).some(e=>e.dataset.offerEditHint==='true'&&e.textContent.includes('Esc')));
assert(tabs.children.some(e=>labelOf(e)==='SZCZEGÓŁY'));
const actions=[];global.openNotesModal=id=>actions.push(['notes',id]);global.openDocumentsModal=id=>actions.push(['documents',id]);global.openOfferCardsModal=id=>actions.push(['cards',id]);
for(const label of ['Notatnik','Dokumenty','Karty ogłoszeń'])walk(tabs).find(e=>labelOf(e)===label).listeners.click();
assert.deepEqual(actions,[['notes',17],['documents',17],['cards',17]]);
assert(!controls.some(e=>/Przygotuj|Aktualny zestaw krajowy/.test(e.textContent)));
for(const label of ['Notatnik','Dokumenty','Karty ogłoszeń'])assert(controls.some(e=>labelOf(e)===label),label);
assert(!controls.some(e=>e.textContent==='Edytuj'));
assert(!calls.some(c=>c.url.includes('export-package')));
assert(!calls.some(c=>c.url.includes('/description/')));
const media=[];global.openOfferDescriptionModal=offer=>media.push([offer.ID,'description']);global.openOfferImagesModal=offer=>media.push([offer.ID,'images']);
controls.find(e=>labelOf(e)==='OPIS').listeners.click();
controls.find(e=>labelOf(e)==='ZDJ\u0118CIA').listeners.click();
assert.deepEqual(media,[[17,'description'],[17,'images']]);
assert(row.className.includes('items-stretch'));assert(row.children[1].className.includes('xl:h-0'));
const group=walk(tabs).find(e=>e.dataset.offerActionGroup==='true');assert(group);assert(group.className.includes('border-t'));
for(const tab of [...tabs.children.filter(e=>e.tag==='button'),...group.children]){
 assert.equal(tab.textContent,tab.textContent.toLocaleUpperCase('pl-PL'));
 assert(tab.textContent.length>labelOf(tab).length);
}
if(process.argv[3]!=='sprzedane'){
 (async()=>{
  const toggle=controls.find(e=>['Dezaktywuj','Aktywuj'].includes(e.textContent));assert(toggle);
  const target=process.argv[3]==='aktywna'?'nieaktywna':'aktywna';let posts=0,updates=0;
  global.showOfferToast=()=>{};global.refreshOffersPanel=()=>{throw Error('No catalog reload allowed');};
  global.refreshOfferMediaState=async offer=>{updates++;offer.Portal_sync={};};
  global.fetch=async url=>{assert.equal(url,'/crm/offers/toggle/17');posts++;return {ok:true,json:async()=>({new_status:target})};};
  const pending=toggle.listeners.click();await toggle.listeners.click();await pending;
  assert.equal(posts,1);assert.equal(updates,1);assert.equal(toggle.disabled,false);
  assert.equal(toggle.textContent,target==='aktywna'?'Dezaktywuj':'Aktywuj');
  assert.equal(details.children[0],row);assert(!details.classList.contains('hidden'));
 })().catch(e=>{console.error(e);process.exit(1)});
}
'''
    result = subprocess.run([executable, '-e', harness, str(JS), str(master).lower(), status],
                            capture_output=True, text=True, encoding='utf-8', timeout=15)
    assert result.returncode == 0, result.stderr
