/* app.js — Portail de restitution Cas ESS (vanilla, sans dépendance) */
(function(){
  'use strict';
  var $=function(s,c){return (c||document).querySelector(s);};
  var $$=function(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));};
  document.documentElement.classList.add('js'); /* progressive enhancement : contenu visible sans JS */
  /* filet de sécurité : tout révéler après chargement complet (robustesse / captures) */
  window.addEventListener('load',function(){setTimeout(function(){$$('.reveal').forEach(function(el){el.classList.add('in');});},700);});

  /* Barre de progression */
  var prog=$('.progress');
  function onScroll(){
    if(!prog) return;
    var h=document.documentElement;
    var p=h.scrollTop/(h.scrollHeight-h.clientHeight||1);
    prog.style.width=(p*100).toFixed(1)+'%';
  }
  document.addEventListener('scroll',onScroll,{passive:true});onScroll();

  /* Menu mobile */
  var side=$('.side'),menuBtn=$('.menubtn');
  if(menuBtn){menuBtn.addEventListener('click',function(){side.classList.toggle('open');});}
  $$('.nav a').forEach(function(a){a.addEventListener('click',function(){if(side)side.classList.remove('open');});});

  /* Scrollspy */
  var links=$$('.nav a[href^="#"]');
  var map={};links.forEach(function(a){map[a.getAttribute('href').slice(1)]=a;});
  if('IntersectionObserver' in window){
    var spy=new IntersectionObserver(function(es){
      es.forEach(function(e){
        if(e.isIntersecting){
          links.forEach(function(l){l.classList.remove('active');});
          var a=map[e.target.id];if(a)a.classList.add('active');
        }
      });
    },{rootMargin:'-45% 0px -50% 0px'});
    $$('section[id]').forEach(function(s){spy.observe(s);});
  }

  /* Reveal */
  if('IntersectionObserver' in window && !matchMedia('(prefers-reduced-motion:reduce)').matches){
    var rev=new IntersectionObserver(function(es){
      es.forEach(function(e){if(e.isIntersecting){e.target.classList.add('in');rev.unobserve(e.target);}});
    },{rootMargin:'0px 0px -8% 0px',threshold:.04});
    $$('.reveal').forEach(function(el){rev.observe(el);});
  } else { $$('.reveal').forEach(function(el){el.classList.add('in');}); }

  /* Modale de consultation */
  var modal=$('#viewer'),frame=modal&&$('iframe',modal),mtitle=modal&&$('.bar h4',modal),dlBtn=modal&&$('#mdl-dl');
  function openView(src,title,dl){
    if(!modal)return;
    frame.src=src;mtitle.textContent=title||'Consultation';
    if(dlBtn){if(dl){dlBtn.style.display='';dlBtn.setAttribute('href',dl);}else{dlBtn.style.display='none';}}
    modal.classList.add('open');document.body.style.overflow='hidden';
  }
  function closeView(){if(!modal)return;modal.classList.remove('open');frame.src='about:blank';document.body.style.overflow='';}
  if(modal){
    $('.x',modal).addEventListener('click',closeView);
    modal.addEventListener('click',function(e){if(e.target===modal)closeView();});
    document.addEventListener('keydown',function(e){if(e.key==='Escape')closeView();});
  }
  /* Boutons Consulter + chips de preuve */
  $$('[data-view]').forEach(function(el){
    el.addEventListener('click',function(e){
      e.preventDefault();
      openView(el.getAttribute('data-view'),el.getAttribute('data-title'),el.getAttribute('data-dl'));
    });
  });

  /* Centre documentaire : filtres + recherche */
  var docs=$$('.doc'),chips=$$('.chip[data-filter]'),searchInput=$('#docsearch');
  var activeFilter='all',query='';
  function applyFilters(){
    docs.forEach(function(d){
      var theme=d.getAttribute('data-theme')||'',aud=d.getAttribute('data-aud')||'',prio=d.getAttribute('data-prio')||'';
      var text=(d.textContent||'').toLowerCase();
      var okF=activeFilter==='all'||theme.indexOf(activeFilter)>-1||aud===activeFilter||prio===activeFilter;
      var okQ=!query||text.indexOf(query)>-1;
      d.style.display=(okF&&okQ)?'':'none';
    });
    var none=$('#docnone');
    if(none){var vis=docs.filter(function(d){return d.style.display!=='none';}).length;none.style.display=vis?'none':'';}
  }
  chips.forEach(function(c){c.addEventListener('click',function(){
    chips.forEach(function(x){x.classList.remove('on');});c.classList.add('on');
    activeFilter=c.getAttribute('data-filter');applyFilters();
  });});
  if(searchInput){searchInput.addEventListener('input',function(){query=searchInput.value.toLowerCase().trim();applyFilters();});}

  /* FAB */
  $$('#fab-print,#fab-print2').forEach(function(b){b.addEventListener('click',function(){window.print();});});
  var tbtn=$('#fab-top');
  if(tbtn)tbtn.addEventListener('click',function(){window.scrollTo({top:0,behavior:'smooth'});});

  /* ===== Animations & interactions ===== */
  var reduced=matchMedia('(prefers-reduced-motion:reduce)').matches;

  /* Cascade d'apparition */
  ['.takeaways','.stats','.doclist','.riskmap'].forEach(function(sel){
    var c=$(sel); if(!c)return;
    Array.prototype.forEach.call(c.children,function(ch,i){ if(ch.classList&&ch.classList.contains('reveal'))ch.style.setProperty('--d',(i*70)+'ms');});
  });

  /* Compteurs animés */
  function prepCount(el){
    var raw=(el.textContent||'').trim();
    var m=raw.match(/^[\d   .,]+/); if(!m)return;
    var numPart=m[0], suf=raw.replace(numPart,'').trim();
    var hasC=numPart.indexOf(',')>-1;
    var num=parseFloat(numPart.replace(/[^\d,]/g,'').replace(',','.')); if(isNaN(num))return;
    var dec=hasC?(numPart.split(',')[1].replace(/\D/g,'').length):0;
    el.setAttribute('data-to',num); el.setAttribute('data-dec',dec); el.setAttribute('data-suf',suf?(' '+suf):'');
    el.textContent='0'+(suf?(' '+suf):'');
  }
  function countUp(el){
    if(el._c)return; el._c=true;
    var to=parseFloat(el.getAttribute('data-to')); if(isNaN(to))return;
    var dec=parseInt(el.getAttribute('data-dec')||'0',10), suf=el.getAttribute('data-suf')||'';
    function fmt(n){return n.toLocaleString('fr-FR',{minimumFractionDigits:dec,maximumFractionDigits:dec})+suf;}
    if(reduced){el.textContent=fmt(to);return;}
    var dur=1100,t0=null;
    function step(ts){if(!t0)t0=ts;var p=Math.min((ts-t0)/dur,1),e=1-Math.pow(1-p,3);
      el.textContent=fmt(to*e); if(p<1)requestAnimationFrame(step); else el.textContent=fmt(to);}
    requestAnimationFrame(step);
  }
  $$('.stat .v').forEach(prepCount);

  /* Donut qui se dessine + jauge qui se remplit */
  function drawDonut(w){ if(w._d)return; w._d=true;
    $$('.ring',w).forEach(function(r,i){ var d=r.getAttribute('data-dash'); if(!d)return;
      if(reduced){r.style.strokeDasharray=d;return;}
      r.style.transitionDelay=(i*150)+'ms';
      requestAnimationFrame(function(){r.style.strokeDasharray=d;});
    });
  }
  function fillGauge(g){ if(g._g)return; g._g=true; var wv=g.getAttribute('data-w')||'0';
    if(reduced){g.style.width=wv;return;} requestAnimationFrame(function(){g.style.width=wv;}); }

  if('IntersectionObserver' in window){
    var io=new IntersectionObserver(function(es){es.forEach(function(e){ if(!e.isIntersecting)return;
      var t=e.target;
      if(t.matches('.stat .v'))countUp(t);
      else if(t.matches('.donut-wrap'))drawDonut(t);
      else if(t.matches('.gauge2-fill'))fillGauge(t);
      io.unobserve(t);
    });},{rootMargin:'0px 0px -6% 0px',threshold:.25});
    $$('.stat .v,.donut-wrap,.gauge2-fill').forEach(function(el){io.observe(el);});
  } else {
    $$('.stat .v').forEach(countUp); $$('.donut-wrap').forEach(drawDonut); $$('.gauge2-fill').forEach(fillGauge);
  }

  /* Ripple au clic */
  function ripple(e){
    if(reduced)return;
    var el=e.currentTarget, r=el.getBoundingClientRect();
    var s=document.createElement('span'); s.className='ripple';
    var size=Math.max(r.width,r.height); s.style.width=s.style.height=size+'px';
    s.style.left=((e.clientX||r.left+r.width/2)-r.left-size/2)+'px';
    s.style.top=((e.clientY||r.top+r.height/2)-r.top-size/2)+'px';
    el.appendChild(s); setTimeout(function(){s.remove();},640);
  }
  $$('.btn,.chip,.proof,.st-btn,.fab button').forEach(function(el){el.addEventListener('click',ripple);});

  /* Spotlight curseur sur la couverture */
  var cover=$('.cover');
  if(cover && !reduced){
    cover.addEventListener('mousemove',function(e){
      var r=cover.getBoundingClientRect();
      cover.style.setProperty('--mx',((e.clientX-r.left)/r.width*100).toFixed(1)+'%');
      cover.style.setProperty('--my',((e.clientY-r.top)/r.height*100).toFixed(1)+'%');
    });
  }

  /* Gadget : simulateur de réduction fiscale */
  var simRate=0.66, simAmt=2000;
  function frInt(n){return Math.round(n).toLocaleString('fr-FR');}
  function setNum(el,v){ if(!el)return;
    if(reduced){el.textContent=frInt(v);return;}
    var from=el._v||0, to=v, t0=null,dur=420; el._v=to;
    function step(ts){if(!t0)t0=ts;var p=Math.min((ts-t0)/dur,1),e=1-Math.pow(1-p,3);
      el.textContent=frInt(from+(to-from)*e); if(p<1)requestAnimationFrame(step); else el.textContent=frInt(to);}
    requestAnimationFrame(step);
  }
  function renderSim(){
    var red=simAmt*simRate, net=simAmt-red;
    setNum($('#simu-red'),red); setNum($('#simu-net'),net);
    var a=$('#simu-amt'); if(a)a.textContent=frInt(simAmt);
    var rg=$('#simu-range'); if(rg){var p=(simAmt-rg.min)/(rg.max-rg.min)*100; rg.style.setProperty('--p',p+'%');}
  }
  $$('.st-btn').forEach(function(b){b.addEventListener('click',function(){
    $$('.st-btn').forEach(function(x){x.classList.remove('on');}); b.classList.add('on');
    simRate=parseFloat(b.getAttribute('data-rate')); renderSim();
  });});
  var srg=$('#simu-range');
  if(srg){srg.addEventListener('input',function(){simAmt=parseInt(srg.value,10)||0; renderSim();}); renderSim();}
})();
