export const SITE_URL = "https://createitsimple.com";

/**
 * Normalizes a URL path by:
 * - Ensuring leading slash
 * - Lowercasing the path
 * - Stripping trailing slashes (except root "/")
 * - Merging duplicate slashes
 */
export function normalizePathname(pathname: string = "/"): string {
  if (!pathname || pathname === "/") return "/";

  let clean = pathname.trim();
  // Strip query parameters or hash fragments if present
  clean = clean.split("?")[0].split("#")[0];
  // Convert path to lowercase
  clean = clean.toLowerCase();
  // Replace multiple adjacent slashes with a single slash
  clean = clean.replace(/\/+/g, "/");
  // Remove trailing slash unless it's the root path "/"
  if (clean.length > 1 && clean.endsWith("/")) {
    clean = clean.slice(0, -1);
  }
  return clean || "/";
}

/**
 * Returns a fully-qualified absolute canonical URL for a given path or relative URL.
 */
export function getCanonicalUrl(pathOrUrl: string = "/"): string {
  if (!pathOrUrl) return `${SITE_URL}/`;

  if (pathOrUrl.startsWith("http://") || pathOrUrl.startsWith("https://")) {
    try {
      const urlObj = new URL(pathOrUrl);
      const cleanPath = normalizePathname(urlObj.pathname);
      return `${SITE_URL}${cleanPath === "/" ? "/" : cleanPath}`;
    } catch {
      // Fallback if URL parsing fails
    }
  }

  const cleanPath = normalizePathname(pathOrUrl);
  return `${SITE_URL}${cleanPath === "/" ? "/" : cleanPath}`;
}

/**
 * Utility to construct consistent SEO metadata including absolute canonical link,
 * OpenGraph, Twitter card, and standard meta tags.
 */
export function buildSeoMeta({
  title,
  description,
  path = "/",
  type = "website",
  image = "/favicon.png",
}: {
  title: string;
  description: string;
  path?: string;
  type?: "website" | "article";
  image?: string;
}) {
  const canonicalUrl = getCanonicalUrl(path);
  const imageUrl = image.startsWith("http") ? image : `${SITE_URL}${image.startsWith("/") ? "" : "/"}${image}`;

  return {
    meta: [
      { title },
      { name: "description", content: description },
      { property: "og:title", content: title },
      { property: "og:description", content: description },
      { property: "og:url", content: canonicalUrl },
      { property: "og:type", content: type },
      { property: "og:image", content: imageUrl },
      { name: "twitter:card", content: "summary_large_image" },
      { name: "twitter:title", content: title },
      { name: "twitter:description", content: description },
      { name: "twitter:url", content: canonicalUrl },
      { name: "twitter:image", content: imageUrl },
    ],
    links: [
      { rel: "canonical", href: canonicalUrl },
    ],
  };
}
