(() => {
  'use strict';
  const $=(s,r=document)=>r.querySelector(s), $$=(s,r=document)=>Array.from(r.querySelectorAll(s));
  const toast=(title,message='')=>{let stack=$('.ax-toast-stack');if(!stack){stack=document.createElement('div');stack.className='ax-toast-stack';document.body.appendChild(stack)}const el=document.createElement('div');el.className='ax-toast';el.innerHTML=`<strong>${title}</strong>${message?`<span>${message}</span>`:''}`;stack.appendChild(el);setTimeout(()=>el.remove(),3200)};
  window.AxiomUX={toast};
  $$('.ax-tabs').forEach(tabs=>tabs.addEventListener('click',e=>{const b=e.target.closest('[data-tab]');if(!b)return;const panel=tabs.closest('.ax-panel');$$('[data-tab]',tabs).forEach(x=>x.classList.toggle('is-active',x===b));$$('.ax-tabpane',panel).forEach(x=>x.classList.toggle('is-active',x.dataset.pane===b.dataset.tab))}));
  const variableSearch=$('#ax-variable-search');if(variableSearch)variableSearch.addEventListener('input',()=>{const q=variableSearch.value.toLowerCase().trim();$$('.ax-token').forEach(x=>x.hidden=q&&!x.textContent.toLowerCase().includes(q))});
  const editor=$('#document-editor'),body=$('#body_html'),form=$('#document-form'),preview=$('#document-preview');
  if(!editor)return;
  const sync=()=>{if(body)body.value=editor.innerHTML};
  if(form)form.addEventListener('submit',()=>{sync();sessionStorage.removeItem('axiom-doc-autosave')});
  $$('[data-cmd]').forEach(b=>b.addEventListener('click',()=>{document.execCommand(b.dataset.cmd,false,b.dataset.value||null);editor.focus();sync()}));
  $$('[data-token]').forEach(b=>b.addEventListener('click',()=>{document.execCommand('insertText',false,b.dataset.token);editor.focus();sync();toast('Variable insérée',b.dataset.token)}));
  $$('[data-insert-html]').forEach(b=>b.addEventListener('click',()=>{document.execCommand('insertHTML',false,b.dataset.insertHtml);editor.focus();sync()}));
  const searchComponents=$$('#ax-components [data-insert-html]'); searchComponents.forEach(b=>b.setAttribute('draggable','true'));
  searchComponents.forEach(b=>b.addEventListener('dragstart',e=>e.dataTransfer.setData('text/html',b.dataset.insertHtml||'')));
  editor.addEventListener('dragover',e=>e.preventDefault());editor.addEventListener('drop',e=>{const html=e.dataTransfer.getData('text/html');if(html){e.preventDefault();document.execCommand('insertHTML',false,html);sync()}});
  let dirty=false,timer;editor.addEventListener('input',()=>{dirty=true;sync();clearTimeout(timer);timer=setTimeout(()=>{sessionStorage.setItem('axiom-doc-autosave',editor.innerHTML);dirty=false;const s=$('#ax-save-status');if(s)s.textContent='Brouillon local sauvegardé';},700)});
  const saved=sessionStorage.getItem('axiom-doc-autosave');if(saved&&editor.dataset.templateId==='0'&&saved!==editor.innerHTML){editor.innerHTML=saved;toast('Brouillon restauré','La sauvegarde locale a été rechargée.')}
  window.addEventListener('beforeunload',e=>{if(dirty){e.preventDefault();e.returnValue=''}});
  const zoom=$('#ax-zoom'),zoomLabel=$('#ax-zoom-label'),page=$('#ax-page');const applyZoom=()=>{if(!zoom||!page)return;const v=Number(zoom.value)/100;page.style.transform=`scale(${v})`;page.style.marginBottom=`-${Math.round(page.offsetHeight*(1-v))}px`;if(zoomLabel)zoomLabel.textContent=zoom.value+'%'};if(zoom){zoom.addEventListener('input',applyZoom);applyZoom()}
  const refreshPreview=()=>{sync();let html=editor.innerHTML;let data={};try{data=JSON.parse($('#sample-json')?.value||'{}')}catch(e){toast('JSON invalide','Corrigez les données de test.');return}const flatten=(o,p='')=>Object.entries(o||{}).forEach(([k,v])=>{const key=p?`${p}.${k}`:k;if(v&&typeof v==='object'&&!Array.isArray(v))flatten(v,key);else html=html.split(`{{${key}}}`).join(v??'')});flatten(data);if(preview)preview.innerHTML=html;toast('Aperçu actualisé')};
  $('#refresh-preview')?.addEventListener('click',refreshPreview);
  const modal=$('#ax-preview-modal');$('#ax-open-preview')?.addEventListener('click',()=>{refreshPreview();modal?.classList.add('is-open')});$('#ax-close-preview')?.addEventListener('click',()=>modal?.classList.remove('is-open'));modal?.addEventListener('click',e=>{if(e.target===modal)modal.classList.remove('is-open')});
  $('#ax-print')?.addEventListener('click',()=>window.print());
  $('#ax-toggle-library')?.addEventListener('click',()=>$('.ax-left')?.classList.toggle('is-mobile-open'));
  const orientation=$('[name="orientation"]');orientation?.addEventListener('change',()=>page?.classList.toggle('is-landscape',orientation.value==='landscape'));
  $('#generate-form')?.addEventListener('submit',()=>{const out=$('#generate-json'),src=$('#sample-json');if(out&&src)out.value=src.value});
  document.addEventListener('keydown',e=>{if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();form?.requestSubmit()}if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='p'){e.preventDefault();$('#ax-open-preview')?.click()}});
})();
