// Year
document.getElementById("year").textContent = String(new Date().getFullYear());

// Mobile menu
const menuBtn = document.getElementById("menuBtn");
const mobileMenu = document.getElementById("mobileMenu");

menuBtn?.addEventListener("click", () => {
  const expanded = menuBtn.getAttribute("aria-expanded") === "true";
  menuBtn.setAttribute("aria-expanded", String(!expanded));
  mobileMenu.style.display = expanded ? "none" : "flex";
  mobileMenu.setAttribute("aria-hidden", String(expanded));
});

// Feature screenshots mini switch
const bigPhoneImg = document.querySelector(".splitVisual .phoneFrame.big img");
document.querySelectorAll(".miniBtn").forEach((btn) => {
  btn.addEventListener("click", () => {
    document.querySelectorAll(".miniBtn").forEach(b => b.classList.remove("is-active"));
    btn.classList.add("is-active");
    const shot = btn.getAttribute("data-shot");
    if (bigPhoneImg && shot) bigPhoneImg.src = shot;
  });
});

// FAQ accordion
const faqItems = document.querySelectorAll(".faqItem");
faqItems.forEach((item) => {
  item.addEventListener("click", () => {
    const panel = item.nextElementSibling;
    const icon = item.querySelector(".icon");
    const isOpen = item.classList.contains("is-open");

    // close all
    faqItems.forEach((it) => {
      it.classList.remove("is-open");
      const p = it.nextElementSibling;
      const ic = it.querySelector(".icon");
      p?.classList.remove("open");
      if (ic) ic.textContent = "+";
    });

    // open current
    if (!isOpen) {
      item.classList.add("is-open");
      panel?.classList.add("open");
      if (icon) icon.textContent = "−";
    }
  });
});

// Scroll reveal: IntersectionObserver
(function initScrollReveal() {
  const els = document.querySelectorAll('.reveal');
  if (!('IntersectionObserver' in window) || els.length === 0) {
    els.forEach(el => el.classList.add('is-in'));
    return;
  }

  const io = new IntersectionObserver(
    (entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('is-in');
          io.unobserve(e.target); // 只播一次，避免一直閃
        }
      });
    },
    { threshold: 0.12, rootMargin: '0px 0px -10% 0px' }
  );

  els.forEach(el => io.observe(el));
})();

(function initScrollRevealStagger() {
  const prefersReduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const items = document.querySelectorAll(".reveal");

  if (prefersReduce) {
    items.forEach(el => el.classList.add("is-in"));
    return;
  }

  // ✅ 找出需要「逐張浮出」的容器
  // 你可以依需求增加 selector
  const staggerGroups = document.querySelectorAll(
    "[data-stagger], .blog-cards, .features-grid, .testimonials-grid"
  );

  staggerGroups.forEach(group => {
    const children = group.querySelectorAll(".reveal");
    children.forEach((el, idx) => {
      // 每張卡延遲 80ms（你可調整）
      el.style.setProperty("--d", `${idx * 80}ms`);
      el.classList.add("stagger");
    });
  });

  if (!("IntersectionObserver" in window)) {
    items.forEach(el => el.classList.add("is-in"));
    return;
  }

  const io = new IntersectionObserver(
    entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          io.unobserve(e.target);
        }
      });
    },
    { threshold: 0.12, rootMargin: "0px 0px -10% 0px" }
  );

  items.forEach(el => io.observe(el));
})();


// =============================
// TDEE / BMI mini calculator
// =============================
(() => {
  const tabs = Array.from(document.querySelectorAll(".tdee-tab"));
  const btn = document.getElementById("tdeeCalcBtn");
  const hEl = document.getElementById("tdeeHeight");
  const wEl = document.getElementById("tdeeWeight");

  const result = document.getElementById("tdeeResult");
  const bmiOut = document.getElementById("tdeeBMI");
  const calOut = document.getElementById("tdeeCalories");
  const goalCopy = document.getElementById("tdeeGoalCopy");

  if (!tabs.length || !btn || !hEl || !wEl || !result) return;

  let goal = "cut"; // cut | maintain | bulk

  function setGoal(next) {
    goal = next;
    tabs.forEach((t) => {
      const active = t.dataset.goal === next;
      t.classList.toggle("is-active", active);
      t.setAttribute("aria-selected", active ? "true" : "false");
    });
  }

  tabs.forEach((t) => {
    t.addEventListener("click", () => setGoal(t.dataset.goal));
  });

  function clamp(n, min, max) {
    return Math.max(min, Math.min(max, n));
  }

  function calc() {
    const heightCm = Number(hEl.value);
    const weightKg = Number(wEl.value);

    if (!heightCm || !weightKg) return;

    const heightM = heightCm / 100;
    const bmi = weightKg / (heightM * heightM);

    // 簡化版：用體重推估 TDEE（保守且不宣稱精準）
    // maintain base: 30 * weight
    // cut: -15% | bulk: +10%
    const base = 30 * weightKg;
    let calories = base;

    if (goal === "cut") calories = base * 0.85;
    if (goal === "bulk") calories = base * 1.10;

    calories = Math.round(clamp(calories, 1200, 3500));

    bmiOut.textContent = bmi.toFixed(1);
    calOut.textContent = `${calories} kcal`;

    if (goal === "cut") goalCopy.textContent = "減脂建議：先做到可持續的熱量赤字，再慢慢微調。";
    if (goal === "maintain") goalCopy.textContent = "維持建議：用穩定熱量與蛋白質，讓體態更好掌控。";
    if (goal === "bulk") goalCopy.textContent = "增肌建議：溫和盈餘 + 規律訓練，成果更乾淨。";

    result.hidden = false;

    // 若你有「reveal」觀察器，讓結果也吃動畫
    result.classList.add("reveal", "pop", "is-in");
  }

  btn.addEventListener("click", calc);
})();
