import { normalizeLanguage, type AppLanguage } from "@/i18n/language";
import DOMPurify from "dompurify";

const KEY_LEGACY = "frontend.play_rules_html";
const KEY_ZH = "frontend.play_rules_html_zh";
const KEY_EN = "frontend.play_rules_html_en";
const KEY_NE = "frontend.play_rules_html_ne";

type SettingItem = { key: string; value: unknown };

function sanitizeHtml(html: string | null): string | null {
  if (!html) return html;

  return DOMPurify.sanitize(html, {
    USE_PROFILES: { html: true },
    FORBID_TAGS: [
      "script",
      "style",
      "iframe",
      "object",
      "embed",
      "form",
      "input",
      "button",
      "textarea",
      "select",
      "option",
      "link",
      "meta",
      "base",
    ],
    FORBID_ATTR: ["style"],
    ALLOW_DATA_ATTR: false,
  });
}

function asNonEmptyString(value: unknown): string | null {
  if (typeof value !== "string") {
    return null;
  }
  const trimmed = value.trim();
  return trimmed === "" ? null : trimmed;
}

/** 从 public settings 列表中按玩家语言选取玩法规则 HTML */
export function resolvePlayRulesHtml(
  items: SettingItem[],
  language: string | undefined,
): string | null {
  const kv = new Map(items.map((item) => [item.key, item.value]));
  const legacy = asNonEmptyString(kv.get(KEY_LEGACY));
  const zh = asNonEmptyString(kv.get(KEY_ZH));
  const en = asNonEmptyString(kv.get(KEY_EN));
  const ne = asNonEmptyString(kv.get(KEY_NE));

  const lang: AppLanguage = normalizeLanguage(language);

  if (lang === "zh") {
    return sanitizeHtml(zh ?? legacy);
  }
  if (lang === "ne") {
    return sanitizeHtml(ne ?? en ?? zh ?? legacy);
  }
  return sanitizeHtml(en ?? zh ?? legacy);
}
