const flyover = document.querySelector("[data-contact-flyover]");
const flyoverPanel = document.querySelector(".contact-flyover__panel");
const openButtons = document.querySelectorAll("[data-open-contact]");
const closeButtons = document.querySelectorAll("[data-close-contact]");
const copyButtons = document.querySelectorAll("[data-copy-value]");
let lastTrigger = null;

const positionFlyover = (trigger) => {
  if (!flyover || !flyoverPanel || !trigger) return;

  const isMobile = window.innerWidth <= 768;
  const rect = trigger.getBoundingClientRect();
  const gap = 16;

  if (isMobile) {
    const top = Math.min(rect.bottom + gap, window.innerHeight - 320);
    flyover.style.setProperty("--flyover-top", `${Math.max(gap, top)}px`);
    flyover.style.removeProperty("--flyover-left");
    return;
  }

  const panelWidth = Math.min(420, window.innerWidth - 32);
  const preferredLeft = rect.right + gap;
  const maxLeft = window.innerWidth - panelWidth - gap;
  const left = Math.min(preferredLeft, maxLeft);
  const top = Math.max(gap, rect.top - 10);

  flyover.style.setProperty("--flyover-left", `${left}px`);
  flyover.style.setProperty("--flyover-top", `${top}px`);
};

const openFlyover = (trigger) => {
  if (!flyover) return;
  lastTrigger = trigger ?? null;
  positionFlyover(trigger);
  flyover.hidden = false;
  document.body.classList.add("is-scroll-locked");
};

const closeFlyover = () => {
  if (!flyover) return;
  flyover.hidden = true;
  document.body.classList.remove("is-scroll-locked");
};

openButtons.forEach((button) => {
  button.addEventListener("click", () => openFlyover(button));
});

closeButtons.forEach((button) => {
  button.addEventListener("click", closeFlyover);
});

document.addEventListener("keydown", (event) => {
  if (event.key === "Escape" && flyover && !flyover.hidden) {
    closeFlyover();
  }
});

window.addEventListener("resize", () => {
  if (flyover && !flyover.hidden && lastTrigger) {
    positionFlyover(lastTrigger);
  }
});

copyButtons.forEach((button) => {
  button.addEventListener("click", async () => {
    const value = button.dataset.copyValue;
    if (!value) return;

    try {
      await navigator.clipboard.writeText(value);
      const label = button.querySelector("span");
      button.classList.add("is-copied");
      if (label) label.textContent = "Kopiert";

      window.setTimeout(() => {
        button.classList.remove("is-copied");
        if (label) label.textContent = "Kopieren";
      }, 1800);
    } catch (error) {
      console.error("Copy failed", error);
    }
  });
});
