/* ================= Scroll & interaction engine ================= */
const {useState:useS, useEffect:useE, useRef:useR} = React;

/* global scroll progress (top bar) */
function ScrollProgress(){
  const [p, setP] = useS(0);
  useE(()=>{
    let raf;
    const on = ()=>{ cancelAnimationFrame(raf); raf=requestAnimationFrame(()=>{
      const h = document.documentElement.scrollHeight - window.innerHeight;
      setP(h>0 ? Math.min(1, window.scrollY/h) : 0);
    });};
    on(); window.addEventListener("scroll", on, {passive:true}); window.addEventListener("resize", on);
    return ()=>{ window.removeEventListener("scroll", on); window.removeEventListener("resize", on); cancelAnimationFrame(raf); };
  },[]);
  return <div className="scroll-prog" style={{transform:`scaleX(${p})`}}></div>;
}

/* reveal-on-scroll: re-scans DOM, supports variant classes */
const useReveal = (dep) => {
  useE(()=>{
    const els = document.querySelectorAll(".reveal:not(.in)");
    const o = new IntersectionObserver((es)=>{
      es.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add("in"); o.unobserve(e.target);} });
    },{threshold:.08, rootMargin:"0px 0px -10% 0px"});
    els.forEach(el=>o.observe(el));
    return ()=>o.disconnect();
  });
};

/* count-up number when scrolled into view. Parses leading symbol + numeric + suffix */
function Counter({value, dur=1600}){
  const ref = useR(null);
  const [txt, setTxt] = useS(()=>value.replace(/[0-9]/g, "0"));
  useE(()=>{
    const m = value.match(/^([^\d]*)([\d.,]+)(.*)$/);
    if(!m){ setTxt(value); return; }
    const pre=m[1], numStr=m[2], suf=m[3];
    const isPct = numStr.includes(",") && !numStr.includes(".");
    const target = parseFloat(numStr.replace(/\./g,"").replace(",", "."));
    const hasThousand = numStr.includes(".") && !numStr.includes(",");
    let started=false, raf;
    const fmtN = (n)=>{
      if(hasThousand) return Math.round(n).toLocaleString("tr-TR");
      if(numStr.includes(",")) return n.toLocaleString("tr-TR",{minimumFractionDigits:0,maximumFractionDigits:0});
      return Math.round(n).toString();
    };
    const run = (t0)=>{
      const tick=(now)=>{ const k=Math.min(1,(now-t0)/dur); const e=1-Math.pow(1-k,3);
        setTxt(pre+fmtN(target*e)+suf); if(k<1) raf=requestAnimationFrame(tick); };
      raf=requestAnimationFrame(tick);
    };
    const o=new IntersectionObserver((es)=>{ if(es[0].isIntersecting && !started){ started=true; run(performance.now()); o.disconnect(); } },{threshold:.4});
    if(ref.current) o.observe(ref.current);
    return ()=>{ o.disconnect(); cancelAnimationFrame(raf); };
  },[value]);
  return <span ref={ref}>{txt}</span>;
}

/* parallax: translateY based on element's position in viewport. speed +down/-up */
function useParallax(speed=0.15){
  const ref=useR(null);
  useE(()=>{
    let raf;
    const on=()=>{ cancelAnimationFrame(raf); raf=requestAnimationFrame(()=>{
      const el=ref.current; if(!el) return;
      const r=el.getBoundingClientRect(); const c=r.top+r.height/2 - window.innerHeight/2;
      el.style.transform=`translate3d(0, ${(-c*speed).toFixed(1)}px, 0)`;
    });};
    on(); window.addEventListener("scroll", on, {passive:true}); window.addEventListener("resize", on);
    return ()=>{ window.removeEventListener("scroll", on); window.removeEventListener("resize", on); cancelAnimationFrame(raf); };
  },[speed]);
  return ref;
}

/* magnetic button: follows cursor slightly */
function Magnetic({children, strength=0.35, className, ...rest}){
  const ref=useR(null);
  const move=(e)=>{ const el=ref.current; if(!el) return; const r=el.getBoundingClientRect();
    const x=(e.clientX-(r.left+r.width/2))*strength; const y=(e.clientY-(r.top+r.height/2))*strength;
    el.style.transform=`translate(${x}px, ${y}px)`; };
  const leave=()=>{ if(ref.current) ref.current.style.transform="translate(0,0)"; };
  return <span ref={ref} className={className} style={{display:"inline-block",transition:"transform .25s cubic-bezier(.22,.61,.36,1)",willChange:"transform"}}
    onMouseMove={move} onMouseLeave={leave} {...rest}>{children}</span>;
}

/* spotlight card: radial glow follows cursor */
function Spotlight({children, className, style, ...rest}){
  const ref=useR(null);
  const move=(e)=>{ const el=ref.current; if(!el) return; const r=el.getBoundingClientRect();
    el.style.setProperty("--mx",(e.clientX-r.left)+"px"); el.style.setProperty("--my",(e.clientY-r.top)+"px"); };
  return <div ref={ref} className={"spotlight "+(className||"")} style={style} onMouseMove={move} {...rest}>{children}</div>;
}

/* infinite marquee */
function Marquee({items, speed=34}){
  return (
    <div className="marquee">
      <div className="marquee-track" style={{animationDuration:speed+"s"}}>
        {[...items,...items].map((t,i)=>(
          <span key={i} className="marquee-item">{t}</span>
        ))}
      </div>
    </div>
  );
}

/* mouse parallax layer (for hero). returns {ref, style getter via data attr} - simpler: hook returns handlers */
function useMouseParallax(){
  const ref=useR(null);
  useE(()=>{
    const el=ref.current; if(!el) return;
    let raf;
    const on=(e)=>{ cancelAnimationFrame(raf); raf=requestAnimationFrame(()=>{
      const r=el.getBoundingClientRect(); const px=(e.clientX-r.left)/r.width-0.5; const py=(e.clientY-r.top)/r.height-0.5;
      el.querySelectorAll("[data-depth]").forEach(n=>{ const d=parseFloat(n.dataset.depth);
        n.style.transform=`translate3d(${(-px*d*40).toFixed(1)}px, ${(-py*d*40).toFixed(1)}px, 0)`; });
    });};
    el.addEventListener("mousemove", on);
    return ()=>{ el.removeEventListener("mousemove", on); cancelAnimationFrame(raf); };
  },[]);
  return ref;
}

window.Scroll = {ScrollProgress, useReveal, Counter, useParallax, Magnetic, Spotlight, Marquee, useMouseParallax};
