/* ============================================================
   Motion — "Glassy Dashboard" animatsiyalari
   Bo'lim ochilganda: kartalar ketma-ket xiradan aniqqa chiqadi,
   barlar o'sadi, chiziqlar chiziladi, donut/halqalar to'ladi,
   katta raqamlar noldan sanab chiqadi.
   Web Animations API ishlatiladi — React holatiga tegmaydi
   (animatsiya tugagach element o'z asl ko'rinishida qoladi).
   ============================================================ */
(function () {
  const reduce = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const EASE = 'cubic-bezier(.23,1,.32,1)'; // kuchli ease-out — birinchi kadrdan javob beradi
  const CARD_SEL = '.dx-card, .dx-kpi, .dash-card, .io-mini, .dash-anim, .gx-card, .ocard, .gx-greet';
  const seen = new WeakSet();

  function inPanel(el) { return !!(el && el.closest && el.closest('.gx-page')); }

  // ---- Kartalar: xira shishadan aniq holatga, ketma-ket ----
  function animateCards(nodes, base) {
    let i = 0;
    nodes.forEach((el) => {
      if (seen.has(el)) return;
      seen.add(el);
      // Ichma-ich kartalar (karta ichidagi karta) — ota bilan birga chiqadi
      const parentCard = el.parentElement && el.parentElement.closest(CARD_SEL);
      if (parentCard && parentCard !== el && seen.has(parentCard)) return;
      const delay = Math.min(base + i * 45, base + 700);
      i++;
      el.animate([
        { opacity: 0, filter: 'blur(14px)', transform: 'translateY(10px) scale(.985)' },
        { opacity: 1, filter: 'blur(0px)', transform: 'none' },
      ], { duration: 520, delay, easing: EASE, fill: 'backwards' });
    });
    return i;
  }

  // ---- Gorizontal/vertikal barlar (div asosidagi) ----
  function animateBars(root, base) {
    root.querySelectorAll('div[style]').forEach((el, idx) => {
      if (seen.has(el)) return;
      const st = el.style;
      const horiz = st.width && st.width.endsWith('%') && st.height === '100%';
      const vert = st.height && st.height.endsWith('%') && st.width === '100%' && el.parentElement &&
        getComputedStyle(el.parentElement).justifyContent === 'flex-end';
      if (!horiz && !vert) return;
      if (parseFloat(horiz ? st.width : st.height) <= 0) return;
      seen.add(el);
      const delay = base + 180 + Math.min(idx, 30) * 18;
      el.animate(horiz
        ? [{ transform: 'scaleX(0)', transformOrigin: 'left center' }, { transform: 'scaleX(1)', transformOrigin: 'left center' }]
        : [{ transform: 'scaleY(0)', transformOrigin: 'center bottom' }, { transform: 'scaleY(1)', transformOrigin: 'center bottom' }],
        { duration: 900, delay, easing: EASE, fill: 'backwards' });
    });
  }

  // ---- SVG: chiziqlar chiziladi, donut/halqalar to'ladi ----
  function animateSvg(root, base) {
    root.querySelectorAll('svg path').forEach((p) => {
      if (seen.has(p)) return;
      seen.add(p);
      const fill = p.getAttribute('fill');
      const stroke = p.getAttribute('stroke');
      if (p.getAttribute('stroke-dasharray')) return; // grid/punktir chiziqlar
      if (stroke && (fill === 'none' || fill === 'transparent')) {
        let L = 0; try { L = p.getTotalLength(); } catch (_) {}
        if (!L || L < 20) return;
        p.animate([{ strokeDasharray: L + ' ' + L, strokeDashoffset: L }, { strokeDasharray: L + ' ' + L, strokeDashoffset: 0 }],
          { duration: 1300, delay: base + 250, easing: EASE, fill: 'backwards' });
      } else if (fill && fill.startsWith('url(')) {
        // Maydon (area) — chiziq bilan birga yumshoq paydo bo'ladi
        p.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 900, delay: base + 700, easing: EASE, fill: 'backwards' });
      }
    });
    root.querySelectorAll('svg circle[stroke-dasharray]').forEach((c, i) => {
      if (seen.has(c)) return;
      seen.add(c);
      const da = c.getAttribute('stroke-dasharray');
      const parts = String(da).split(/[\s,]+/).map(Number);
      if (parts.length < 2 || parts.some(isNaN)) return;
      const C = parts[0] + parts[1];
      c.animate([{ strokeDasharray: '0 ' + C }, { strokeDasharray: parts[0] + ' ' + parts[1] }],
        { duration: 1100, delay: base + 220 + i * 90, easing: EASE, fill: 'backwards' });
    });
  }

  // ---- Raqamlar noldan sanab chiqadi ----
  function countUp(root, base) {
    const nodes = root.querySelectorAll('.dx-kpi__v, .dash-hero-total, .gx-count, .tnum');
    nodes.forEach((el) => {
      if (seen.has(el)) return;
      seen.add(el);
      if (el.classList.contains('tnum') && parseFloat(getComputedStyle(el).fontSize) < 19) return;
      const tn = [...el.childNodes].find((n) => n.nodeType === 3 && /\d/.test(n.nodeValue));
      if (!tn) return;
      const orig = tn.nodeValue;
      const m = orig.match(/-?\d[\d\s  .,]*/);
      if (!m) return;
      const raw = m[0];
      const decSep = /[.,]\d{1,2}$/.test(raw.trim()) ? raw.trim().slice(-3).match(/[.,]/)[0] : null;
      const digits = decSep ? raw.trim().slice(0, raw.trim().lastIndexOf(decSep)).replace(/[^\d-]/g, '') + '.' + raw.trim().split(decSep).pop()
                            : raw.replace(/[^\d-]/g, '');
      const target = parseFloat(digits);
      if (!isFinite(target) || target === 0) return;
      const decimals = decSep ? raw.trim().split(decSep).pop().length : 0;
      const sepMatch = raw.match(/\d([\s  ,.])\d{3}/);
      const thou = sepMatch && sepMatch[1] !== decSep ? sepMatch[1] : '';
      const fmt = (v) => {
        const fixed = v.toFixed(decimals);
        let [ip, dp] = fixed.split('.');
        if (thou) ip = ip.replace(/\B(?=(\d{3})+(?!\d))/g, thou);
        return dp ? ip + decSep + dp : ip;
      };
      const start = performance.now() + base + 150;
      const dur = 1100;
      let last = orig;
      const tick = (now) => {
        if (tn.nodeValue !== last) return; // React yangiladi — to'xtaymiz
        const t = Math.max(0, Math.min(1, (now - start) / dur));
        const e = 1 - Math.pow(1 - t, 3);
        last = t >= 1 ? orig : orig.replace(raw, fmt(target * e) + (raw.match(/\s+$/) || [''])[0]);
        tn.nodeValue = last;
        if (t < 1) requestAnimationFrame(tick);
      };
      last = orig.replace(raw, fmt(0) + (raw.match(/\s+$/) || [''])[0]);
      tn.nodeValue = last;
      requestAnimationFrame(tick);
    });
  }

  function run(root, base) {
    if (reduce() || !root) return;
    const cards = [...root.querySelectorAll(CARD_SEL)].filter(inPanel);
    animateCards(cards, base);
    animateBars(root, base);
    animateSvg(root, base);
    countUp(root, base);
  }

  // Bo'lim sahifasi: ochilganda va keyingi 5 soniyada yuklangan kontentni jonlantiradi
  function mountPage(root) {
    if (!root) return () => {};
    run(root, 120);
    let timer = null;
    const mo = new MutationObserver(() => {
      clearTimeout(timer);
      timer = setTimeout(() => run(root, 0), 40);
    });
    mo.observe(root, { childList: true, subtree: true });
    const stop = setTimeout(() => mo.disconnect(), 5000);
    return () => { mo.disconnect(); clearTimeout(stop); clearTimeout(timer); };
  }

  window.GlassMotion = { mountPage };
})();

/* Bo'lim o'ramasi — har bo'lim almashganda qayta mount bo'ladi (key=view) */
function GlassPage({ children }) {
  const ref = useRef(null);
  useEffect(() => window.GlassMotion.mountPage(ref.current), []);
  return <div ref={ref} className="gx-page">{children}</div>;
}

/* AI qatoridagi matn — yozilib chiqadi (videodagi kabi) */
function Typewriter({ text, speed = 34, startDelay = 500 }) {
  const [n, setN] = useState(0);
  useEffect(() => {
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { setN(text.length); return; }
    let i = 0, id = null;
    const t0 = setTimeout(function step() {
      i++; setN(i);
      if (i < text.length) id = setTimeout(step, speed);
    }, startDelay);
    return () => { clearTimeout(t0); clearTimeout(id); };
  }, [text]);
  return <>{text.slice(0, n)}<span className="gx-caret" aria-hidden="true" /></>;
}

Object.assign(window, { GlassPage, Typewriter });
