/* V6.18 — stable sticky toolbar and pointer-safe card spotlight/tilt. */
(()=>{
  'use strict';
  const toolbar=document.getElementById('projectToolbar');
  const header=document.getElementById('siteHeader');
  const cards=()=>Array.from(document.querySelectorAll('.project-card'));
  const fine=matchMedia('(hover:hover) and (pointer:fine)').matches;
  const reduced=matchMedia('(prefers-reduced-motion:reduce)').matches;
  let toolbarTop=0;

  const updateToolbarOffset=()=>{
    const mobile=innerWidth<=720;
    const fallback=mobile?66:(innerWidth<=980?72:84);
    const h=header?Math.ceil(header.getBoundingClientRect().height+20):fallback;
    document.documentElement.style.setProperty('--neo-toolbar-top',`${Math.max(fallback,h)}px`);
    if(toolbar) toolbarTop=toolbar.getBoundingClientRect().top+scrollY;
  };
  const updateStickyState=()=>{
    if(!toolbar)return;
    const configured=parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--neo-toolbar-top'))||84;
    toolbar.classList.toggle('is-stuck',toolbar.getBoundingClientRect().top<=configured+2 && scrollY>toolbarTop-configured-4);
  };

  const attachCard=(card)=>{
    if(card.dataset.neoV618==='1')return;
    card.dataset.neoV618='1';
    if(!fine||reduced)return;
    card.addEventListener('pointermove',event=>{
      const rect=card.getBoundingClientRect();
      const x=Math.min(1,Math.max(0,(event.clientX-rect.left)/rect.width));
      const y=Math.min(1,Math.max(0,(event.clientY-rect.top)/rect.height));
      card.style.setProperty('--spot-x',`${x*100}%`);
      card.style.setProperty('--spot-y',`${y*100}%`);
      card.style.transform=`translateY(-7px) rotateX(${(y-.5)*-6}deg) rotateY(${(x-.5)*6}deg)`;
    },{passive:true});
    card.addEventListener('pointerleave',()=>{card.style.transform='';},{passive:true});
  };
  const attachAll=()=>cards().forEach(attachCard);

  addEventListener('resize',()=>{updateToolbarOffset();updateStickyState();},{passive:true});
  addEventListener('orientationchange',()=>setTimeout(updateToolbarOffset,120),{passive:true});
  addEventListener('scroll',updateStickyState,{passive:true});
  if(header&&'ResizeObserver'in window)new ResizeObserver(updateToolbarOffset).observe(header);
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{updateToolbarOffset();attachAll();updateStickyState();},{once:true});
  else{updateToolbarOffset();attachAll();updateStickyState();}
  new MutationObserver(attachAll).observe(document.getElementById('projectGrid')||document.body,{childList:true,subtree:true});
})();
