import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";

export type PostLinkKind = "pkg" | "project" | "billboard" | "shop" | "shopproduct" | "booking";

/** مارکر لینک داخل کپشن */
export const POST_LINK_TOKEN_REGEX =
  /\[\[(pkg|project|billboard|shop|shopproduct|booking):([a-f0-9]{24})\]\]([\s\S]*?)\[\[\/\1\]\]/gi;

/** @deprecated use POST_LINK_TOKEN_REGEX */
export const POST_PACKAGE_TOKEN_REGEX =
  /\[\[pkg:([a-f0-9]{24})\]\]([\s\S]*?)\[\[\/pkg\]\]/gi;

export interface SelectedPostLink {
  kind: PostLinkKind;
  _id: string;
  title: string;
}
const FA_LINK_LABELS = {
  pkg: "پکیج آموزشی",
  project: "پروژه",
  billboard: "بیلبورد",
  shop: "فروشگاه",
  shopproduct: "کالا",
  booking: "رزرو نوبت",
} as const;

const EN_LINK_LABELS = {
  pkg: "Training package",
  project: "Project",
  billboard: "Billboard",
  shop: "Shop",
  shopproduct: "Product",
  booking: "Booking",
} as const;

export function getPostLinkLabels(lang: AppLanguage = DEFAULT_LANGUAGE) {
  return lang === "en" ? EN_LINK_LABELS : FA_LINK_LABELS;
}

const ALL_LINK_LABELS = [
  ...Object.values(FA_LINK_LABELS),
  ...Object.values(EN_LINK_LABELS),
];

const LINK_LABEL_PATTERN = new RegExp(
  `^(${ALL_LINK_LABELS.map((label) => label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\s*:`
);

export function buildPostLinkPath(
  kind: PostLinkKind,
  id: string,
  title: string
) {
  const name = encodeURIComponent(title || kind);
  switch (kind) {
    case "pkg":
      return `/academy/${id}/${name}`;
    case "project":
      return `/projects/${id}/${name}`;
    case "billboard":
      return `/billboards/${id}/${name}`;
    case "shop":
      return `/shops/profile/${id}`;
    case "shopproduct":
      return `/shops/listing/${id}`;
    case "booking":
      return `/booking/${id}`;
  }
}

export function buildPostLinkCaptionToken(
  kind: PostLinkKind,
  id: string,
  title: string
) {
  return `[[${kind}:${id}]]${title.trim()}[[/${kind}]]`;
}

/** خط اول کپشن — برچسب + لینک‌های قابل کلیک */
export function buildPostLinkCaptionHeader(
  links: Array<SelectedPostLink | null | undefined>,
  lang: AppLanguage = DEFAULT_LANGUAGE
) {
  const list = links.filter((l): l is SelectedPostLink => Boolean(l?._id));
  if (!list.length) return "";

  const linkLabels = getPostLinkLabels(lang);
  const groups: Record<PostLinkKind, SelectedPostLink[]> = {
    pkg: [],
    project: [],
    billboard: [],
    shop: [],
    shopproduct: [],
    booking: [],
  };
  for (const link of list) {
    groups[link.kind].push(link);
  }

  const parts: string[] = [];
  (["pkg", "project", "billboard", "shop", "shopproduct", "booking"] as const).forEach((kind) => {
    if (!groups[kind].length) return;
    const tokens = groups[kind]
      .map((l) => buildPostLinkCaptionToken(l.kind, l._id, l.title))
      .join(" – ");
    parts.push(`${linkLabels[kind]}: ${tokens}`);
  });

  return parts.join("\n");
}

/** @deprecated */
export function buildCourseDetailPath(courseId: string, courseName: string) {
  return buildPostLinkPath("pkg", courseId, courseName);
}

/** @deprecated */
export function buildPostPackageCaptionToken(
  courseId: string,
  courseName: string
) {
  return buildPostLinkCaptionToken("pkg", courseId, courseName);
}

export function stripPostLinkTokens(text: string) {
  return text.replace(POST_LINK_TOKEN_REGEX, "$3");
}

/** خطوط حاوی لینک پکیج/پروژه/بیلبورد را از بدنه جدا می‌کند */
export function splitCaptionBodyAndLinks(caption: string) {
  if (!caption?.trim()) {
    return { body: "", links: "" };
  }

  const bodyLines: string[] = [];
  const linkLines: string[] = [];

  for (const line of caption.split("\n")) {
    const trimmed = line.trim();
    if (!trimmed) continue;

    const hasLinkToken = new RegExp(POST_LINK_TOKEN_REGEX.source, "i").test(
      line
    );
    POST_LINK_TOKEN_REGEX.lastIndex = 0;

    const hasLinkLabel = LINK_LABEL_PATTERN.test(trimmed);

    if (hasLinkToken || hasLinkLabel) {
      if (
        trimmed.includes(" – ") &&
        (trimmed.match(new RegExp(ALL_LINK_LABELS.join("|"), "g")) || []).length > 1
      ) {
        trimmed.split(" – ").forEach((part) => {
          if (part.trim()) linkLines.push(part.trim());
        });
      } else {
        linkLines.push(line);
      }
    } else {
      bodyLines.push(line);
    }
  }

  return {
    body: bodyLines.join("\n"),
    links: linkLines.join("\n"),
  };
}

/** بدنه کپشن + لینک‌ها در انتها (برای پست‌های قدیمی که لینک اول بود) */
export function reorderCaptionLinksToEnd(caption: string) {
  const { body, links } = splitCaptionBodyAndLinks(caption);
  return [body, links].filter(Boolean).join("\n");
}

/** @deprecated */
export function stripPostPackageTokens(text: string) {
  return stripPostLinkTokens(text);
}

/** @deprecated — use buildPostLinkCaptionHeader */
export function buildPostLinkCaptionTokens(
  links: Array<SelectedPostLink | null | undefined>
) {
  return links
    .filter((link): link is SelectedPostLink => Boolean(link?._id))
    .map((link) => buildPostLinkCaptionToken(link.kind, link._id, link.title));
}

export function captionNeedsTruncation(caption: string, maxLen: number) {
  const { body } = splitCaptionBodyAndLinks(reorderCaptionLinksToEnd(caption));
  const plain = stripPostLinkTokens(body).replace(/\s+/g, " ").trim();
  return plain.length > maxLen;
}

/** آستانه «بیشتر» در فید پست‌ها — مثل اینستاگرام */
export const POST_CAPTION_FIRST_LINE_MORE_AT = 20;

/** نمایش «بیشتر» در صفحه پست‌ها: خط دوم یا ۲۰+ کاراکتر در خط اول */
export function postCaptionNeedsMore(body: string): boolean {
  if (!body?.trim()) return false;

  const plain = stripPostLinkTokens(body);
  const lines = plain.split("\n");
  const firstLine = (lines[0] ?? "").replace(/\s+/g, " ").trim();
  const hasSecondLine = lines
    .slice(1)
    .some((line) => line.replace(/\s+/g, " ").trim().length > 0);

  if (hasSecondLine) return true;
  return firstLine.length >= POST_CAPTION_FIRST_LINE_MORE_AT;
}

/** متن کوتاه‌شده برای حالت جمع‌شده — همراه «بیشتر» در همان خط */
export function getCollapsedCaptionPreview(body: string): string {
  if (!body?.trim() || !postCaptionNeedsMore(body)) return body;

  const plain = stripPostLinkTokens(body);
  const plainLines = plain.split("\n");
  const firstPlainLine = (plainLines[0] ?? "").replace(/\s+/g, " ").trim();
  const hasSecondLine = plainLines
    .slice(1)
    .some((line) => line.replace(/\s+/g, " ").trim().length > 0);

  const firstBodyLine = body.split("\n")[0] ?? body;

  if (firstPlainLine.length <= POST_CAPTION_FIRST_LINE_MORE_AT) {
    return hasSecondLine ? firstBodyLine : body;
  }

  return firstPlainLine.slice(0, POST_CAPTION_FIRST_LINE_MORE_AT).trimEnd();
}

export function truncateCaptionPlain(caption: string, maxLen: number) {
  const reordered = reorderCaptionLinksToEnd(caption);
  const { body, links } = splitCaptionBodyAndLinks(reordered);
  const plain = stripPostLinkTokens(body);
  if (plain.length <= maxLen) return reordered;

  const truncatedBody = plain.slice(0, maxLen);
  return links ? `${truncatedBody}\n${links}` : truncatedBody;
}
