/** MageStock 2.6.124 — installateur multi-étapes sans état serveur intermédiaire. */
(function(){
'use strict';
const root=document.querySelector('[data-install-root]');
if(!root)return;
const form=document.getElementById('installForm');
const panes=[...document.querySelectorAll('[data-install-pane]')];
const steps=[...document.querySelectorAll('[data-install-step]')];
const back=document.getElementById('installBack');
const next=document.getElementById('installNext');
const submit=document.getElementById('installSubmit');
const progress=document.getElementById('installProgressText');
let current=Math.max(0,Math.min(panes.length-1,Number(root.dataset.initialStep||0)));
let maxVisited=current;
const systemReady=root.dataset.systemReady==='1';

function activeFields(index){return [...panes[index].querySelectorAll('input,select,textarea')].filter(el=>!el.disabled && el.type!=='hidden');}
function validatePane(index){
  if(index===0 && !systemReady)return false;
  for(const field of activeFields(index)){
    if(!field.checkValidity()){field.reportValidity();field.focus({preventScroll:true});field.scrollIntoView({behavior:'smooth',block:'center'});return false;}
  }
  if(index===2){
    const p=document.getElementById('adminPassword');
    const c=document.getElementById('adminPasswordConfirm');
    if(p&&c&&p.value!==c.value){c.setCustomValidity('Les deux mots de passe ne correspondent pas.');c.reportValidity();c.focus();return false;}
    if(c)c.setCustomValidity('');
  }
  return true;
}
function setStep(index){
  current=Math.max(0,Math.min(panes.length-1,index));maxVisited=Math.max(maxVisited,current);
  panes.forEach((pane,i)=>pane.classList.toggle('is-active',i===current));
  steps.forEach((button,i)=>{button.classList.toggle('is-current',i===current);button.classList.toggle('is-complete',i<current);button.setAttribute('aria-current',i===current?'step':'false');});
  back.hidden=current===0;next.hidden=current===panes.length-1;submit.hidden=current!==panes.length-1;
  next.disabled=current===0&&!systemReady;
  if(progress)progress.textContent=`Étape ${current+1} sur ${panes.length}`;
  if(current===panes.length-1)populateReview();
  const scroller=document.querySelector('.install-panel-scroll');
  if(scroller){if(window.matchMedia('(max-width:680px)').matches)window.scrollTo({top:0,behavior:'smooth'});else scroller.scrollTo({top:0,behavior:'smooth'});}
}
function value(id,fallback='—'){const el=document.getElementById(id);if(!el)return fallback;if(el.type==='checkbox')return el.checked?'Oui':'Non';if(el.tagName==='SELECT')return el.options[el.selectedIndex]?.text||fallback;return el.value.trim()||fallback;}
function review(id,text){const el=document.querySelector(`[data-review="${id}"]`);if(el)el.textContent=text;}
function populateReview(){
 review('companyName',value('companyName'));review('language',value('language'));review('locale',value('locale'));review('country',value('country'));review('currency',value('currency'));review('timezone',value('timezone'));review('warehouseName',value('warehouseName'));review('warehouseAddress',value('warehouseAddress','Non renseignée'));review('locationCode',value('locationCode','Non créé'));review('enablePush',value('enablePush'));
}
next?.addEventListener('click',()=>{if(validatePane(current))setStep(current+1);});
back?.addEventListener('click',()=>setStep(current-1));
steps.forEach((button,i)=>button.addEventListener('click',()=>{if(i<=maxVisited)setStep(i);}));
form?.addEventListener('submit',event=>{
  if(!validatePane(current)){event.preventDefault();return;}
  const confirm=document.getElementById('installConfirm');
  if(confirm&&!confirm.checked){event.preventDefault();confirm.focus();return;}
  submit.disabled=true;submit.setAttribute('aria-busy','true');submit.textContent='Installation en cours…';
});
const password=document.getElementById('adminPassword');
const confirmPassword=document.getElementById('adminPasswordConfirm');
function passwordStatus(){
 if(!password)return;const v=password.value;const rules={length:v.length>=14,lower:/[a-z]/.test(v),upper:/[A-Z]/.test(v),number:/\d/.test(v),symbol:/[^A-Za-z0-9]/.test(v),identity:!/(magestock|admin)/i.test(v)};
 let score=0;Object.entries(rules).forEach(([key,ok])=>{document.querySelector(`[data-password-rule="${key}"]`)?.classList.toggle('is-valid',ok);if(ok)score++;});
 const bar=document.querySelector('.password-meter>span');if(bar){bar.style.width=`${Math.round(score/6*100)}%`;bar.style.background=score>=6?'var(--install-success)':score>=4?'var(--install-warning)':'var(--install-danger)';}
 if(confirmPassword&&confirmPassword.value)confirmPassword.setCustomValidity(password.value===confirmPassword.value?'':'Les deux mots de passe ne correspondent pas.');
}
password?.addEventListener('input',passwordStatus);confirmPassword?.addEventListener('input',passwordStatus);passwordStatus();
setStep(current);
})();
