// Landing behavior (pricing + demo form)
(async function () {

  // Mobile menu toggle
  const toggle = document.querySelector(".nav-toggle");
  const mobile = document.querySelector(".mobile");
  if (toggle && mobile) {
    toggle.addEventListener("click", () => {
      const expanded = toggle.getAttribute("aria-expanded") === "true";
      toggle.setAttribute("aria-expanded", String(!expanded));
      mobile.hidden = expanded;
      toggle.textContent = expanded ? "☰" : "✕";
    });
    mobile.querySelectorAll("a").forEach((a) =>
      a.addEventListener("click", () => {
        mobile.hidden = true;
        toggle.setAttribute("aria-expanded", "false");
        toggle.textContent = "☰";
      })
    );
  }

  const pricingGrid = document.getElementById("pricingGrid");
  let billing = "monthly";

  const formatPrice = (p) => (p === null || p === undefined ? "TBD" : `$${p}`);

  async function loadPricing() {
    const res = await fetch("pricing.json", { cache: "no-store" });
    return res.json();
  }

  function renderPricing(data) {
    if (!pricingGrid) return;
    pricingGrid.innerHTML = "";
    data.plans.forEach((plan) => {
      const priceObj = plan[billing] || {};
      const price = formatPrice(priceObj.price);
      const unit = priceObj.unit || "";
      const el = document.createElement("div");
      el.className = "plan" + (plan.highlight ? " highlight" : "");
      el.innerHTML = `
        <div class="plan-name">${plan.name}</div>
        <div class="plan-tag">${plan.tag || ""}</div>
        <div class="plan-price">${price}<span style="font-size:14px;font-weight:950;opacity:.75"> ${price === "TBD" ? "" : unit}</span></div>
        <ul>${(plan.features || []).map((f) => `<li>${f}</li>`).join("")}</ul>
        <a class="btn ${plan.highlight ? "btn-primary" : "btn-secondary"}" href="${plan.cta?.href || "#waitlist"}">${plan.cta?.label || "Join waitlist"}</a>
      `;
      pricingGrid.appendChild(el);
    });
  }

  const data = await loadPricing();
  billing = data.billingDefault || "monthly";
  document.querySelectorAll(".toggle-btn").forEach((btn) => {
    const b = btn.dataset.billing;
    btn.classList.toggle("is-active", b === billing);
    btn.addEventListener("click", () => {
      billing = b;
      document.querySelectorAll(".toggle-btn").forEach((x) => x.classList.remove("is-active"));
      btn.classList.add("is-active");
      renderPricing(data);
    });
  });
  renderPricing(data);

  // Waitlist form demo (replace with Formspree/Mailchimp)
  const form = document.getElementById("waitlistForm");
  const status = document.getElementById("formStatus");
  if (form && status) {
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      status.textContent = "Thanks — you’re on the list (demo). Hook this form to your provider to store submissions.";
      form.reset();
    });
  }
})();
