import { Post } from "@/types/types";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";
import { getSiteSeoMeta } from "@/lib/i18n/seo";
import { translateCommon } from "@/lib/i18n/translate";

function slugify(text: string): string {
  return text
    .trim()
    .toLowerCase()
    .replace(/[^\p{L}\p{N}\s-]/gu, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^-|-$/g, "")
    .slice(0, 80);
}

export function buildPostSlug(post: Pick<Post, "caption" | "user_name" | "first_name" | "last_name">): string {
  const author =
    [post.first_name, post.last_name].filter(Boolean).join(" ") ||
    post.user_name ||
    "post";
  const captionPart = post.caption ? slugify(post.caption.slice(0, 60)) : "";
  const authorPart = slugify(author);
  const combined = [authorPart, captionPart].filter(Boolean).join("-");
  return combined || "post";
}

export function buildPostPath(
  postId: string,
  post?: Pick<Post, "caption" | "user_name" | "first_name" | "last_name">
): string {
  const slug = post ? buildPostSlug(post) : "post";
  return `/posts/${postId}/${slug}`;
}

export function buildPostPublicUrl(
  postId: string,
  post?: Pick<Post, "caption" | "user_name" | "first_name" | "last_name">
): string {
  return `https://modstagram.com${buildPostPath(postId, post)}`;
}

export function buildPostSeoTitle(
  post: Pick<Post, "caption" | "user_name" | "first_name" | "last_name" | "expertise">,
  lang: AppLanguage = DEFAULT_LANGUAGE
): string {
  const siteName = getSiteSeoMeta(lang).name;
  const author =
    [post.first_name, post.last_name].filter(Boolean).join(" ") ||
    post.user_name ||
    translateCommon(lang, "postsMeta.userFallback");
  const caption = post.caption?.trim();
  if (caption) {
    return translateCommon(lang, "postsMeta.titleWithCaption", {
      caption: caption.slice(0, 55),
      author,
      siteName,
    });
  }
  if (post.expertise) {
    return translateCommon(lang, "postsMeta.titleWithExpertise", {
      expertise: post.expertise,
      author,
      siteName,
    });
  }
  return translateCommon(lang, "postsMeta.titleSimple", { author, siteName });
}

export function buildPostSeoDescription(
  post: Pick<Post, "caption" | "user_name" | "first_name" | "last_name" | "expertise">,
  lang: AppLanguage = DEFAULT_LANGUAGE
): string {
  const siteName = getSiteSeoMeta(lang).name;
  const author =
    [post.first_name, post.last_name].filter(Boolean).join(" ") ||
    post.user_name ||
    translateCommon(lang, "postsMeta.userFallback");
  const caption = post.caption?.trim();
  if (caption) {
    return translateCommon(lang, "postsMeta.descWithCaption", {
      caption: caption.slice(0, 140),
      author,
      siteName,
    });
  }
  const expertise = post.expertise
    ? translateCommon(lang, "postsMeta.expertiseSuffix", {
        expertise: post.expertise,
      })
    : "";
  return translateCommon(lang, "postsMeta.descSimple", {
    author,
    expertise,
    siteName,
  });
}
