import type { SupportedLanguage } from "../locales";

const SPANISH_DIACRITICS = /[ñáéíóúüàèìòù¿¡]/i;

type SubjectLang = "es" | "en" | "unknown";

function classifySubject(subject: string): SubjectLang {
  const s = subject.trim();
  if (!s) return "unknown";

  if (SPANISH_DIACRITICS.test(s)) return "es";

  const lower = s.toLowerCase();

  if (
    /translations into english/i.test(lower) ||
    /\binto english\b/i.test(lower) ||
    /\bfamily life\b/i.test(lower) ||
    /\bhistorical fiction\b/i.test(lower) ||
    /\blove stories\b/i.test(lower) ||
    /\bcourtship\b/i.test(lower) ||
    /\bnovels\b/.test(lower) ||
    (/\bfiction\b/i.test(lower) && !/ficci/i.test(lower))
  ) {
    return "en";
  }

  if (
    /\bvida familiar\b/i.test(lower) ||
    /\bhistorias de amor\b/i.test(lower) ||
    /\bficci[oó].*hist[oó]rica\b/i.test(lower) ||
    /\bnovela\b/i.test(lower) ||
    (/\b(de|del)\b/i.test(lower) && /\b(el|la|los|las|amor|vida|historias)\b/i.test(lower))
  ) {
    return "es";
  }

  if (/\b(the|of|into|and)\b/i.test(lower)) return "en";
  if (/\b(de|del|la|las|los|el)\b/i.test(lower)) return "es";

  if (lower === "novela") return "es";
  if (lower === "novels") return "en";

  return "unknown";
}

export function filterSubjectsByLocale(subjects: string[], locale: SupportedLanguage): string[] {
  const want: SubjectLang = locale.startsWith("es") ? "es" : "en";
  const filtered = subjects.filter((subject) => {
    const lang = classifySubject(subject);
    if (lang === "unknown") return false;
    return lang === want;
  });
  return filtered.length > 0 ? filtered : subjects;
}
