// utils/openInNewTab.js

export function openInNewTab(e, target) {
  const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";
  const url = new URL(window.location.origin);
  const originWithoutPort = `${url.protocol}//${url.hostname}`; // ohne Port!

  let link;

  if (target instanceof L.Marker && target.options.link) {
    link = `${originWithoutPort}${basePath}/devices/${target.options.link}`;
  } else if (target instanceof L.Polyline) {
    const idLD = target.options.idLD;
    if (idLD) {
      link = `${originWithoutPort}${basePath}/devices/cpl.aspx?id=${idLD}`;
    } else {
      console.error("Keine gültige 'idLD' für die Linie gefunden.");
      return;
    }
  } else {
    const lastElementType = localStorage.getItem("lastElementType");
    if (lastElementType === "polyline") {
      const savedLink = localStorage.getItem("polylineLink");
      if (savedLink) {
        link = `${originWithoutPort}${basePath}/devices/${savedLink}`;
      }
    }
  }

  if (link) {
    if (process.env.NEXT_PUBLIC_DEBUG_LOG === "true") {
      console.log("🟢 Öffne Link:", link);
    }
    window.open(link, "_blank");
  } else {
    console.error("❌ Kein gültiger Link gefunden.");
  }
}
