/* pfe — interações de interface (jQuery) */
(function ($) {
  "use strict";

  $(function () {
    var $header = $(".site-header");
    var $nav = $(".nav");

    // Sombra do header ao fazer scroll
    function onScroll() {
      $header.toggleClass("is-stuck", $(window).scrollTop() > 8);
    }
    $(window).on("scroll", onScroll);
    onScroll();

    // Menu mobile
    $(".nav__toggle").on("click", function () {
      $nav.toggleClass("is-open");
      $(this).attr("aria-expanded", $nav.hasClass("is-open"));
    });
    $(document).on("click", function (e) {
      if (!$(e.target).closest(".nav").length) $nav.removeClass("is-open");
    });
    $(".nav__links a").on("click", function () {
      $nav.removeClass("is-open");
    });

    // Reveal on scroll
    if ("IntersectionObserver" in window) {
      var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            entry.target.classList.add("in");
            io.unobserve(entry.target);
          }
        });
      }, { threshold: 0.12, rootMargin: "0px 0px -40px 0px" });
      $(".reveal").each(function () { io.observe(this); });
    } else {
      $(".reveal").addClass("in");
    }

    // Contadores nas estatísticas do hero
    function animateCount($el) {
      var target = parseInt($el.data("count"), 10);
      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.text(Math.floor(eased * target));
        if (p < 1) requestAnimationFrame(step);
        else $el.text(target);
      }
      requestAnimationFrame(step);
    }
    var counted = false;
    var $stats = $("[data-count]");
    if ($stats.length) {
      var statObs = new IntersectionObserver(function (entries) {
        entries.forEach(function (e) {
          if (e.isIntersecting && !counted) {
            counted = true;
            $stats.each(function () { animateCount($(this)); });
          }
        });
      }, { threshold: 0.4 });
      statObs.observe($stats.first().closest(".hero__panel, .stats-band")[0] || $stats[0]);
    }

    // Validação simples + feedback do formulário de contacto (sem backend)
    $("#contact-form").on("submit", function (e) {
      e.preventDefault();
      var ok = true;
      $(this).find("[required]").each(function () {
        if (!$.trim($(this).val())) {
          ok = false;
          $(this).css("border-color", "#d96d00");
        } else {
          $(this).css("border-color", "");
        }
      });
      if (ok) {
        $(".form__ok").addClass("show");
        this.reset();
        $("html, body").animate({ scrollTop: $(".form").offset().top - 120 }, 400);
      }
    });

    // Ano dinâmico no rodapé
    $(".js-year").text(new Date().getFullYear());
  });
})(jQuery);
