const header=document.getElementById('header');
  const toggle=document.getElementById('toggle');
  const nav=document.getElementById('nav');
  const story=document.getElementById('story');
  const scenes=[...story.querySelectorAll('.scene')];
  const rail=document.getElementById('rail');
  const cue=document.getElementById('cue');
  const N=scenes.length;
  const reduceMotion=window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  toggle.addEventListener('click',()=>{
    const open=nav.classList.toggle('open');
    toggle.classList.toggle('active',open);
    toggle.setAttribute('aria-expanded',open);
    // Le backdrop-filter du header casse le position:fixed du menu (fond
    // transparent => texte blanc sur page blanche). On le neutralise.
    header.classList.toggle('nav-open',open);
    document.body.style.overflow=open?'hidden':'';
  });
  nav.querySelectorAll('a').forEach(a=>a.addEventListener('click',()=>{
    nav.classList.remove('open');toggle.classList.remove('active');
    header.classList.remove('nav-open');
    toggle.setAttribute('aria-expanded',false);document.body.style.overflow='';
  }));

  const io=new IntersectionObserver((es)=>{es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('in');io.unobserve(e.target);}});},{threshold:.16,rootMargin:'0px 0px -8% 0px'});
  document.querySelectorAll('.reveal').forEach(el=>io.observe(el));

  document.getElementById('year').textContent=new Date().getFullYear();

  /* Formulaire (envoie au back-end si présent, sinon confirme en prévisualisation) */
  const form=document.getElementById('contactForm');
  form.addEventListener('submit',async (e)=>{
    e.preventDefault();
    if(!form.checkValidity()){form.reportValidity();return;}
    const payload={sujet:'Contact',nom:nom.value,email:email.value,telephone:tel.value,type_bien:(document.getElementById('tb')?document.getElementById('tb').value:''),message:msg.value};
    try{const r=await fetch('/api/contact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});if(r&&!r.ok)throw 0;}catch(_){}
    document.getElementById('formDone').classList.add('show');
    form.querySelectorAll('input,textarea').forEach(i=>i.value='');
    form.querySelector('button').style.display='none';
  });

  /* Bascule entre les deux formulaires (contact / visite) */
  var fsBtns=document.querySelectorAll('.fs-btn');
  fsBtns.forEach(function(btn){
    btn.addEventListener('click',function(){
      fsBtns.forEach(function(b){b.classList.remove('active');});
      btn.classList.add('active');
      var target=btn.getAttribute('data-target');
      var cf=document.getElementById('contactForm'), vf=document.getElementById('visitForm');
      if(cf) cf.style.display=(target==='contactForm')?'':'none';
      if(vf) vf.style.display=(target==='visitForm')?'':'none';
    });
  });
  if(location.hash==='#visite'){
    var vbtn=document.querySelector('.fs-btn[data-target="visitForm"]');
    if(vbtn) vbtn.click();
  }

  /* Formulaire "Demander une visite" */
  var vform=document.getElementById('visitForm');
  if(vform){
    vform.addEventListener('submit',async function(e){
      e.preventDefault();
      if(!vform.checkValidity()){vform.reportValidity();return;}
      var payload={sujet:'Visite',nom:v_nom.value,telephone:v_tel.value,type_bien:v_bien.value,creneau:v_creneau.value,message:(v_msg.value||'Demande de visite')};
      try{var r=await fetch('/api/contact',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});if(r&&!r.ok)throw 0;}catch(_){}
      document.getElementById('visitDone').classList.add('show');
      vform.querySelectorAll('input,textarea').forEach(function(i){i.value='';});
      vform.querySelector('button').style.display='none';
    });
  }

  /* ---- SCROLL STORY ENGINE ---- */
  if(reduceMotion){
    story.classList.add('no-motion');
    header.classList.add('scrolled');
  }else{
    function setHeight(){ story.style.height=(N*100)+'vh'; }
    setHeight();
    let ticking=false;
    function render(){
      ticking=false;
      const rect=story.getBoundingClientRect();
      const travel=story.offsetHeight-window.innerHeight;
      let p=travel>0 ? (-rect.top)/travel : 0;
      p=Math.min(1,Math.max(0,p));
      const x=p*(N-1);
      // Fondu resserre. Avant : op = 1 - d, donc a mi-parcours les deux
      // images etaient a 50% et le fond sombre transparaissait au travers
      // des deux -> effet delave/flou. Ici l'image en place reste pleinement
      // opaque pendant que la suivante apparait par-dessus : le passage est
      // net, sans voile.
      const FADE=0.30;
      const clamp01=v=>v<0?0:(v>1?1:v);
      scenes.forEach((s,k)=>{
        const d=Math.abs(x-k);
        const op=clamp01((1-d)/FADE);
        s.style.opacity=op.toFixed(3);
        s.style.pointerEvents=op>0.5?'auto':'none';
        const img=s.querySelector('.scene-img');
        if(img) img.style.transform='scale('+(1.05-0.05*op).toFixed(3)+')';
        const cap=s.querySelector('.scene-cap');
        if(cap){
          // Le texte sort avant l'echange d'image et le suivant arrive apres :
          // jamais deux legendes superposees.
          const sd=x-k;
          const c=sd>=0 ? clamp01(1-sd/0.18) : clamp01((sd+0.35)/0.25);
          cap.style.opacity=c.toFixed(3);
          const base=cap.classList.contains('pos-c')?'translate(-50%,-50%) ':
                     (cap.classList.contains('pos-bc')?'translateX(-50%) ':'');
          cap.style.transform=base+'translateY('+((1-c)*42).toFixed(1)+'px)';
        }
      });
      const active=Math.round(x);
      rail.querySelectorAll('.tick').forEach((t,i)=>t.classList.toggle('on',i<=active));
      const inStory=rect.top<=0 && rect.bottom>=window.innerHeight;
      rail.classList.toggle('show',inStory && p<0.985);
      cue.style.opacity=(inStory && p<0.12)?'1':'0';
      cue.style.pointerEvents='none';
      header.classList.toggle('scrolled', rect.bottom<=window.innerHeight+2);
    }
    for(let i=0;i<N;i++){const t=document.createElement('div');t.className='tick';t.innerHTML='<i></i>';rail.appendChild(t);}
    window.addEventListener('scroll',()=>{if(!ticking){requestAnimationFrame(render);ticking=true;}},{passive:true});
    window.addEventListener('resize',()=>{setHeight();render();});
    render();
  }

  /* ============================================================
     CONTENU DYNAMIQUE (textes, avantages, logements)
     Chaque bloc est protégé : en cas d'échec, le contenu HTML
     statique déjà en place reste affiché (aucune casse possible).
     ============================================================ */
  (function(){
    function esc(s){return String(s==null?'':s).replace(/[&<>"]/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c];});}

    /* --- Textes éditables --- */
    fetch('/api/content').then(function(r){return r.ok?r.json():null;}).then(function(c){
      if(!c) return;
      document.querySelectorAll('[data-content]').forEach(function(el){
        var key=el.getAttribute('data-content');
        var val=c[key];
        if(val==null||val==='') return;
        el.textContent=val;
        var link=el.getAttribute('data-link');
        if(link==='tel') el.setAttribute('href','tel:'+String(val).replace(/\s+/g,''));
        if(link==='mailto') el.setAttribute('href','mailto:'+val);
      });
    }).catch(function(){});

    /* --- Avantages --- */
    var ICON={
      securite:'<path d="M12 3l7 3v5c0 4.5-3 7.6-7 9-4-1.4-7-4.5-7-9V6l7-3z"/>',
      piscine:'<path d="M3 14c2 0 2 1.4 4.5 1.4S10 14 12 14s2 1.4 4.5 1.4S19 14 21 14"/><path d="M3 18.5c2 0 2 1.4 4.5 1.4S10 18.5 12 18.5s2 1.4 4.5 1.4S19 18.5 21 18.5"/><path d="M7 14V6.5a2 2 0 0 1 4 0M14 14V7"/>',
      sport:'<path d="M4 9v6M7 7v10M17 7v10M20 9v6M7 12h10"/>',
      parking:'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M9.5 16V8h3a2.5 2.5 0 0 1 0 5h-3"/>',
      espaces:'<path d="M12 21v-7"/><path d="M12 14c0-4 3-7.5 7.5-7.5C19.5 11 16 14 12 14z"/><path d="M12 16.5c0-3.2-2.6-5.5-6-5.5 0 3.2 2.6 5.5 6 5.5z"/>',
      commerce:'<path d="M5 8h14l1 12H4L5 8z"/><path d="M9 8a3 3 0 0 1 6 0"/>',
      jeux:'<circle cx="12" cy="8.5" r="5.5"/><path d="M12 14v6M9.5 20h5"/>',
      cinema:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 9.5h18M8 5v14M16 5v14"/>',
      maison:'<path d="M4 11l8-6 8 6"/><path d="M6 10v9h12v-9"/>',
      cle:'<circle cx="8" cy="8" r="4"/><path d="M11 11l8 8M16 16l2-2M18 18l2-2"/>',
      etoile:'<path d="M12 3l2.6 6.3 6.4.5-4.9 4 1.6 6.2L12 16.9 6.3 20l1.6-6.2-4.9-4 6.4-.5z"/>',
      soleil:'<circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2"/>',
      climatisation:'<path d="M12 2v20M4.5 6l15 12M19.5 6l-15 12M2 12h20"/>',
      chauffage:'<path d="M12 22c3 0 5-2.2 5-5 0-3-2-4.5-3-7-1 2-1.5 3-2.5 3-1.5 0-1-3-1-4-3 2-4 6-4 8 0 2.8 2 5 5.5 5z"/>',
      fibre:'<path d="M12 20h.01M8.5 16.5a5 5 0 0 1 7 0M5.5 13.5a9 9 0 0 1 13 0M3 10.5a13 13 0 0 1 18 0"/>',
      camera:'<rect x="3" y="7" width="13" height="11" rx="2"/><path d="M16 10.5l5-2.5v9l-5-2.5z"/>',
      video:'<rect x="4" y="4" width="16" height="12" rx="2"/><path d="M9 20h6M12 16v4"/><circle cx="12" cy="10" r="2.4"/>',
      vitrage:'<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 12h16M12 4v16"/>',
      ascenseur:'<rect x="6" y="3" width="12" height="18" rx="1.5"/><path d="M10 8l2-2 2 2M10 15l2 2 2-2"/>',
      credit:'<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18M7 15h4"/>',
      horloge:'<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3.5 2"/>',
      accompagnement:'<path d="M8 12a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM16 12a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/><path d="M2 20c.5-3.5 3-5.5 6-5.5s5.5 2 6 5.5M12 20c.5-3.5 3-5.5 6-5.5"/>'
    };
    var avGrid=document.getElementById('avGrid');
    if(avGrid){
      fetch('/api/avantages').then(function(r){return r.ok?r.json():null;}).then(function(list){
        if(!Array.isArray(list)||!list.length) return;
        avGrid.innerHTML=list.map(function(a){
          var ic=ICON[a.icon]||ICON.etoile;
          return '<div class="av reveal in"><svg viewBox="0 0 24 24">'+ic+'</svg><h4>'+esc(a.titre)+'</h4><p>'+esc(a.texte)+'</p></div>';
        }).join('');
      }).catch(function(){});
    }

    /* --- Galerie : carrousel avec catégories (Extérieur / Intérieur) --- */
    var galTrack=document.getElementById('galTrack');
    if(galTrack){
      fetch('/api/content').then(function(r){return r.ok?r.json():null;}).then(function(content){
        var items=[];
        if(content && content.gallery_items){
          try{ items=JSON.parse(content.gallery_items); }catch(_){}
        }
        if(!items.length) return;

        var current='exterieur';
        function render(){
          var filtered=items.filter(function(it){return it.cat===current;});
          if(!filtered.length) filtered=items;
          galTrack.innerHTML=filtered.map(function(it){
            return '<div class="gal-slide"><div class="gal-item"><img src="'+esc(it.src)+'" alt="" loading="lazy" onerror="this.closest(\'.gal-slide\').style.display=\'none\'"></div></div>';
          }).join('');
          galTrack.scrollTo({left:0});
        }
        render();

        document.querySelectorAll('.gal-tab').forEach(function(tab){
          tab.addEventListener('click',function(){
            document.querySelectorAll('.gal-tab').forEach(function(t){t.classList.remove('active');});
            tab.classList.add('active');
            current=tab.getAttribute('data-cat');
            render();
          });
        });

        var prevBtn=document.querySelector('.gal-prev'), nextBtn=document.querySelector('.gal-next');
        function step(){ var s=galTrack.querySelector('.gal-slide'); return s? s.getBoundingClientRect().width+16 : 300; }
        if(prevBtn) prevBtn.addEventListener('click',function(){ galTrack.scrollBy({left:-step(),behavior:'smooth'}); });
        if(nextBtn) nextBtn.addEventListener('click',function(){ galTrack.scrollBy({left:step(),behavior:'smooth'}); });
      }).catch(function(){});
    }
  })();
