(() => {
  const overlay = document.querySelector(".overlay");

  const toggleSet = [
    {
      trigger: document.querySelector(".menu-btn"),
      target: document.querySelector(".header-nav"),
      close: document.querySelector(".close-btn"),
    },
    {
      trigger: document.querySelector(".search-btn"),
      target: document.querySelector(".header-form"),
      close: document.querySelector(".close-search"),
      focus: () => {
        const input = document.querySelector(
          ".header-form input[type='search']",
        );
        input?.focus();
      },
    },
  ];

  toggleSet.forEach(({ trigger, target, close, focus }) => {
    const open = () => {
      target?.classList.add("active");
      overlay?.classList.add("active");
      focus?.();
    };

    const closeAll = () => {
      target?.classList.remove("active");
      overlay?.classList.remove("active");
    };

    trigger?.addEventListener("click", open);
    close?.addEventListener("click", closeAll);
    overlay?.addEventListener("click", closeAll);
  });

  // === Server Button Active Toggle ===
  document.querySelectorAll(".server-btn").forEach((btn) => {
    btn.addEventListener("click", () => {
      document
        .querySelectorAll(".server-btn.active")
        .forEach((el) => el.classList.remove("active"));
      btn.classList.add("active");
    });
  });

  const rmContent = document.querySelector(".readmore-content");
  const toggleBtn = document.querySelector(".readmore-toggle");

  if (rmContent && toggleBtn) {
    toggleBtn.addEventListener("click", function () {
      rmContent.classList.toggle("expanded");
      const expanded = rmContent.classList.contains("expanded");
      rmContent.setAttribute("aria-expanded", expanded);
      toggleBtn.textContent = expanded ? "Less" : "More";
    });
  }

  document.querySelectorAll(".seo-expand-block").forEach((block) => {
    const btn = block.querySelector(".seo-toggle-btn");
    btn.addEventListener("click", () => {
      const expanded = block.getAttribute("aria-expanded") === "true";
      block.setAttribute("aria-expanded", !expanded);
    });
  });

  const btn = document.querySelector(".scroll-to-top");

  if (!btn) return;

  window.addEventListener("scroll", () => {
    if (window.scrollY > 300) {
      btn.classList.add("active");
    } else {
      btn.classList.remove("active");
    }
  });

  btn.addEventListener("click", () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  });

  const shareBtn = document.getElementById("shareBtn");

  if (!shareBtn) return;

  shareBtn.addEventListener("click", async () => {
    const shareData = {
      title: document.title,
      text: "Xem bài viết này!",
      url: window.location.href,
    };

    if (navigator.share) {
      try {
        await navigator.share(shareData);
        console.log("Chia sẻ thành công!");
      } catch (err) {
        console.warn("Người dùng hủy chia sẻ hoặc lỗi:", err);
      }
    } else {
      // Fallback: hiển thị popup share custom
      document.body.classList.toggle("show-share-popup");
    }
  });


  // ESC để đóng nhanh
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      document.querySelectorAll(".mega-menu.open").forEach((m) => {
        m.classList.remove("open");
        const btn = m.closest(".menu-item")?.querySelector(".submenu-toggle");
        if (btn) btn.setAttribute("aria-expanded", "false");
      });
    }
  });
})();

document.addEventListener("DOMContentLoaded", () => {
  const slider = document.querySelector(".video-list");
  const prevBtn = document.querySelector(".prev-btn");
  const nextBtn = document.querySelector(".next-btn");

  const scrollAmount = 300;

  prevBtn.addEventListener("click", () => {
    slider.scrollBy({
      left: -scrollAmount,
      behavior: "smooth",
    });
  });
  nextBtn.addEventListener("click", () => {
    slider.scrollBy({
      left: scrollAmount,
      behavior: "smooth",
    });
  });
});

(() => {
  const lazyImgs = document.querySelectorAll(".lazy-img");

  const observer = new IntersectionObserver(
    (entries, obs) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target;
          const src = img.getAttribute("data-src");
          if (src) {
            img.src = src;
            img.onload = () => img.classList.add("loaded");
            img.removeAttribute("data-src");
          }
          obs.unobserve(img);
        }
      });
    },
    {
      rootMargin: "100px",
      threshold: 0.1,
    },
  );

  lazyImgs.forEach((img) => observer.observe(img));
})();

(() => {
  const slider = document.querySelector(".tag-slider");
  const prevBtn = document.querySelector(".tag-nav.prev");
  const nextBtn = document.querySelector(".tag-nav.next");

  prevBtn?.addEventListener("click", () => {
    slider.scrollBy({ left: -200, behavior: "smooth" });
  });

  nextBtn?.addEventListener("click", () => {
    slider.scrollBy({ left: 200, behavior: "smooth" });
  });
})();
