/* ===========================================================================
   VIZIS — interactions (vanilla, no dependencies)
   =========================================================================== */
(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)); };
  var REDUCE = matchMedia("(prefers-reduced-motion: reduce)").matches;
  var TOUCH  = matchMedia("(hover: none), (max-width: 760px)").matches;

  /* ---------- preloader ---------- */
  var pre = $("#pre");
  if(pre){
    if(REDUCE){ pre.classList.add("done"); }
    else{
      pre.classList.add("run");
      window.addEventListener("load", function(){ setTimeout(function(){ pre.classList.add("done"); }, 350); });
      setTimeout(function(){ pre.classList.add("done"); }, 2200); /* safety */
    }
  }

  /* ---------- nav solidify + mobile menu ---------- */
  var nav = $("#nav");
  function navState(){ if(nav) nav.classList.toggle("solid", scrollY > (innerHeight*0.6)); }
  navState(); addEventListener("scroll", navState, {passive:true});
  var burger = $("#burger"), mob = $("#mob");
  if(burger && mob){
    function toggleMob(){ var o = mob.classList.toggle("open"); burger.classList.toggle("x", o);
      document.body.style.overflow = o ? "hidden" : ""; }
    burger.addEventListener("click", toggleMob);
    $$("a", mob).forEach(function(a){ a.addEventListener("click", function(){
      mob.classList.remove("open"); burger.classList.remove("x"); document.body.style.overflow=""; }); });
  }

  /* ---------- IntersectionObserver reveals ---------- */
  if("IntersectionObserver" in window && !REDUCE){
    var io = new IntersectionObserver(function(es){ es.forEach(function(e){
      if(e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); } }); },
      {threshold:.18, rootMargin:"0px 0px -8% 0px"});
    $$(".fu, .reveal").forEach(function(el){ io.observe(el); });
  } else { $$(".fu, .reveal").forEach(function(el){ el.classList.add("in"); }); }

  /* wrap headline words for reveal (.reveal-words) — inline-block masks,
     so the heading still wraps and reads normally, left to right. */
  $$(".reveal-words").forEach(function(el){
    if(REDUCE) return;
    var words = el.textContent.trim().split(/\s+/);
    el.innerHTML = words.map(function(w){ return '<span class="r-word"><span>'+w+'</span></span>'; }).join(" ");
  });

  /* ---------- hero signature transition (clip-path wipe + scale settle) ---------- */
  var hslides = $$("#heroMedia .slide");
  if(hslides.length>1 && !REDUCE){
    var hi=0;
    setInterval(function(){
      var prev = hslides[hi];
      hi = (hi+1) % hslides.length;
      var next = hslides[hi];
      prev.classList.remove("on"); prev.classList.add("out");
      next.classList.add("on");
      setTimeout(function(){ prev.classList.remove("out"); }, 1500);
    }, 5800);
  }
  /* hero parallax */
  var heroMedia = $("#heroMedia");
  if(heroMedia && !REDUCE && !TOUCH){
    addEventListener("scroll", function(){ var y=scrollY; if(y<innerHeight){ heroMedia.style.transform="translateY("+(y*0.18)+"px)"; } }, {passive:true});
  }

  /* ---------- PINNED HORIZONTAL SHOWCASE ---------- */
  var sc = $("#showcase");
  if(sc){
    var track = $("#scTrack", sc), pin = $(".pin", sc), bar = $("#scBar", sc);
    var flat = TOUCH || REDUCE;
    if(flat){ sc.classList.add("flat"); }
    else{
      var distance = 0, top = 0;
      function measure(){
        track.style.transform = "translateX(0)";
        distance = Math.max(0, track.scrollWidth - innerWidth);
        sc.style.height = (innerHeight + distance) + "px";
        top = sc.offsetTop;
      }
      function onScroll(){
        var p = (scrollY - top) / (sc.offsetHeight - innerHeight);
        p = Math.min(1, Math.max(0, p));
        track.style.transform = "translateX(" + (-p*distance) + "px)";
        if(bar) bar.style.width = (p*100) + "%";
      }
      var raf=false;
      function loop(){ onScroll(); raf=false; }
      addEventListener("scroll", function(){ if(!raf){ raf=true; requestAnimationFrame(loop); } }, {passive:true});
      addEventListener("resize", function(){ measure(); onScroll(); });
      window.addEventListener("load", function(){ measure(); onScroll(); });
      measure(); onScroll();
    }
  }

  /* ---------- services floating preview ---------- */
  var float = $("#svcFloat"), floatImg = float ? $("img", float) : null;
  if(float && !TOUCH){
    var mx=0,my=0,fx=0,fy=0, active=false;
    $$(".svc-row").forEach(function(row){
      row.addEventListener("mouseenter", function(){ active=true; floatImg.src = row.dataset.img; float.classList.add("show"); });
      row.addEventListener("mouseleave", function(){ active=false; float.classList.remove("show"); });
    });
    addEventListener("mousemove", function(e){ mx=e.clientX; my=e.clientY; });
    (function fl(){ fx+=(mx-fx)*0.14; fy+=(my-fy)*0.14;
      if(active){ float.style.left=fx+"px"; float.style.top=fy+"px"; } requestAnimationFrame(fl); })();
  }

  /* ---------- animated counters ---------- */
  function animateCount(el){
    var target = parseFloat(el.dataset.count), suf = el.dataset.suffix || "", dur=1400, t0=null;
    function tick(t){ if(!t0)t0=t; var p=Math.min(1,(t-t0)/dur); var eased=1-Math.pow(1-p,3);
      var val = target * eased;
      el.querySelector(".num").textContent = (target % 1 ? val.toFixed(0) : Math.round(val));
      if(p<1) requestAnimationFrame(tick);
      else el.querySelector(".num").textContent = (target % 1 ? target : Math.round(target)); }
    requestAnimationFrame(tick);
  }
  var counters = $$("[data-count]");
  if(counters.length){
    if("IntersectionObserver" in window && !REDUCE){
      var cio = new IntersectionObserver(function(es){ es.forEach(function(e){
        if(e.isIntersecting){ animateCount(e.target); cio.unobserve(e.target); } }); }, {threshold:.6});
      counters.forEach(function(c){ cio.observe(c); });
    } else { counters.forEach(function(c){ var n=c.querySelector(".num"); if(n) n.textContent=c.dataset.count; }); }
  }

  /* ---------- gallery build + filter + lightbox ---------- */
  var grid = $("#grid");
  if(grid){
    var COUNTS = {exterior:7, interior:7, landscape:5, plan:4, illustration:2};
    var LABEL  = {exterior:"Exterior", interior:"Interior", landscape:"Landscape", plan:"Plan / Section", illustration:"Illustration"};
    var work = [];
    Object.keys(COUNTS).forEach(function(cat){ for(var n=1;n<=COUNTS[cat];n++){
      work.push({cat:cat, label:LABEL[cat], thumb:"assets/img/work/"+cat+"-"+n+"-t.webp", full:"assets/img/work/"+cat+"-"+n+".webp"}); } });
    work.forEach(function(w,idx){
      var b=document.createElement("button"); b.className="tile"; b.dataset.cat=w.cat; b.dataset.idx=idx;
      b.setAttribute("aria-label", w.label+" render — open");
      b.innerHTML='<img loading="lazy" src="'+w.thumb+'" alt="'+w.label+' 3D architectural render by Vizis">'+
        '<span class="ov"><span><b>'+String(idx+1).padStart(2,"0")+'</b> · '+w.label+'</span></span>';
      grid.appendChild(b);
    });
    var act="all";
    $$("#filters button").forEach(function(btn){ btn.addEventListener("click", function(){
      $$("#filters button").forEach(function(x){x.classList.remove("on");}); btn.classList.add("on"); act=btn.dataset.f;
      $$(".tile", grid).forEach(function(t){ t.classList.toggle("hide", act!=="all" && t.dataset.cat!==act); }); }); });

    var lb=$("#lb"), lbImg=$("#lbImg"), lbCap=$("#lbCap"), list=[], pos=0;
    function vis(){ return work.map(function(w,i){ return {w:w,i:i}; }).filter(function(o){ return act==="all"||o.w.cat===act; }); }
    function open(idx){ list=vis(); pos=list.findIndex(function(o){return o.i===idx;}); if(pos<0)pos=0; draw();
      lb.classList.add("open"); document.body.style.overflow="hidden"; }
    function draw(){ var w=list[pos].w; lbImg.src=w.full; lbImg.alt=w.label+" render"; lbCap.textContent=w.label+" — "+String(list[pos].i+1).padStart(2,"0")+" / "+work.length; }
    function close(){ lb.classList.remove("open"); document.body.style.overflow=""; }
    function step(d){ pos=(pos+d+list.length)%list.length; draw(); }
    grid.addEventListener("click", function(e){ var t=e.target.closest(".tile"); if(t) open(+t.dataset.idx); });
    $("#lbX").addEventListener("click", close); $("#lbP").addEventListener("click", function(){step(-1);}); $("#lbN").addEventListener("click", function(){step(1);});
    lb.addEventListener("click", function(e){ if(e.target===lb) close(); });
    addEventListener("keydown", function(e){ if(!lb.classList.contains("open")) return;
      if(e.key==="Escape") close(); if(e.key==="ArrowLeft") step(-1); if(e.key==="ArrowRight") step(1); });
  }

  /* ---------- contact form ---------- */
  var form = $("#contactForm");
  if(form){
    /* OPTIONAL: paste a Formspree/endpoint URL here to capture submissions server-side.
       Leave empty to use the built-in email-app fallback (works with no backend). */
    var ENDPOINT = "";
    function val(id){ var el=$("#"+id); return el ? el.value.trim() : ""; }
    function setErr(id,on){ var el=$("#"+id); if(!el)return; el.classList.toggle("err",on);
      var m=el.parentNode.querySelector(".errmsg"); if(m) m.classList.toggle("on",on); }
    function validEmail(e){ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e); }
    form.addEventListener("submit", function(e){
      e.preventDefault();
      var ok=true;
      if(!val("c-name")){ setErr("c-name",true); ok=false; } else setErr("c-name",false);
      if(!validEmail(val("c-email"))){ setErr("c-email",true); ok=false; } else setErr("c-email",false);
      if(!val("c-message")){ setErr("c-message",true); ok=false; } else setErr("c-message",false);
      if(!ok) return;

      var data = { name:val("c-name"), email:val("c-email"), company:val("c-company"),
                   service:val("c-service"), message:val("c-message") };
      var status = $("#formStatus");

      if(ENDPOINT){
        fetch(ENDPOINT, { method:"POST", headers:{"Content-Type":"application/json","Accept":"application/json"}, body:JSON.stringify(data) })
          .then(function(r){ if(r.ok){ form.reset(); status.textContent="Thanks — your enquiry is in. We'll be in touch shortly."; status.className="form-status ok"; }
                             else throw 0; })
          .catch(function(){ mailtoFallback(data, status); });
      } else { mailtoFallback(data, status); }
    });
    function mailtoFallback(d, status){
      var body = "Name: "+d.name+"\nEmail: "+d.email+"\nCompany: "+d.company+"\nService: "+d.service+"\n\n"+d.message;
      window.location.href = "mailto:projects@vizis.in?subject="+encodeURIComponent("Project enquiry — "+(d.service||"Vizis"))+"&body="+encodeURIComponent(body);
      status.textContent="Your email draft is ready — just press send in your mail app.";
      status.className="form-status ok";
    }
  }

  /* ---------- footer year ---------- */
  $$(".year").forEach(function(y){ y.textContent = new Date().getFullYear(); });
})();
