"use strict";

document.documentElement.classList.replace("no-js", "js");

const SITE_CONFIG = Object.freeze({
  environment: "demo",   // "demo" or "production".
  allowIndexing: false,  // Set to true for the official production domain.

  siteUrl: "https://demo.gularinnovate.com/shalom_landing", // Base URL for this site (no trailing slash).

  appStatus: "prelaunch", // Change to "live" once store links are available.
  playStoreUrl: "",
  appStoreUrl: "",

  // Direct APK download (not a store listing). Place the APK at this path
  // relative to the landing page root and update the file name below.
  apkUrl: "downloads/shalom-app.apk",
  apkFileName: "shalom-app.apk",

  websiteUrl: "https://shalomsuriname.com", // Existing official Shalom website.
  privacyPath: "privacy/",
  termsPath: "voorwaarden/",
  contactUrl: "mailto:Info@shalomsuriname.com",
  facebookUrl: "https://www.facebook.com/shalomsuriname/",
  youtubeUrl: "https://www.youtube.com/@shalomradioentvsuriname5066",

  canonicalUrl: "",      // Legacy full-page canonical URL (overrides siteUrl).
  canonicalDomain: "",   // Legacy base URL (overridden by siteUrl).
  ogImageUrl: "",        // Optional full-URL override for og:image and twitter:image.
  ogImagePath: "resources/assets/generated/og.jpg", // Relative to siteUrl.

  contactEmail: "Info@shalomsuriname.com", // Privacy/Terms contact email.
  contactPhone: "+(597) 422-630",           // Contact phone number.
  legalAddress: "Stadionlaan 7, Paramaribo, Suriname", // Official postal address.
});

/** Analytics-ready no-op. Connect a privacy-respecting provider here later. */
function trackEvent(eventName, properties = {}) {
  void eventName;
  void properties;
}

const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const header = document.querySelector("[data-header]");
const menuToggle = document.querySelector("[data-menu-toggle]");
const mobileMenu = document.querySelector("[data-mobile-menu]");
const mainContent = document.querySelector("main");
const footer = document.querySelector("footer");
let lastFocusedElement = null;

function setHeaderState() {
  header?.classList.toggle("is-scrolled", window.scrollY > 16);
}

setHeaderState();
window.addEventListener("scroll", setHeaderState, { passive: true });

function getMenuFocusableElements() {
  return mobileMenu
    ? [...mobileMenu.querySelectorAll("a[href], button:not([disabled])")]
    : [];
}

function closeMenu({ restoreFocus = true } = {}) {
  if (!menuToggle || !mobileMenu || mobileMenu.hidden) return;

  menuToggle.setAttribute("aria-expanded", "false");
  menuToggle.setAttribute("aria-label", "Menu openen");
  mobileMenu.hidden = true;
  document.body.classList.remove("menu-open");
  header?.classList.remove("menu-active");
  mainContent?.removeAttribute("inert");
  footer?.removeAttribute("inert");

  if (restoreFocus) lastFocusedElement?.focus();
}

function openMenu() {
  if (!menuToggle || !mobileMenu) return;

  lastFocusedElement = document.activeElement;
  menuToggle.setAttribute("aria-expanded", "true");
  menuToggle.setAttribute("aria-label", "Menu sluiten");
  mobileMenu.hidden = false;
  document.body.classList.add("menu-open");
  header?.classList.add("menu-active");
  mainContent?.setAttribute("inert", "");
  footer?.setAttribute("inert", "");
  getMenuFocusableElements()[0]?.focus();
}

menuToggle?.addEventListener("click", () => {
  const isOpen = menuToggle.getAttribute("aria-expanded") === "true";
  isOpen ? closeMenu() : openMenu();
});

mobileMenu?.addEventListener("click", (event) => {
  if (event.target.closest("a")) closeMenu({ restoreFocus: false });
});

document.addEventListener("keydown", (event) => {
  if (!mobileMenu || mobileMenu.hidden) return;

  if (event.key === "Escape") {
    closeMenu();
    return;
  }

  if (event.key !== "Tab") return;

  const focusable = getMenuFocusableElements();
  if (!focusable.length) return;
  const first = focusable[0];
  const last = focusable[focusable.length - 1];

  if (event.shiftKey && document.activeElement === first) {
    event.preventDefault();
    last.focus();
  } else if (!event.shiftKey && document.activeElement === last) {
    event.preventDefault();
    first.focus();
  }
});

window.addEventListener("resize", () => {
  if (window.innerWidth > 900) closeMenu({ restoreFocus: false });
});

// Restrained reveal enhancement. Content remains visible if JavaScript is unavailable.
const revealElements = document.querySelectorAll(".reveal");
if (prefersReducedMotion || !("IntersectionObserver" in window)) {
  revealElements.forEach((element) => element.classList.add("is-visible"));
} else {
  const revealObserver = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        entry.target.classList.add("is-visible");
        observer.unobserve(entry.target);
      });
    },
    { threshold: 0.12, rootMargin: "0px 0px -6%" },
  );

  revealElements.forEach((element) => revealObserver.observe(element));
}

function getNavHash(link) {
  const href = link.getAttribute("href") || "";
  return href.startsWith("/") ? href.split("#")[1] : href.replace(/^#/, "");
}

// Keep the current desktop navigation section legible at a glance.
const navLinks = [...document.querySelectorAll("[data-nav-link]")];
const navTargets = navLinks
  .map((link) => {
    const id = getNavHash(link);
    return id ? document.getElementById(id) : null;
  })
  .filter(Boolean);

if ("IntersectionObserver" in window && navTargets.length) {
  const navObserver = new IntersectionObserver(
    (entries) => {
      const visible = entries
        .filter((entry) => entry.isIntersecting)
        .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];

      if (!visible) return;
      navLinks.forEach((link) => {
        link.classList.toggle("is-active", getNavHash(link) === visible.target.id);
      });
    },
    { rootMargin: "-20% 0px -60%", threshold: [0, 0.2, 0.5] },
  );

  navTargets.forEach((section) => navObserver.observe(section));
}

// Mobile platform selector keeps both products clear without consuming excessive height.
const heroVisual = document.querySelector(".hero-visual");
const platformButtons = document.querySelectorAll("[data-platform]");
platformButtons.forEach((button) => {
  button.addEventListener("click", () => {
    const platform = button.dataset.platform;
    heroVisual?.setAttribute("data-platform-view", platform);
    platformButtons.forEach((item) => {
      const isSelected = item === button;
      item.classList.toggle("is-active", isSelected);
      item.setAttribute("aria-pressed", String(isSelected));
    });
    if (platform === "android") trackEvent("hero_android_click");
    if (platform === "ios") trackEvent("hero_ios_click");
  });
});

// Small concept demo only: it never requests or changes real notification permissions.
const notificationToggle = document.querySelector("[data-notification-toggle]");
const notificationCard = document.querySelector("[data-notification-card]");
notificationToggle?.addEventListener("click", () => {
  const nextState = notificationToggle.getAttribute("aria-checked") !== "true";
  notificationToggle.setAttribute("aria-checked", String(nextState));
  notificationCard?.classList.toggle("is-hidden", !nextState);
});

function getStoreConfig(platform) {
  return platform === "android"
    ? { url: SITE_CONFIG.playStoreUrl, event: "footer_store_android" }
    : { url: SITE_CONFIG.appStoreUrl, event: "footer_store_ios" };
}

function apkIsAvailable() {
  return Boolean(SITE_CONFIG.apkUrl && SITE_CONFIG.apkUrl.trim());
}

function storeIsLive(platform) {
  const { url } = getStoreConfig(platform);
  return SITE_CONFIG.appStatus === "live" && Boolean(url);
}

function openStore(platform, sourceEvent) {
  const { url, event } = getStoreConfig(platform);
  const status = document.querySelector("[data-store-status]");

  if (!storeIsLive(platform)) {
    if (status) {
      status.textContent = `${platform === "android" ? "De Android-app" : "De iPhone-app"} is binnenkort beschikbaar.`;
    }
    document.querySelector("#download")?.scrollIntoView({ behavior: prefersReducedMotion ? "auto" : "smooth" });
    return;
  }

  trackEvent(sourceEvent || event, { platform });
  window.open(url, "_blank", "noopener,noreferrer");
}

document.querySelectorAll("[data-store-button]").forEach((button) => {
  const platform = button.dataset.storeButton;
  const pre = button.querySelector("small");
  const main = button.querySelector("strong");

  button.addEventListener("click", () => openStore(platform));

  if (storeIsLive(platform)) {
    const preLabel = platform === "android" ? "Download via " : "Download in de ";
    const mainLabel = platform === "android" ? "Google Play" : "App Store";
    if (pre) pre.textContent = preLabel;
    if (main) main.textContent = mainLabel;
    button.setAttribute("aria-label", `${preLabel}${mainLabel} (opent in een nieuw venster)`);
  }
});

const hasLiveStore = storeIsLive("android") || storeIsLive("ios");

if (hasLiveStore) {
  document.querySelectorAll("[data-download-trigger]").forEach((button) => {
    const label = button.querySelector("span");
    if (label) label.textContent = "Download de app";
    else button.textContent = "Download de app";
  });

  const mobileStatusCta = document.querySelector("[data-status-cta]");
  if (mobileStatusCta) mobileStatusCta.textContent = "Download de app";

  const availabilityCopy = document.querySelector("[data-availability-copy]");
  if (availabilityCopy) availabilityCopy.textContent = "Nu beschikbaar";

  const launchLabel = document.querySelector("[data-launch-label]");
  if (launchLabel) {
    launchLabel.childNodes.forEach((node) => {
      if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) node.textContent = " Nu beschikbaar ";
    });
  }

  const storeStatus = document.querySelector("[data-store-status]");
  if (storeStatus) storeStatus.textContent = "Kies je platform om de app veilig via de officiële store te downloaden.";
}

const apkAvailable = !hasLiveStore && apkIsAvailable();
if (apkAvailable) {
  const apkFileName = SITE_CONFIG.apkFileName || "shalom-app.apk";

  document.querySelectorAll("[data-download-trigger]").forEach((el) => {
    if (el.tagName === "A" && !el.getAttribute("download") && el.getAttribute("href")?.includes(".apk")) {
      el.setAttribute("download", apkFileName);
      return;
    }
    const label = el.querySelector("span") || el;
    if (label && label.textContent.trim() === "Binnenkort beschikbaar") {
      label.textContent = "Download Android";
    }
  });

  const mobileStatusCta = document.querySelector("[data-status-cta]");
  if (mobileStatusCta) {
    const label = mobileStatusCta.querySelector("span") || mobileStatusCta;
    if (label && label.textContent.trim() === "Binnenkort beschikbaar") {
      label.textContent = "Download Android";
    }
  }

  const availabilityCopy = document.querySelector("[data-availability-copy]");
  if (availabilityCopy) {
    availabilityCopy.textContent = "Download de APK direct. Google Play en de App Store volgen binnenkort.";
  }

  const launchLabel = document.querySelector("[data-launch-label]");
  if (launchLabel) {
    launchLabel.childNodes.forEach((node) => {
      if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) node.textContent = " Android APK nu beschikbaar ";
    });
  }

  const storeStatus = document.querySelector("[data-store-status]");
  if (storeStatus) {
    storeStatus.textContent = "Download de Android-app rechtstreeks via deze website. Google Play en de App Store volgen binnenkort. Android kan bij directe installatie om toestemming vragen om de APK te installeren.";
  }
}

document.querySelectorAll("[data-download-trigger]").forEach((el) => {
  el.addEventListener("click", (event) => {
    trackEvent("hero_download_cta");
    if (!apkIsAvailable()) {
      event.preventDefault();
      document.querySelector("#download")?.scrollIntoView({ behavior: prefersReducedMotion ? "auto" : "smooth" });
    }
    // When an APK URL is configured and the trigger is a real anchor, the
    // browser's default download action is allowed to proceed.
  });
});

// Replace prelaunch placeholders only when verified production URLs are configured.
const footerConfig = [
  ["Website", SITE_CONFIG.websiteUrl],
  ["Contact", SITE_CONFIG.contactUrl],
  ["Facebook", SITE_CONFIG.facebookUrl],
  ["YouTube", SITE_CONFIG.youtubeUrl],
];
const configLinksContainer = document.querySelector("[data-config-links]");
if (configLinksContainer) {
  const heading = configLinksContainer.querySelector("strong");
  configLinksContainer.replaceChildren(heading);
  footerConfig.forEach(([label, url]) => {
    if (url) {
      const link = document.createElement("a");
      link.href = url;
      link.textContent = label;
      configLinksContainer.append(link);
    } else {
      const item = document.createElement("span");
      item.append(document.createTextNode(`${label} `));
      const status = document.createElement("small");
      status.textContent = "Binnenkort";
      item.append(status);
      configLinksContainer.append(item);
    }
  });
}

// Inject canonical and social image URLs from centralized config.
function setSeoUrls() {
  let canonicalHref = "";
  if (SITE_CONFIG.canonicalUrl) {
    canonicalHref = SITE_CONFIG.canonicalUrl;
  } else {
    const canonicalBase = SITE_CONFIG.siteUrl || SITE_CONFIG.canonicalDomain || SITE_CONFIG.websiteUrl;
    if (canonicalBase) {
      const canonicalPath = (document.body?.dataset.canonicalPath || "/").replace(/^\//, "");
      const base = canonicalBase.replace(/\/$/, "");
      canonicalHref = `${base}/${canonicalPath}`;
    }
  }

  if (canonicalHref) {
    let canonical = document.querySelector('link[rel="canonical"]');
    if (!canonical) {
      canonical = document.createElement("link");
      canonical.rel = "canonical";
      document.head.appendChild(canonical);
    }
    canonical.href = canonicalHref;

    const ogUrl = document.querySelector('meta[property="og:url"]') || document.createElement("meta");
    ogUrl.setAttribute("property", "og:url");
    ogUrl.setAttribute("content", canonicalHref);
    if (!ogUrl.parentNode) document.head.appendChild(ogUrl);
  }

  let ogImageHref = "";
  if (SITE_CONFIG.ogImageUrl) {
    ogImageHref = SITE_CONFIG.ogImageUrl;
  } else if (SITE_CONFIG.siteUrl && SITE_CONFIG.ogImagePath) {
    const base = SITE_CONFIG.siteUrl.replace(/\/$/, "");
    const path = SITE_CONFIG.ogImagePath.replace(/^\//, "");
    ogImageHref = `${base}/${path}`;
  }

  if (ogImageHref) {
    const ogImage = document.querySelector('meta[property="og:image"]') || document.createElement("meta");
    ogImage.setAttribute("property", "og:image");
    ogImage.setAttribute("content", ogImageHref);
    if (!ogImage.parentNode) document.head.appendChild(ogImage);

    const twitterImage = document.querySelector('meta[name="twitter:image"]') || document.createElement("meta");
    twitterImage.setAttribute("name", "twitter:image");
    twitterImage.setAttribute("content", ogImageHref);
    if (!twitterImage.parentNode) document.head.appendChild(twitterImage);
  }
}
setSeoUrls();

// Set robots directive based on environment config.
function setRobots() {
  const content = SITE_CONFIG.allowIndexing ? "index, follow" : "noindex, nofollow";
  let meta = document.querySelector('meta[name="robots"]');
  if (!meta) {
    meta = document.createElement("meta");
    meta.setAttribute("name", "robots");
    document.head.appendChild(meta);
  }
  meta.setAttribute("content", content);
}
setRobots();

// Fill configurable legal fields such as contact email and official address.
function setLegalPlaceholders() {
  const fields = document.querySelectorAll("[data-legal-field]");
  if (!fields.length) return;

  const isDev =
    window.location.hostname === "localhost" ||
    window.location.hostname === "127.0.0.1" ||
    window.location.hostname.endsWith(".local");

  const values = {
    "contact-email": SITE_CONFIG.contactEmail,
    "contact-phone": SITE_CONFIG.contactPhone,
    "legal-address": SITE_CONFIG.legalAddress,
  };

  fields.forEach((el) => {
    const key = el.dataset.legalField;
    const value = values[key];
    if (value) {
      if (key === "contact-email") {
        el.innerHTML = `<a href="mailto:${value}">${value}</a>`;
      } else if (key === "contact-phone") {
        const tel = value.replace(/[^+\d]/g, "");
        el.innerHTML = `<a href="tel:${tel}">${value}</a>`;
      } else {
        el.textContent = value;
      }
      el.classList.remove("legal-pending");
    } else if (isDev) {
      const pending = {
        "contact-email": "e-mailadres wordt aangevuld",
        "contact-phone": "telefoonnummer wordt aangevuld",
        "legal-address": "adres wordt aangevuld",
      };
      el.textContent = pending[key] || "wordt aangevuld";
      el.classList.add("legal-pending");
    }
  });
}
setLegalPlaceholders();

// Future feature-view analytics: no personal data and each event fires only once.
if ("IntersectionObserver" in window) {
  const featureObserver = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        trackEvent(entry.target.dataset.observeSection);
        observer.unobserve(entry.target);
      });
    },
    { threshold: 0.35 },
  );
  document.querySelectorAll("[data-observe-section]").forEach((section) => featureObserver.observe(section));
}

const year = document.querySelector("[data-current-year]");
if (year) year.textContent = String(new Date().getFullYear());
