/* =========================================================
   Doctor B Natural — interactions
   ========================================================= */
(function () {
  "use strict";

  var doc = document;
  var prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  /* ---------- footer year ---------- */
  var yearEl = doc.getElementById("year");
  if (yearEl) yearEl.textContent = new Date().getFullYear();

  /* ---------- sticky header state ---------- */
  var header = doc.getElementById("header");
  var onScroll = function () {
    if (window.scrollY > 24) header.classList.add("scrolled");
    else header.classList.remove("scrolled");
  };
  onScroll();
  window.addEventListener("scroll", onScroll, { passive: true });

  /* ---------- mobile menu ---------- */
  var hamburger = doc.getElementById("hamburger");
  var nav = doc.getElementById("nav");
  var backdrop = doc.createElement("div");
  backdrop.className = "nav-backdrop";
  doc.body.appendChild(backdrop);

  function navFocusables() {
    return Array.prototype.slice.call(nav.querySelectorAll('a[href], button:not([disabled])'));
  }

  function setMenu(open, returnFocus) {
    nav.classList.toggle("open", open);
    backdrop.classList.toggle("show", open);
    doc.body.classList.toggle("menu-open", open);
    header.classList.toggle("menu-active", open);
    hamburger.setAttribute("aria-expanded", open ? "true" : "false");
    hamburger.setAttribute("aria-label", open ? "Close menu" : "Open menu");
    if (open) {
      var f = navFocusables();
      if (f.length) setTimeout(function () { f[0].focus({ preventScroll: true }); }, 60);
    } else if (returnFocus !== false && nav.contains(doc.activeElement)) {
      hamburger.focus({ preventScroll: true });
    }
  }

  if (hamburger && nav) {
    hamburger.addEventListener("click", function () {
      setMenu(!nav.classList.contains("open"));
    });
    backdrop.addEventListener("click", function () { setMenu(false); });
    // Note: closing the menu on a nav-link tap is handled by the global
    // anchor handler below, so it can sequence the close + scroll correctly.
    doc.addEventListener("keydown", function (e) {
      if (!nav.classList.contains("open")) return;
      if (e.key === "Escape") { setMenu(false); return; }
      // trap Tab within the open off-canvas menu
      if (e.key === "Tab") {
        var f = navFocusables();
        if (!f.length) return;
        var first = f[0], last = f[f.length - 1];
        if (e.shiftKey && doc.activeElement === first) { e.preventDefault(); last.focus(); }
        else if (!e.shiftKey && doc.activeElement === last) { e.preventDefault(); first.focus(); }
      }
    });
    // reset on resize to desktop
    window.addEventListener("resize", function () {
      if (window.innerWidth > 760) setMenu(false);
    });
  }

  /* ---------- smooth in-page anchor navigation ---------- */
  /* Drives scrolling via scrollIntoView (honours each section's scroll-margin-top)
     so links work consistently and the mobile menu closes cleanly on tap. */
  doc.addEventListener("click", function (e) {
    var a = e.target.closest ? e.target.closest('a[href^="#"]') : null;
    if (!a) return;
    var id = a.getAttribute("href");
    if (!id || id === "#" || id.length < 2) return;
    var target = doc.querySelector(id);
    if (!target) return;
    e.preventDefault();
    var wasOpen = nav && nav.classList.contains("open");
    if (wasOpen) setMenu(false, false);
    var go = function () {
      target.scrollIntoView({ behavior: prefersReducedMotion ? "auto" : "smooth", block: "start" });
      if (history.replaceState) history.replaceState(null, "", id);
      else location.hash = id;
    };
    // when closing the menu, wait briefly so the body-scroll lock is lifted
    // (and the layout reflows) before scrolling to the target
    if (wasOpen) setTimeout(go, 90);
    else go();
  });

  /* ---------- scroll reveal ---------- */
  var revealEls = doc.querySelectorAll(".reveal");
  if ("IntersectionObserver" in window && !prefersReducedMotion) {
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry, i) {
        if (entry.isIntersecting) {
          var el = entry.target;
          // small stagger for siblings
          var delay = Math.min(i * 60, 180);
          setTimeout(function () { el.classList.add("in"); }, delay);
          io.unobserve(el);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -8% 0px" });
    revealEls.forEach(function (el) { io.observe(el); });
  } else {
    revealEls.forEach(function (el) { el.classList.add("in"); });
  }

  /* ---------- hero video: respect reduced motion ---------- */
  var heroVideo = doc.getElementById("heroVideo");
  if (heroVideo && prefersReducedMotion) {
    heroVideo.removeAttribute("autoplay");
    heroVideo.pause();
  }

  /* ---------- brand film player ---------- */
  var filmVideo = doc.getElementById("filmVideo");
  var filmPlay = doc.getElementById("filmPlay");
  if (filmVideo && filmPlay) {
    var playFilm = function () {
      filmVideo.play();
    };
    filmPlay.addEventListener("click", playFilm);
    filmVideo.addEventListener("play", function () { filmPlay.classList.add("is-hidden"); });
    filmVideo.addEventListener("pause", function () { filmPlay.classList.remove("is-hidden"); });
    filmVideo.addEventListener("ended", function () { filmPlay.classList.remove("is-hidden"); });
  }

  /* ---------- contact form ---------- */
  var form = doc.getElementById("contactForm");
  if (!form) return;

  var note = doc.getElementById("formNote");
  var submitBtn = doc.getElementById("submitBtn");

  // OPTIONAL: paste a real form endpoint (e.g. Formspree / Web3Forms) here to
  // receive submissions in an inbox automatically. Leave empty to use the
  // built-in mailto fallback (opens the visitor's email app to info@doctorbpro.com).
  var ENDPOINT = ""; // e.g. "https://formspree.io/f/xxxxxx"
  var RECIPIENT = "info@doctorbpro.com";

  var emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  function fieldWrap(input) { return input.closest(".field"); }

  function setError(input, msg) {
    var wrap = fieldWrap(input);
    if (!wrap) return;
    wrap.classList.toggle("field--invalid", !!msg);
    input.setAttribute("aria-invalid", msg ? "true" : "false");
    var err = wrap.querySelector(".field__error");
    if (err) err.textContent = msg || "";
  }

  function validate() {
    var ok = true;
    var name = form.name, email = form.email, message = form.message;

    if (!name.value.trim()) { setError(name, "Please enter your name."); ok = false; }
    else setError(name, "");

    if (!email.value.trim()) { setError(email, "Please enter your email."); ok = false; }
    else if (!emailRe.test(email.value.trim())) { setError(email, "Please enter a valid email address."); ok = false; }
    else setError(email, "");

    if (!message.value.trim()) { setError(message, "Please enter a message."); ok = false; }
    else setError(message, "");

    return ok;
  }

  // live-clear errors as the user types
  ["name", "email", "message"].forEach(function (n) {
    if (form[n]) form[n].addEventListener("input", function () { setError(form[n], ""); });
  });

  function showNote(msg, kind) {
    note.textContent = msg;
    note.className = "contact__formnote " + (kind || "");
  }

  function mailtoFallback(data) {
    var subject = data.subject ? data.subject : "Website enquiry from " + data.name;
    var body =
      "Name: " + data.name + "\n" +
      "Email: " + data.email + "\n" +
      (data.subject ? "Subject: " + data.subject + "\n" : "") +
      "\n" + data.message + "\n";
    var href = "mailto:" + RECIPIENT +
      "?subject=" + encodeURIComponent(subject) +
      "&body=" + encodeURIComponent(body);
    window.location.href = href;
  }

  form.addEventListener("submit", function (e) {
    e.preventDefault();

    // honeypot: if filled, silently "succeed" (likely a bot)
    if (form.company_website && form.company_website.value) {
      showNote("Thank you — your message has been sent.", "ok");
      form.reset();
      return;
    }

    if (!validate()) {
      showNote("Please fix the highlighted fields and try again.", "err");
      var firstInvalid = form.querySelector(".field--invalid input, .field--invalid textarea");
      if (firstInvalid) firstInvalid.focus();
      return;
    }

    var data = {
      name: form.name.value.trim(),
      email: form.email.value.trim(),
      subject: form.subject.value.trim(),
      message: form.message.value.trim()
    };

    if (!ENDPOINT) {
      // No backend configured → open the visitor's email client.
      showNote("Opening your email app… if nothing happens, email us at " + RECIPIENT + ".", "ok");
      mailtoFallback(data);
      return;
    }

    // Real endpoint configured → POST as JSON.
    submitBtn.disabled = true;
    var original = submitBtn.textContent;
    submitBtn.textContent = "Sending…";
    showNote("", "");

    fetch(ENDPOINT, {
      method: "POST",
      headers: { "Accept": "application/json", "Content-Type": "application/json" },
      body: JSON.stringify(data)
    })
      .then(function (res) {
        if (res.ok) {
          showNote("Thank you — your message has been sent. We'll be in touch soon.", "ok");
          form.reset();
        } else {
          throw new Error("Bad response");
        }
      })
      .catch(function () {
        showNote("Something went wrong. Please email us directly at " + RECIPIENT + ".", "err");
      })
      .finally(function () {
        submitBtn.disabled = false;
        submitBtn.textContent = original;
      });
  });
})();
