(function () {
  "use strict";

  const $ = (sel, ctx) => (ctx || document).querySelector(sel);
  const $$ = (sel, ctx) => Array.from((ctx || document).querySelectorAll(sel));
  const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  document.addEventListener("DOMContentLoaded", () => {
  const header = $("#site-header");
  const nav = $("#site-nav");
  const navToggle = $("#nav-toggle");
  const toTop = $("#to-top");

  const setHeaderState = () => {
    const scrolled = window.scrollY > 12;
    header.classList.toggle("is-scrolled", scrolled);
    if (toTop) toTop.classList.toggle("is-visible", window.scrollY > 640);
  };

  let scrollTicking = false;
  window.addEventListener("scroll", () => {
    if (!scrollTicking) {
      window.requestAnimationFrame(() => {
        setHeaderState();
        scrollTicking = false;
      });
      scrollTicking = true;
    }
  }, { passive: true });

  setHeaderState();

  if (toTop) {
    toTop.addEventListener("click", () => {
      window.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" });
    });
  }

  const closeMobileNav = () => {
    nav.classList.remove("is-open");
    navToggle.classList.remove("is-active");
    navToggle.setAttribute("aria-expanded", "false");
    document.body.classList.remove("no-scroll");
  };

  const openMobileNav = () => {
    nav.classList.add("is-open");
    navToggle.classList.add("is-active");
    navToggle.setAttribute("aria-expanded", "true");
    document.body.classList.add("no-scroll");
  };

  navToggle.addEventListener("click", () => {
    const open = nav.classList.contains("is-open");
    open ? closeMobileNav() : openMobileNav();
  });

  nav.addEventListener("click", (e) => {
    if (e.target.closest("a")) closeMobileNav();
  });

  window.addEventListener("resize", () => {
    if (window.innerWidth > 920 && nav.classList.contains("is-open")) {
      closeMobileNav();
      $$(".has-dropdown.is-open").forEach((d) => d.classList.remove("is-open"));
    }
  });

  $$(".nav__toggle").forEach((toggle) => {
    toggle.addEventListener("click", () => {
      const parent = toggle.closest(".has-dropdown");
      const wasOpen = parent.classList.contains("is-open");
      $$(".has-dropdown.is-open").forEach((d) => {
        d.classList.remove("is-open");
        const t = d.querySelector(".nav__toggle");
        if (t) t.setAttribute("aria-expanded", "false");
      });
      if (!wasOpen) {
        parent.classList.add("is-open");
        toggle.setAttribute("aria-expanded", "true");
      }
    });
  });

  document.addEventListener("click", (e) => {
    if (!e.target.closest(".has-dropdown")) {
      $$(".has-dropdown.is-open").forEach((d) => {
        d.classList.remove("is-open");
        const t = d.querySelector(".nav__toggle");
        if (t) t.setAttribute("aria-expanded", "false");
      });
    }
  });

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      closeMobileNav();
      $$(".has-dropdown.is-open").forEach((d) => d.classList.remove("is-open"));
      closeModal();
    }
  });

  const revealEls = $$(".reveal");
  if ("IntersectionObserver" in window && !reduceMotion) {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("is-revealed");
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.14, rootMargin: "0px 0px -40px 0px" });
    revealEls.forEach((el) => io.observe(el));
  } else {
    revealEls.forEach((el) => el.classList.add("is-revealed"));
  }

  const counters = $$("[data-count]");
  if ("IntersectionObserver" in window) {
    const co = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        const el = entry.target;
        co.unobserve(el);
        const target = parseFloat(el.dataset.count);
        const decimals = parseInt(el.dataset.decimals || "0", 10);
        const prefix = el.dataset.prefix || "";
        const suffix = el.dataset.suffix || "";
        const format = (v) => prefix + v.toFixed(decimals) + suffix;
        if (reduceMotion || isNaN(target)) {
          el.textContent = format(target);
          return;
        }
        const duration = 1600;
        const start = performance.now();
        const tick = (now) => {
          const p = Math.min((now - start) / duration, 1);
          const eased = 1 - Math.pow(1 - p, 3);
          el.textContent = format(target * eased);
          if (p < 1) window.requestAnimationFrame(tick);
        };
        window.requestAnimationFrame(tick);
      });
    }, { threshold: 0.4 });
    counters.forEach((el) => co.observe(el));
  } else {
    counters.forEach((el) => {
      const decimals = parseInt(el.dataset.decimals || "0", 10);
      el.textContent = (el.dataset.prefix || "") + parseFloat(el.dataset.count).toFixed(decimals) + (el.dataset.suffix || "");
    });
  }

  const chips = $$(".chip[data-filter]");
  const articles = $$(".article-card");
  chips.forEach((chip) => {
    chip.addEventListener("click", () => {
      chips.forEach((c) => c.classList.toggle("is-active", c === chip));
      const filter = chip.dataset.filter;
      articles.forEach((a) => {
        a.hidden = filter !== "all" && a.dataset.cat !== filter;
      });
    });
  });

  const tabs = $$(".tabs");
  tabs.forEach((tabGroup) => {
    const btns = $$(".tabs__btn", tabGroup);
    const panels = $$(".tabs__panel", tabGroup);

    const activate = (index) => {
      btns.forEach((b, i) => {
        const active = i === index;
        b.classList.toggle("is-active", active);
        b.setAttribute("aria-selected", active ? "true" : "false");
        b.tabIndex = active ? 0 : -1;
      });
      panels.forEach((p, i) => {
        p.classList.toggle("is-active", i === index);
        p.hidden = i !== index;
      });
    };

    btns.forEach((btn, i) => {
      btn.addEventListener("click", () => activate(i));
      btn.addEventListener("keydown", (e) => {
        if (!["ArrowRight", "ArrowLeft", "Home", "End"].includes(e.key)) return;
        e.preventDefault();
        let next = i;
        if (e.key === "ArrowRight") next = (i + 1) % btns.length;
        else if (e.key === "ArrowLeft") next = (i - 1 + btns.length) % btns.length;
        else if (e.key === "Home") next = 0;
        else if (e.key === "End") next = btns.length - 1;
        activate(next);
        btns[next].focus();
      });
    });
  });

  $$(".faq__btn").forEach((btn) => {
    btn.addEventListener("click", () => {
      const item = btn.closest(".faq__item");
      const isOpen = item.classList.contains("is-open");
      $$(".faq__item.is-open").forEach((open) => {
        open.classList.remove("is-open");
        const b = open.querySelector(".faq__btn");
        const a = open.querySelector(".faq__a");
        if (b) b.setAttribute("aria-expanded", "false");
        if (a) a.hidden = true;
      });
      if (!isOpen) {
        item.classList.add("is-open");
        btn.setAttribute("aria-expanded", "true");
        const panel = btn.getAttribute("aria-controls");
        const a = document.getElementById(panel);
        if (a) a.hidden = false;
      }
    });
  });

  const sectionIds = ["about", "approach", "pipeline", "trials", "testimonials", "investor-card", "news", "contact"];
  const navLinks = $$(".nav__link[href^='#']");

  if ("IntersectionObserver" in window) {
    const spy = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        navLinks.forEach((link) => {
          const target = link.getAttribute("href").slice(1);
          link.classList.toggle("is-active", target === entry.target.id);
        });
      });
    }, { rootMargin: "-45% 0px -50% 0px" });
    sectionIds.forEach((id) => {
      const el = document.getElementById(id);
      if (el) spy.observe(el);
    });
  }

  const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

  const setFieldError = (field, message) => {
    const wrap = field.closest(".form__field");
    if (!wrap) return;
    wrap.classList.add("is-invalid");
    const err = wrap.querySelector(".form__error");
    if (err) err.textContent = message;
  };

  const clearFieldError = (field) => {
    const wrap = field.closest(".form__field");
    if (!wrap) return;
    wrap.classList.remove("is-invalid");
  };

  const validateField = (field) => {
    const value = field.value.trim();
    if (field.required && !value) {
      setFieldError(field, "This field is required.");
      return false;
    }
    if (field.type === "email" && value && !emailRe.test(value)) {
      setFieldError(field, "Please enter a valid email address.");
      return false;
    }
    clearFieldError(field);
    return true;
  };

  const validateForm = (form) => {
    let valid = true;
    $$("input, select, textarea", form).forEach((field) => {
      if (!validateField(field)) valid = false;
    });
    const check = $('input[type="checkbox"]', form);
    if (check) {
      const wrap = check.closest(".form__check");
      if (!check.checked) {
        valid = false;
        if (wrap) wrap.style.color = "#d9475e";
      } else if (wrap) {
        wrap.style.color = "";
      }
    }
    return valid;
  };

  const bindForm = (form, successId) => {
    const success = document.getElementById(successId);
    $$("input, select, textarea", form).forEach((field) => {
      field.addEventListener("blur", () => validateField(field));
      field.addEventListener("input", () => {
        if (field.closest(".form__field").classList.contains("is-invalid")) {
          validateField(field);
        }
      });
    });

    form.addEventListener("submit", (e) => {
      e.preventDefault();
      if (!validateForm(form)) return;
      if (success) success.hidden = false;
      form.reset();
      $$(".form__field", form).forEach((f) => f.classList.remove("is-invalid"));
      const check = $('input[type="checkbox"]', form);
      if (check) {
        const wrap = check.closest(".form__check");
        if (wrap) wrap.style.color = "";
      }
      if (success) {
        setTimeout(() => {
          success.hidden = true;
          if (form.closest(".modal__box")) closeModal();
        }, 3200);
      }
    });
  };

  const contactForm = $("#contact-form");
  if (contactForm) bindForm(contactForm, "form-success");

  const irForm = $("#ir-form");
  if (irForm) bindForm(irForm, "ir-success");

  const modal = $("#modal-ir");
  let lastFocused = null;

  const openModal = () => {
    if (!modal) return;
    lastFocused = document.activeElement;
    modal.hidden = false;
    document.body.classList.add("no-scroll");
    const firstInput = $("input", modal);
    setTimeout(() => (firstInput || modal).focus(), 60);
  };

  const closeModal = () => {
    if (!modal || modal.hidden) return;
    modal.hidden = true;
    document.body.classList.remove("no-scroll");
    if (lastFocused && lastFocused.focus) lastFocused.focus();
  };

  $$(".js-modal-open").forEach((btn) => {
    btn.addEventListener("click", (e) => {
      e.preventDefault();
      openModal();
    });
  });

  $$("[data-modal-close]", modal || document).forEach((el) => {
    el.addEventListener("click", closeModal);
  });

  window.addEventListener("keydown", (e) => {
    if (e.key === "Escape" && modal && !modal.hidden) closeModal();
    if (e.key === "Tab" && modal && !modal.hidden) {
      const focusables = $$('a[href], button:not([disabled]), input, select, textarea', modal).filter((el) => !el.hasAttribute("hidden"));
      if (!focusables.length) return;
      const first = focusables[0];
      const last = focusables[focusables.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    }
  });

  const leaderModal = $("#leader-modal");
  if (leaderModal) {
    const leaderPhoto = $("#leader-modal-photo", leaderModal);
    const leaderName = $("#leader-modal-name", leaderModal);
    const leaderRole = $("#leader-modal-role", leaderModal);
    const leaderBio = $("#leader-modal-bio", leaderModal);
    const leaderCloseBtn = $(".modal__close", leaderModal);
    let leaderTimer = null;

    const leaderHide = () => {
      leaderModal.classList.remove("is-closing");
      leaderModal.hidden = true;
      document.body.classList.remove("no-scroll");
      if (lastFocused && lastFocused.focus) lastFocused.focus();
    };

    const leaderClose = () => {
      if (leaderModal.hidden) return;
      leaderModal.classList.add("is-closing");
      document.body.classList.remove("no-scroll");
      clearTimeout(leaderTimer);
      leaderTimer = setTimeout(leaderHide, 260);
    };

    $$(".team-card__link").forEach((link) => {
      link.addEventListener("click", () => {
        const card = link.closest(".team-card");
        lastFocused = link;
        leaderName.textContent = card.querySelector(".team-card__name").textContent;
        leaderRole.textContent = card.querySelector(".team-card__title").textContent;
        leaderBio.textContent = card.querySelector(".team-card__bio").textContent;
        const img = card.querySelector(".team-card__photo");
        leaderPhoto.src = img.getAttribute("src");
        leaderPhoto.alt = "Portrait of " + leaderName.textContent;
        leaderModal.hidden = false;
        document.body.classList.add("no-scroll");
        if (leaderCloseBtn) leaderCloseBtn.focus();
      });
    });

    $$("[data-leader-close]", leaderModal).forEach((el) => {
      el.addEventListener("click", leaderClose);
    });

    window.addEventListener("keydown", (e) => {
      if (e.key === "Escape") leaderClose();
    });
  }
  });
})();
