/* ============================================================
   ui.js — інтеракції: reveal-on-scroll, sticky CTA, topbar.
   Програма/FAQ — нативні <details> (доступно, нуль dead-click).
   ============================================================ */
(function () {
  "use strict";

  /* reveal-on-scroll (.reveal → .in-view) */
  var reveals = document.querySelectorAll(".reveal");
  if ("IntersectionObserver" in window && reveals.length) {
    var ro = new IntersectionObserver(function (entries) {
      entries.forEach(function (e) {
        if (e.isIntersecting) { e.target.classList.add("in-view"); ro.unobserve(e.target); }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    reveals.forEach(function (el) { ro.observe(el); });
  } else {
    reveals.forEach(function (el) { el.classList.add("in-view"); });
  }

  /* topbar — тінь після скролу */
  var topbar = document.getElementById("topbar");
  function onScrollTop() {
    if (!topbar) return;
    topbar.classList.toggle("is-scrolled", window.scrollY > 8);
  }
  onScrollTop();
  window.addEventListener("scroll", onScrollTop, { passive: true });

  /* sticky CTA (mobile): показуємо після hero, ховаємо біля форми */
  var sticky = document.getElementById("stickyCta");
  var hero = document.getElementById("hero");
  var leadForm = document.getElementById("lead-form");
  if (sticky && hero && "IntersectionObserver" in window) {
    var heroVisible = true, formVisible = false;
    function update() { sticky.hidden = (heroVisible || formVisible); }
    new IntersectionObserver(function (es) {
      es.forEach(function (e) { heroVisible = e.isIntersecting; });
      update();
    }, { threshold: 0.15 }).observe(hero);
    if (leadForm) {
      new IntersectionObserver(function (es) {
        es.forEach(function (e) { formVisible = e.isIntersecting; });
        update();
      }, { threshold: 0.2 }).observe(leadForm);
    }
    update();
  }

  /* prefers-reduced-motion */
  var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  /* hero-робот (прозорий):
     - reduce-motion → лишаємо статичний прозорий постер (нічого не граємо);
     - браузер не тягне VP9-alpha webm (Safari/iOS) → підміна на анімований APNG. */
  var robot = document.querySelector("[data-robot]");
  if (robot) {
    var video = robot.querySelector(".lead__video");
    var canWebm = !!(video && video.canPlayType &&
                     video.canPlayType('video/webm; codecs="vp9"') !== "");
    if (reduce) {
      if (video) { video.removeAttribute("autoplay"); video.autoplay = false;
        try { video.pause(); } catch (e) { /* noop */ } }
    } else if (!canWebm) {
      var apng = robot.getAttribute("data-apng");
      if (apng) {
        var img = new Image();
        img.className = "lead__video";
        img.width = 1280; img.height = 720;
        img.alt = "Анімований робот тримає логотип Meta";
        img.src = apng;                 // APNG тягнеться лише тут (Safari/iOS)
        robot.innerHTML = "";
        robot.appendChild(img);
      }
    }
  }

  /* count-up для статів (+9300 / +325 / +47) */
  function countUp(el) {
    var target = parseFloat(el.getAttribute("data-count"));
    var prefix = el.getAttribute("data-prefix") || "";
    if (isNaN(target)) return;
    if (reduce) { el.textContent = prefix + target; return; }
    var dur = 1400, start = null;
    function step(ts) {
      if (!start) start = ts;
      var p = Math.min((ts - start) / dur, 1);
      var eased = 1 - Math.pow(1 - p, 3);
      el.textContent = prefix + Math.round(target * eased);
      if (p < 1) requestAnimationFrame(step);
    }
    requestAnimationFrame(step);
  }
  var counters = document.querySelectorAll("[data-count]");
  if (counters.length && "IntersectionObserver" in window) {
    var co = new IntersectionObserver(function (es) {
      es.forEach(function (e) { if (e.isIntersecting) { countUp(e.target); co.unobserve(e.target); } });
    }, { threshold: 0.6 });
    counters.forEach(function (el) { co.observe(el); });
  } else {
    counters.forEach(function (el) {
      el.textContent = (el.getAttribute("data-prefix") || "") + el.getAttribute("data-count");
    });
  }

  /* stagger-поява гридів */
  var groups = document.querySelectorAll("[data-stagger]");
  if (groups.length && "IntersectionObserver" in window) {
    var so = new IntersectionObserver(function (es) {
      es.forEach(function (e) {
        if (!e.isIntersecting) return;
        var kids = e.target.children;
        for (var i = 0; i < kids.length; i++) {
          kids[i].style.setProperty("--d", (i * 70) + "ms");
        }
        e.target.classList.add("in-view");
        so.unobserve(e.target);
      });
    }, { threshold: 0.15 });
    groups.forEach(function (g) { so.observe(g); });
  } else {
    groups.forEach(function (g) { g.classList.add("in-view"); });
  }
})();
