/* ============================================================
   AFTERWAVE DASHBOARD — UTILITIES  (window.AU)
   ============================================================ */
(function () {
  "use strict";
  const { useState, useRef, useLayoutEffect } = React;
  const RAMP = ["#eceadf", "#dcd8c9", "#c2bca9", "#9d9883", "#74705f", "#4a473d", "#232019"];
  function lerpHex(a, b, t) {
    const p = (h, i) => parseInt(h.slice(1 + i * 2, 3 + i * 2), 16);
    const c = [0, 1, 2].map((i) => Math.round(p(a, i) + (p(b, i) - p(a, i)) * t));
    return "#" + c.map((x) => x.toString(16).padStart(2, "0")).join("");
  }
  function gray(v) {
    v = Math.max(0, Math.min(1, v || 0));
    const i = v * (RAMP.length - 1), lo = Math.floor(i), hi = Math.ceil(i);
    return lerpHex(RAMP[lo], RAMP[hi], i - lo);
  }
  const inkOn = (v) => v > 0.52 ? "#f4f1ea" : "#232019";
  const clamp = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
  const lerp = (a, b, t) => a + (b - a) * t;

  let tipEl = null;
  function tipNode() { if (!tipEl) { tipEl = document.createElement("div"); tipEl.className = "tip"; tipEl.style.display = "none"; document.body.appendChild(tipEl); } return tipEl; }
  function showTip(html, x, y) {
    const t = tipNode(); t.innerHTML = html; t.style.display = "block";
    const r = t.getBoundingClientRect();
    let nx = x + 14, ny = y + 14;
    if (nx + r.width > innerWidth - 8) nx = x - r.width - 14;
    if (ny + r.height > innerHeight - 8) ny = y - r.height - 14;
    t.style.left = nx + "px"; t.style.top = ny + "px";
  }
  const hideTip = () => { if (tipEl) tipEl.style.display = "none"; };
  const T = (e, html) => showTip(html, e.clientX, e.clientY);

  function useSize() {
    const ref = useRef(null);
    const [s, set] = useState({ w: 0, h: 0 });
    useLayoutEffect(() => {
      if (!ref.current) return;
      const m = () => { const r = ref.current.getBoundingClientRect(); set({ w: Math.round(r.width), h: Math.round(r.height) }); };
      m(); const ro = new ResizeObserver(m); ro.observe(ref.current); return () => ro.disconnect();
    }, []);
    return [ref, s];
  }

  window.AU = { RAMP, gray, inkOn, lerpHex, clamp, lerp, showTip, hideTip, T, useSize };
})();
