/* VIZIS — interactions */
(function(){
  "use strict";
  const $  = (s,c=document)=>c.querySelector(s);
  const $$ = (s,c=document)=>Array.from(c.querySelectorAll(s));
  const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  /* ---- portfolio data (optimized webp) ---- */
  const COUNTS = { exterior:7, interior:7, landscape:5, plan:4, illustration:2 };
  const LABEL  = { exterior:"Exterior", interior:"Interior", landscape:"Landscape", plan:"Plan / Section", illustration:"Illustration" };
  const work = [];
  Object.keys(COUNTS).forEach(cat=>{
    for(let i=1;i<=COUNTS[cat];i++){
      work.push({ cat, label:LABEL[cat],
        thumb:`assets/img/work/${cat}-${i}-t.webp`,
        full:`assets/img/work/${cat}-${i}.webp` });
    }
  });

  /* ---- build gallery ---- */
  const grid = $("#grid");
  work.forEach((w,idx)=>{
    const el = document.createElement("button");
    el.className = "tile"; el.dataset.cat = w.cat; el.dataset.idx = idx;
    el.setAttribute("aria-label", `${w.label} render — open`);
    el.innerHTML =
      `<img loading="lazy" src="${w.thumb}" alt="${w.label} 3D render by Vizis">
       <span class="meta"><b>${String(idx+1).padStart(2,"0")}</b> · ${w.label}</span>`;
    grid.appendChild(el);
  });

  /* ---- filters ---- */
  let activeCat = "all";
  $$(".filters button").forEach(b=>{
    b.addEventListener("click",()=>{
      $$(".filters button").forEach(x=>x.classList.remove("on"));
      b.classList.add("on"); activeCat = b.dataset.f;
      $$(".tile").forEach(t=> t.classList.toggle("hide", activeCat!=="all" && t.dataset.cat!==activeCat));
    });
  });

  /* ---- lightbox ---- */
  const lb = $("#lb"), lbImg = $("#lbImg"), lbCap = $("#lbCap");
  let curList = [], curPos = 0;
  function visibleList(){
    return work.map((w,i)=>({...w,i})).filter(w=> activeCat==="all"||w.cat===activeCat);
  }
  function openLb(idx){
    curList = visibleList();
    curPos = curList.findIndex(w=>w.i===idx);
    if(curPos<0) curPos=0;
    show(); lb.classList.add("open"); document.body.style.overflow="hidden";
  }
  function show(){
    const w = curList[curPos];
    lbImg.src = w.full; lbImg.alt = `${w.label} 3D render by Vizis`;
    lbCap.textContent = `${w.label} — ${String(w.i+1).padStart(2,"0")} / ${work.length}`;
  }
  function closeLb(){ lb.classList.remove("open"); document.body.style.overflow=""; }
  function step(d){ curPos=(curPos+d+curList.length)%curList.length; show(); }
  grid.addEventListener("click",e=>{ const t=e.target.closest(".tile"); if(t) openLb(+t.dataset.idx); });
  $("#lbClose").addEventListener("click",closeLb);
  $("#lbPrev").addEventListener("click",()=>step(-1));
  $("#lbNext").addEventListener("click",()=>step(1));
  lb.addEventListener("click",e=>{ if(e.target===lb) closeLb(); });
  document.addEventListener("keydown",e=>{
    if(!lb.classList.contains("open")) return;
    if(e.key==="Escape") closeLb();
    if(e.key==="ArrowLeft") step(-1);
    if(e.key==="ArrowRight") step(1);
  });

  /* ---- nav solidify + mobile ---- */
  const nav = $("#nav");
  const onScroll = ()=> nav.classList.toggle("solid", window.scrollY>40);
  onScroll(); window.addEventListener("scroll",onScroll,{passive:true});
  $("#navToggle").addEventListener("click",()=> $("#navLinks").classList.toggle("show"));
  $$("#navLinks a").forEach(a=>a.addEventListener("click",()=>$("#navLinks").classList.remove("show")));

  /* ---- hero crossfade ---- */
  const slides = $$(".hero-bg .slide");
  if(slides.length>1 && !reduce){
    let h=0; setInterval(()=>{
      slides[h].classList.remove("on"); h=(h+1)%slides.length; slides[h].classList.add("on");
    }, 5200);
  }

  /* ---- scroll reveals ---- */
  if("IntersectionObserver" in window && !reduce){
    const io = new IntersectionObserver((es)=>es.forEach(e=>{
      if(e.isIntersecting){ e.target.classList.add("in"); io.unobserve(e.target); }
    }), {threshold:.12, rootMargin:"0px 0px -8% 0px"});
    $$("[data-reveal]").forEach(el=>io.observe(el));
  } else { $$("[data-reveal]").forEach(el=>el.classList.add("in")); }

  /* ---- comparator (signature) ---- */
  const cmp = $("#cmp");
  if(cmp){
    const after = $(".after",cmp), handle=$(".handle",cmp), knob=$(".knob",cmp);
    let drag=false;
    const set = (pct)=>{ pct=Math.max(2,Math.min(98,pct));
      after.style.clipPath=`inset(0 0 0 ${pct}%)`; handle.style.left=pct+"%"; knob.style.left=pct+"%"; };
    const pos = (e)=>{ const r=cmp.getBoundingClientRect();
      const x=(e.touches?e.touches[0].clientX:e.clientX)-r.left; return x/r.width*100; };
    const start=(e)=>{ drag=true; set(pos(e)); };
    const move =(e)=>{ if(drag){ set(pos(e)); } };
    const end  =()=> drag=false;
    cmp.addEventListener("mousedown",start); window.addEventListener("mousemove",move); window.addEventListener("mouseup",end);
    cmp.addEventListener("touchstart",start,{passive:true}); cmp.addEventListener("touchmove",move,{passive:true}); cmp.addEventListener("touchend",end);
    set(50);
  }

  /* ---- contact form -> mailto (no backend needed) ---- */
  const form = $("#quoteForm");
  if(form){
    form.addEventListener("submit",e=>{
      e.preventDefault();
      const f = id=> (form.querySelector("#"+id)||{}).value || "";
      const body =
`Name: ${f("cf-name")}
Email: ${f("cf-email")}
Service: ${f("cf-service")}

${f("cf-msg")}`;
      const subj = encodeURIComponent(`Project enquiry — ${f("cf-service")||"Vizis"}`);
      window.location.href = `mailto:projects@vizis.in?subject=${subj}&body=${encodeURIComponent(body)}`;
      $("#cf-done").style.display="block";
    });
  }

  /* footer year */
  const y=$("#year"); if(y) y.textContent=new Date().getFullYear();
})();
