export type EditorHostKind =
  | "blocknote"
  | "leptos_tiptap_island"
  | "leptos_tiptap_iframe_debug";

export interface EditorHostConfig {
  kind: EditorHostKind;
}

export const DEFAULT_EDITOR_HOST_KIND: EditorHostKind = "leptos_tiptap_island";

export function normalizeEditorHostKind(
  value: unknown,
  fallback: EditorHostKind = DEFAULT_EDITOR_HOST_KIND,
): EditorHostKind {
  const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
  if (normalized === "blocknote") {
    return "blocknote";
  }
  if (
    normalized === "leptos_tiptap_runtime" ||
    normalized === "leptos_tiptap_inline" ||
    normalized === "leptos_tiptap"
  ) {
    return "leptos_tiptap_island";
  }
  // 说明：iframe 只保留给显式调试桥，不再混入正式 runtime 主链。
  if (
    normalized === "leptos_tiptap_iframe_debug" ||
    normalized === "leptos_tiptap_debug" ||
    normalized === "iframe_debug"
  ) {
    return "leptos_tiptap_iframe_debug";
  }
  // 说明：保留历史 query 值兼容；未显式声明 debug 时，一律回到正式 runtime host。
  return fallback;
}

export function resolveEditorHostKind(input: {
  override?: unknown;
  runtimeDefault?: unknown;
}): EditorHostKind {
  const runtimeDefault = normalizeEditorHostKind(
    input.runtimeDefault,
    DEFAULT_EDITOR_HOST_KIND,
  );
  const hasOverride =
    typeof input.override === "string" && input.override.trim().length > 0;
  if (hasOverride) {
    return normalizeEditorHostKind(input.override, runtimeDefault);
  }
  return runtimeDefault;
}

export function isLeptosTiptapHostKind(kind: EditorHostKind): boolean {
  return kind !== "blocknote";
}

export function getEditorHostKindFromEnv(value?: unknown): EditorHostKind {
  return normalizeEditorHostKind(value);
}

export function getEditorHostConfig(value?: unknown): EditorHostConfig {
  return { kind: getEditorHostKindFromEnv(value) };
}
