import {
  SITE_BRAND_NAME,
  SITE_DEFAULT_DESCRIPTION,
  SITE_ORIGIN,
} from "../constants/brand.js";
import { getSiteOgImageUrl, getSiteLocale } from "../config/site.js";

const OG_IMAGE_WIDTH = "1200";
const OG_IMAGE_HEIGHT = "630";

function resolvePublicOrigin() {
  if (typeof window === "undefined" || !window.location) return SITE_ORIGIN;
  const { hostname, origin } = window.location;
  if (hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".local")) {
    return origin;
  }
  return SITE_ORIGIN;
}

export function absolutePublicPageUrl(path) {
  const base = resolvePublicOrigin().replace(/\/$/, "");
  const p = path === "/" || !path ? "/" : path.startsWith("/") ? path : `/${path}`;
  if (p === "/") return `${base}/`;
  return `${base}${p}`;
}

function setMetaName(name, content) {
  let el = document.querySelector(`meta[name="${name}"]`);
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute("name", name);
    document.head.appendChild(el);
  }
  el.setAttribute("content", content);
}

function setMetaProperty(property, content) {
  let el = document.querySelector(`meta[property="${property}"]`);
  if (!el) {
    el = document.createElement("meta");
    el.setAttribute("property", property);
    document.head.appendChild(el);
  }
  el.setAttribute("content", content);
}

function setLinkRel(rel, href) {
  let el = document.querySelector(`link[rel="${rel}"]`);
  if (!el) {
    el = document.createElement("link");
    el.setAttribute("rel", rel);
    document.head.appendChild(el);
  }
  el.setAttribute("href", href);
}

function removeMetaProperty(property) {
  document.querySelectorAll(`meta[property="${property}"]`).forEach((n) => n.remove());
}

function applyOgLocales() {
  const loc = getSiteLocale();
  const primary = loc === "en" ? "en_US" : "tr_TR";
  const alternate = loc === "en" ? "tr_TR" : "en_US";
  setMetaProperty("og:locale", primary);
  removeMetaProperty("og:locale:alternate");
  const m = document.createElement("meta");
  m.setAttribute("property", "og:locale:alternate");
  m.setAttribute("content", alternate);
  document.head.appendChild(m);
}

const WEBPAGE_LD_SCRIPT_ID = "seo-jsonld-webpage";

function upsertWebPageJsonLd(path, meta, description) {
  const url = absolutePublicPageUrl(path);
  const existing = document.getElementById(WEBPAGE_LD_SCRIPT_ID);
  if (existing) existing.remove();

  const loc = getSiteLocale();
  const inLanguage = loc === "en" ? "en-US" : "tr-TR";

  const data = {
    "@context": "https://schema.org",
    "@type": "WebPage",
    "@id": `${url}#webpage`,
    url,
    name: meta.title,
    description,
    inLanguage,
    isPartOf: { "@id": `${SITE_ORIGIN}/#website` },
    publisher: { "@id": `${SITE_ORIGIN}/#organization` },
  };

  const script = document.createElement("script");
  script.type = "application/ld+json";
  script.id = WEBPAGE_LD_SCRIPT_ID;
  script.textContent = JSON.stringify(data);
  document.head.appendChild(script);
}

function syncDocumentHtmlLang() {
  document.documentElement.lang = getSiteLocale() === "en" ? "en" : "tr";
}

export function applyClientSeo(path, meta) {
  const description = (meta.description && meta.description.trim()) || SITE_DEFAULT_DESCRIPTION;
  const canonical = absolutePublicPageUrl(path);
  const ogImage = getSiteOgImageUrl();

  syncDocumentHtmlLang();

  setMetaName("description", description);
  setLinkRel("canonical", canonical);

  setMetaProperty("og:title", meta.title);
  setMetaProperty("og:description", description);
  setMetaProperty("og:type", "website");
  setMetaProperty("og:url", canonical);
  setMetaProperty("og:image", ogImage);
  setMetaProperty("og:image:width", OG_IMAGE_WIDTH);
  setMetaProperty("og:image:height", OG_IMAGE_HEIGHT);
  setMetaProperty("og:image:alt", `${SITE_BRAND_NAME} — ${meta.title}`);
  setMetaProperty("og:site_name", SITE_BRAND_NAME);
  applyOgLocales();

  setMetaName("twitter:card", "summary_large_image");
  setMetaName("twitter:title", meta.title);
  setMetaName("twitter:description", description);
  setMetaName("twitter:image", ogImage);
  const twAlt =
    getSiteLocale() === "en"
      ? `${SITE_BRAND_NAME} — preview image`
      : `${SITE_BRAND_NAME} — önizleme görseli`;
  setMetaName("twitter:image:alt", twAlt);

  upsertWebPageJsonLd(path, meta, description);
}
