(()=>{
  document.querySelectorAll('.ref-row').forEach(row=>{const actions=row.querySelector('.ref-actions'),id=row.querySelector('input[name="id"]')?.value;if(actions&&id&&!row.classList.contains('is-archived')){const link=document.createElement('a');link.className='ref-edit';link.href='/public/administration/axiom/referentiels?type=poles&edit='+encodeURIComponent(id);link.textContent='Modifier';actions.prepend(link)}});
  const label=document.querySelector('#pole-label'),code=document.querySelector('#pole-code'),color=document.querySelector('#pole-color');if(!label||!code)return;
  let manual=code.hasAttribute('data-existing');
  const choices={structure:{label:'Structure',code:'STR',color:'#334155'},theatre:{label:'Théâtre',code:'THE',color:'#7c3aed'},musique:{label:'Musique',code:'MUS',color:'#2563eb'},arts:{label:'Arts plastiques',code:'ART',color:'#ea580c'},autre:{label:'',code:'',color:'#0f766e'}};
  const normalize=value=>value.normalize('NFD').replace(/[\u0300-\u036f]/g,'').toUpperCase().replace(/[^A-Z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,20),selected=()=>document.querySelector('[name="pole_kind"]:checked');
  const refresh=()=>{const input=selected();if(!input)return;const choice=choices[input.value];if(input.value!=='autre'&&!label.value.trim())label.value=choice.label;if(color)color.value=choice.color;if(!manual)code.value='POL-'+(choice.code||normalize(label.value))};
  document.querySelectorAll('[name="pole_kind"]').forEach(input=>input.addEventListener('change',()=>{const choice=choices[input.value];if(input.checked&&input.value!=='autre')label.value=choice.label;manual=code.hasAttribute('data-existing');refresh()}));
  label.addEventListener('input',()=>{if(selected()?.value==='autre'&&!manual)refresh()});code.addEventListener('input',()=>manual=code.value.trim()!=='');refresh();
})();
