/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck

export function normalizeEditorTagValue(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}

export function normalizeEditorTags(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const seen = new Set();
  return value
    .map((entry) => normalizeEditorTagValue(entry))
    .filter((entry) => {
      if (!entry) {
        return false;
      }
      const key = entry.toLocaleLowerCase();
      if (seen.has(key)) {
        return false;
      }
      seen.add(key);
      return true;
    })
    .sort((left, right) => left.localeCompare(right, undefined, { sensitivity: "base" }));
}

export function serializeEditorTags(value) {
  return JSON.stringify(normalizeEditorTags(value));
}

export function parseImportedEditorTags(rawValue) {
  const raw = String(rawValue || "").trim();
  if (!raw) {
    return [];
  }
  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return normalizeEditorTags(parsed);
    }
    if (typeof parsed === "string") {
      return normalizeEditorTags(
        parsed
          .split(/\r?\n|[,;|]/g)
          .map((entry) => String(entry || "").trim()),
      );
    }
  } catch {
    // Fall through to plain text parsing.
  }
  return normalizeEditorTags(
    raw
      .split(/\r?\n|[,;|]/g)
      .map((entry) => String(entry || "").trim()),
  );
}
