import { TemplateSampleSetting } from "@/user-management/services/TemplateConfiguration/types/templateTypes";
import { parseCSSDeclarations } from "./cssConversion";

export const DEFAULT_LETTER_FONT_FAMILY_AM =
  "'Visual Geez Unicode', 'Visual Geez', serif";
export const DEFAULT_LETTER_FONT_FAMILY_EN =
  "'Times New Roman', Times, serif";
export const DEFAULT_LETTER_FONT_SIZE = "12pt";

const LIST_FORMATTING_PROPERTY_KEYS = new Set([
  "list-style",
  "list-style-type",
  "list-style-image",
  "list-style-position",
]);

export function getDefaultLetterFontFamily(language: "am" | "en"): string {
  return language === "am"
    ? DEFAULT_LETTER_FONT_FAMILY_AM
    : DEFAULT_LETTER_FONT_FAMILY_EN;
}

export function getDefaultLetterFontSize(): string {
  return DEFAULT_LETTER_FONT_SIZE;
}

function collectSettingPropertyKeys(
  setting: Pick<TemplateSampleSetting, "value" | "templateSettingValues">,
): Set<string> {
  const keys = new Set<string>();

  setting.templateSettingValues?.forEach((entry) => {
    if (entry.value && typeof entry.value === "object") {
      Object.keys(entry.value).forEach((key) => keys.add(key));
    }
  });

  if (
    typeof setting.value === "object" &&
    setting.value !== null &&
    !Array.isArray(setting.value)
  ) {
    Object.keys(setting.value).forEach((key) => keys.add(key));
  } else if (typeof setting.value === "string" && setting.value.trim()) {
    parseCSSDeclarations(setting.value).forEach(([key]) => keys.add(key));
  }

  return keys;
}

/** True when the setting schema includes list-related CSS properties. */
export function settingSupportsListFormatting(
  setting: Pick<TemplateSampleSetting, "value" | "templateSettingValues">,
): boolean {
  const keys = collectSettingPropertyKeys(setting);
  for (const key of LIST_FORMATTING_PROPERTY_KEYS) {
    if (keys.has(key)) return true;
  }
  return false;
}

export function isFontSetting(code: string): boolean {
  return code.trim().toLowerCase() === "letter-fonts";
}
