import "@fontsource-variable/inter";
import "@fontsource/jetbrains-mono/400.css";
import "@fontsource/jetbrains-mono/500.css";
import "@fontsource/jetbrains-mono/600.css";
import "./styles.css";

console.log("%cCreated by Sarthak", "font-size:14px;font-weight:700;color:#F2A83B;");

(function(){
  var reduced = matchMedia("(prefers-reduced-motion: reduce)").matches;
  var finePointer = matchMedia("(pointer: fine)").matches;

  /* ---------- scrollbar materialises only while scrolling ---------- */
  (function(){
    var to = null;
    addEventListener("scroll", function(){
      document.documentElement.classList.add("scrolling");
      clearTimeout(to);
      to = setTimeout(function(){ document.documentElement.classList.remove("scrolling"); }, 900);
    }, { passive: true, capture: true });
  })();

  /* ---------- mobile scroll progress bar ---------- */
  (function(){
    var bar = document.getElementById("mprogBar");
    if(!bar) return;
    var raf = null;
    function upd(){
      raf = null;
      var doc = document.scrollingElement || document.documentElement;
      var max = Math.max(1, doc.scrollHeight - innerHeight);
      bar.style.transform = "scaleX(" + Math.min(1, window.scrollY / max).toFixed(4) + ")";
    }
    addEventListener("scroll", function(){ if(raf == null) raf = requestAnimationFrame(upd); }, { passive: true });
    upd();
  })();

  /* ---------- mobile nav ---------- */
  (function(){
    var mb = document.getElementById("menuBtn");
    if(!mb) return;
    mb.addEventListener("click", function(){
      var open = document.body.classList.toggle("nav-open");
      mb.setAttribute("aria-expanded", open ? "true" : "false");
    });
    [].slice.call(document.querySelectorAll(".nav-links a")).forEach(function(a){
      a.addEventListener("click", function(){
        document.body.classList.remove("nav-open");
        mb.setAttribute("aria-expanded", "false");
      });
    });
  })();

  /* ---------- footer: hail alerts by ZIP ---------- */
  (function(){
    var form = document.getElementById("zipForm");
    if(!form) return;
    var zin = document.getElementById("zipInput");
    form.addEventListener("submit", function(e){
      e.preventDefault();
      var v = zin.value.trim();
      if(!/^\d{5}$/.test(v)){ zin.focus(); zin.select(); return; }
      form.innerHTML = "<div class='fa-done'><span class='tag'>&#9873; WATCHING " + v + "</span>" +
        "<span>First alert lands after the next radar-verified swath. No spam, only storms.</span></div>";
    });
  })();

  /* ---------- station rail: generic, built from any [data-rail] section on the page ---------- */
  (function(){
    var rail = document.getElementById("rail"), track = document.getElementById("railTrack");
    if(!rail || !track) return;
    var car = document.getElementById("railCar"), read = document.getElementById("railRead");
    var secs = [].slice.call(document.querySelectorAll("[data-rail]")).map(function(el){
      return { el: el, label: el.getAttribute("data-rail") };
    });
    if(!secs.length) return;
    var nodes = secs.map(function(s){
      var b = document.createElement("button");
      b.className = "rail-node"; b.type = "button"; b.title = s.label;
      b.setAttribute("aria-label", s.label);
      b.addEventListener("click", function(){
        scrollTo({top:s.el.offsetTop - 52, behavior:reduced ? "auto" : "smooth"});
      });
      track.appendChild(b);
      return b;
    });
    var tops = [], maxScroll = 1;
    function layout(){
      var doc = document.scrollingElement || document.documentElement;
      maxScroll = Math.max(1, doc.scrollHeight - innerHeight);
      tops = secs.map(function(s){ return Math.max(0, Math.min(s.el.offsetTop - 52, maxScroll)); });
      tops.forEach(function(tp, i){ nodes[i].style.top = (tp / maxScroll * 100) + "%"; });
    }
    var carP = 0, target = 0, actLabel = "", raf = null, lastT = 0;
    function frame(now){
      var rawDt = lastT ? now - lastT : 16;
      var dt = Math.min(rawDt, 50);
      lastT = now;
      var k = rawDt > 400 ? 1 : 1 - Math.exp(-dt / 110);
      carP += (target - carP) * k;
      if(Math.abs(target - carP) < .0005) carP = target;
      car.style.top = (carP * 100) + "%";
      read.textContent = actLabel + " · " + Math.round(carP * 100) + "%";
      if(carP === target){ raf = null; lastT = 0; return; }
      raf = requestAnimationFrame(frame);
    }
    function upd(){
      var doc = document.scrollingElement || document.documentElement;
      if(Math.abs(doc.scrollHeight - innerHeight - maxScroll) > 2) layout();
      var y = window.scrollY;
      target = Math.max(0, Math.min(1, y / maxScroll));
      var act = 0;
      tops.forEach(function(tp, i){ if(y >= tp - innerHeight * .35) act = i; });
      if(maxScroll - y < 4) act = secs.length - 1;
      nodes.forEach(function(n, i){ n.classList.toggle("on", i === act); });
      actLabel = secs[act].label;
      if(raf == null){ lastT = 0; raf = requestAnimationFrame(frame); }
    }
    addEventListener("scroll", upd, {passive:true});
    addEventListener("resize", function(){ layout(); upd(); });
    addEventListener("load", function(){ layout(); upd(); });
    layout(); upd();
  })();

  /* ---------- scroll reveals: 150ms, 60ms stagger ---------- */
  var revealEls = [].slice.call(document.querySelectorAll(".reveal"));
  if(!reduced && "IntersectionObserver" in window){
    var groups = new Map();
    var io = new IntersectionObserver(function(entries){
      entries.forEach(function(e){
        if(!e.isIntersecting && e.boundingClientRect.top >= 0) return;
        io.unobserve(e.target);
        var parent = e.target.parentElement;
        var idx = groups.get(parent) || 0;
        groups.set(parent, idx + 1);
        setTimeout(function(){ e.target.classList.add("in"); }, idx * 60);
        setTimeout(function(){ groups.set(parent, Math.max(0,(groups.get(parent)||1)-1)); }, 400);
      });
    }, {threshold:.15});
    revealEls.forEach(function(el){ io.observe(el); });
  } else {
    revealEls.forEach(function(el){ el.classList.add("in"); });
  }

  /* ---------- card tilt physics (spring, with glare tracking) ---------- */
  if(finePointer && !reduced){
    [].slice.call(document.querySelectorAll(".risk-card,.founder-card,.feat,.terms-card")).forEach(function(el){
      var rx=0,ry=0,tx=0,ty=0,vx=0,vy=0,raf=null,over=false;
      function frame(){
        vx+=(tx-rx)*.16; vy+=(ty-ry)*.16; vx*=.72; vy*=.72;
        rx+=vx; ry+=vy;
        if(!over && Math.abs(rx)<.02 && Math.abs(ry)<.02 && Math.abs(vx)<.02 && Math.abs(vy)<.02){
          el.style.transform=""; raf=null; return;
        }
        el.style.transform="perspective(900px) rotateX("+rx.toFixed(2)+"deg) rotateY("+ry.toFixed(2)+"deg) translateY(-2px)";
        raf=requestAnimationFrame(frame);
      }
      el.addEventListener("pointerenter",function(){
        over=true; el.classList.add("tilting");
        if(!raf) raf=requestAnimationFrame(frame);
      });
      el.addEventListener("pointermove",function(e){
        var r=el.getBoundingClientRect();
        var px=(e.clientX-r.left)/r.width, py=(e.clientY-r.top)/r.height;
        ty=(px-.5)*5; tx=(.5-py)*5;
        el.style.setProperty("--gx",(px*100)+"%");
        el.style.setProperty("--gy",(py*100)+"%");
      });
      el.addEventListener("pointerleave",function(){ over=false; tx=0; ty=0; });
    });
  }
})();
