import {
  formatLocalizedSeoTitle,
  getListSeoTemplates,
  getSeoPage,
  interpolateTemplate,
} from "@/lib/i18n/seo";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";

export type AcademyListFilters = {
  category?: string;
  type?: string;
  isFree?: boolean;
  sortBy?: string;
  sortOrder?: string;
  search?: string;
};

export function getAcademyListDescription(lang: AppLanguage = DEFAULT_LANGUAGE) {
  return getSeoPage("academy", lang).description;
}

/** @deprecated Use getAcademyListDescription(lang) */
export const ACADEMY_LIST_DESCRIPTION = getAcademyListDescription();

function resolveSortLabel(
  filters: AcademyListFilters,
  lang: AppLanguage
): string {
  const sortLabels = getListSeoTemplates(lang).academy.sort as Record<
    string,
    string
  >;

  if (filters.sortBy && filters.sortOrder) {
    const key = `${filters.sortBy}_${filters.sortOrder}`;
    if (sortLabels[key]) return sortLabels[key];
  }
  if (filters.sortBy === "likes" && filters.sortOrder === "desc") {
    return sortLabels.likes_desc ?? sortLabels.createdAt_desc;
  }
  return sortLabels.createdAt_desc;
}

function resolveTypeLabel(
  filters: AcademyListFilters,
  lang: AppLanguage
): string {
  const typeLabels = getListSeoTemplates(lang).academy.type as Record<
    string,
    string
  >;

  if (filters.isFree || filters.type === "free") {
    return typeLabels.free ?? "";
  }
  if (filters.type && typeLabels[filters.type]) {
    return lang === "fa"
      ? `بصورت ${typeLabels[filters.type]}`
      : typeLabels[filters.type];
  }
  return "";
}

export function buildAcademyListPath(filters: AcademyListFilters): string {
  const params = new URLSearchParams();
  if (filters.search) params.set("search", filters.search);
  if (filters.category) params.set("category", filters.category);
  if (filters.type && filters.type !== "free") params.set("type", filters.type);
  if (filters.isFree || filters.type === "free") params.set("isFree", "true");
  if (filters.sortBy && filters.sortBy !== "createdAt") {
    params.set("sortBy", filters.sortBy);
  }
  if (filters.sortOrder && filters.sortOrder !== "desc") {
    params.set("sortOrder", filters.sortOrder);
  }
  const query = params.toString();
  return query ? `/academy?${query}` : "/academy";
}

export function buildAcademyListSeo(
  filters: AcademyListFilters,
  lang: AppLanguage = DEFAULT_LANGUAGE
) {
  const academyPage = getSeoPage("academy", lang);
  const templates = getListSeoTemplates(lang).academy as Record<string, string>;
  const sortLabels = getListSeoTemplates(lang).academy.sort as Record<
    string,
    string
  >;

  const hasFilters = Boolean(
    filters.category ||
      filters.type ||
      filters.isFree ||
      filters.search ||
      (filters.sortBy && filters.sortBy !== "createdAt")
  );

  if (!hasFilters) {
    return {
      title: academyPage.title,
      description: academyPage.description,
      path: academyPage.path,
      h1: academyPage.h1 ?? templates.defaultTitle,
    };
  }

  const sortLabel = resolveSortLabel(filters, lang);
  const categoryPart = filters.category ? filters.category : "";
  const typePart = resolveTypeLabel(filters, lang);
  const searchPart = filters.search
    ? interpolateTemplate(templates.searchPart, { search: filters.search })
    : "";

  const titleCore = [
    searchPart,
    sortLabel,
    templates.coursesWord,
    categoryPart,
    typePart,
  ]
    .filter(Boolean)
    .join(templates.titleJoiner ?? " ")
    .replace(/\s+/g, " ")
    .trim();

  const filterDescParts = [
    categoryPart,
    typePart,
    filters.search
      ? lang === "fa"
        ? `جستجوی ${filters.search}`
        : `search: ${filters.search}`
      : "",
  ]
    .filter(Boolean)
    .join(lang === "fa" ? "، " : ", ");

  return {
    title: formatLocalizedSeoTitle(titleCore, lang),
    description: filterDescParts
      ? interpolateTemplate(templates.filteredDescription, {
          filters: filterDescParts,
        })
      : academyPage.description,
    path: buildAcademyListPath(filters),
    h1: titleCore,
  };
}
