<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';

import { Crepe } from '@milkdown/crepe';
import { editorStateCtx, editorViewCtx } from '@milkdown/kit/core';
import { replaceAll } from '@milkdown/kit/utils';

import {
  hasEquivalentMarkdownSemantics,
  normalizeLiveMarkdownUpdate,
} from './markdown-fidelity';
import {
  isSafeMarkdownLinkHref,
  resolveSafeExternalMarkdownImageUrl,
} from './markdown-security';
import { installFrontmatter } from './milkdown-frontmatter';

import '@milkdown/crepe/theme/common/style.css';

const props = withDefaults(
  defineProps<{
    modelValue: string;
    placeholder?: string;
    readonly?: boolean;
    resolveImageUrl?: (url: string) => Promise<string> | string;
    uploadImage?: (file: File) => Promise<string>;
  }>(),
  {
    placeholder: '输入 Skill 指令…',
    readonly: false,
    resolveImageUrl: undefined,
    uploadImage: undefined,
  },
);

const emit = defineEmits<{
  error: [error: Error];
  fidelityLoss: [];
  frontmatterActivate: [];
  linkClick: [href: string];
  ready: [];
  save: [];
  'update:modelValue': [value: string];
}>();

const hostRef = ref<HTMLElement>();
const crepeRef = shallowRef<Crepe>();
const loading = ref(true);
const failed = ref(false);
const fidelityLoss = ref(false);
let destroyed = false;
let hasUserEdited = false;
let ready = false;
let syncingFromOutside = false;
let synchronizedMarkdown = '';
let domObserver: MutationObserver | undefined;

async function createEditor() {
  if (!hostRef.value) return;
  const initialModelValue = props.modelValue || '';
  loading.value = true;
  failed.value = false;
  fidelityLoss.value = false;
  const crepe = new Crepe({
    defaultValue: initialModelValue,
    featureConfigs: {
      [Crepe.Feature.ImageBlock]: {
        onUpload: async (file) => {
          if (props.uploadImage) return props.uploadImage(file);
          const error = new Error(
            '当前上下文不支持直接上传图片，请从资源文件树上传',
          );
          emit('error', error);
          throw error;
        },
        proxyDomURL: (url) =>
          props.resolveImageUrl
            ? props.resolveImageUrl(url)
            : resolveSafeExternalMarkdownImageUrl(url),
      },
      [Crepe.Feature.Placeholder]: {
        mode: 'block',
        text: props.placeholder,
      },
    },
    features: {
      [Crepe.Feature.AI]: false,
      [Crepe.Feature.ImageBlock]: true,
      [Crepe.Feature.Latex]: false,
      [Crepe.Feature.TopBar]: false,
    },
    root: hostRef.value,
  });
  installFrontmatter(crepe.editor);
  crepe.setReadonly(props.readonly);
  crepe.on((listener) => {
    listener.markdownUpdated((_ctx, markdown) => {
      const repairedListSpread = normalizeListSpreadAttributes(crepe);
      const editorMarkdown = repairedListSpread
        ? crepe.getMarkdown()
        : markdown;
      const nextMarkdown = normalizeLiveMarkdownUpdate(
        props.modelValue || '',
        editorMarkdown,
      );
      if (
        !ready ||
        fidelityLoss.value ||
        syncingFromOutside ||
        !hasUserEdited ||
        nextMarkdown === props.modelValue ||
        nextMarkdown === synchronizedMarkdown ||
        !hasMeaningfulMarkdownDifference(props.modelValue || '', nextMarkdown)
      ) {
        synchronizedMarkdown = nextMarkdown;
        return;
      }
      synchronizedMarkdown = nextMarkdown;
      emit('update:modelValue', nextMarkdown);
    });
  });
  try {
    await crepe.create();
    if (destroyed) {
      await crepe.destroy();
      return;
    }
    const latestModelValue = props.modelValue || '';
    if (latestModelValue !== initialModelValue) {
      syncingFromOutside = true;
      try {
        crepe.editor.action(replaceAll(latestModelValue, true));
      } finally {
        syncingFromOutside = false;
      }
    }
    normalizeListSpreadAttributes(crepe);
    synchronizedMarkdown = normalizeLiveMarkdownUpdate(
      latestModelValue,
      crepe.getMarkdown(),
    );
    if (
      hasMeaningfulMarkdownDifference(latestModelValue, synchronizedMarkdown)
    ) {
      reportFidelityLoss(crepe);
    }
    crepe.setReadonly(props.readonly || fidelityLoss.value);
    crepeRef.value = crepe;
    ready = true;
    emit('ready');
  } catch (error_) {
    failed.value = true;
    const error =
      error_ instanceof Error ? error_ : new Error('实时编辑器加载失败');
    emit('error', error);
    try {
      await crepe.destroy();
    } catch {
      // Best-effort cleanup after a partial editor initialization.
    }
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.modelValue,
  (value) => {
    const crepe = crepeRef.value;
    if (!crepe) return;
    const editorMarkdown = crepe.getMarkdown();
    const comparableMarkdown = normalizeLiveMarkdownUpdate(
      value || '',
      editorMarkdown,
    );
    if (comparableMarkdown === (value || '')) {
      synchronizedMarkdown = comparableMarkdown;
      return;
    }
    syncingFromOutside = true;
    hasUserEdited = false;
    try {
      crepe.editor.action(replaceAll(value || '', true));
      normalizeListSpreadAttributes(crepe);
      synchronizedMarkdown = crepe.getMarkdown();
      if (hasMeaningfulMarkdownDifference(value || '', synchronizedMarkdown)) {
        reportFidelityLoss(crepe);
      }
    } finally {
      syncingFromOutside = false;
    }
  },
);

watch(
  () => props.readonly,
  (value) => crepeRef.value?.setReadonly(value || fidelityLoss.value),
);

onMounted(createEditor);
onMounted(() => {
  hostRef.value?.addEventListener('click', handleLinkClick);
  hostRef.value?.addEventListener('click', handleFrontmatterActivate);
  hostRef.value?.addEventListener('beforeinput', markUserEdited);
  hostRef.value?.addEventListener('drop', markUserEdited);
  hostRef.value?.addEventListener('keydown', handleKeydown);
  hostRef.value?.addEventListener('paste', markUserEdited);
  if (hostRef.value) {
    domObserver = new MutationObserver(sanitizeRenderedLinks);
    domObserver.observe(hostRef.value, {
      attributeFilter: ['href'],
      attributes: true,
      childList: true,
      subtree: true,
    });
    sanitizeRenderedLinks();
  }
});
onBeforeUnmount(async () => {
  destroyed = true;
  ready = false;
  hostRef.value?.removeEventListener('click', handleLinkClick);
  hostRef.value?.removeEventListener('click', handleFrontmatterActivate);
  hostRef.value?.removeEventListener('beforeinput', markUserEdited);
  hostRef.value?.removeEventListener('drop', markUserEdited);
  hostRef.value?.removeEventListener('keydown', handleKeydown);
  hostRef.value?.removeEventListener('paste', markUserEdited);
  domObserver?.disconnect();
  domObserver = undefined;
  await crepeRef.value?.destroy();
  crepeRef.value = undefined;
});

function handleLinkClick(event: MouseEvent) {
  const target = event.target as HTMLElement | null;
  const anchor = target?.closest<HTMLAnchorElement>('a[href]');
  if (!anchor) return;
  const href = anchor.getAttribute('href') || '';
  if (!href || !isSafeMarkdownLinkHref(href)) {
    event.preventDefault();
    emit('error', new Error('该链接协议不受支持'));
    return;
  }
  if (/^https?:\/\//i.test(href)) {
    anchor.rel = 'noopener noreferrer';
    anchor.target = '_blank';
    return;
  }
  if (/^(?:mailto:|#)/i.test(href)) return;
  event.preventDefault();
  emit('linkClick', href);
}

function handleFrontmatterActivate(event: Event) {
  const target = event.target as HTMLElement | null;
  if (!target) return;
  const frontmatter = target.closest<HTMLElement>('.milkdown-frontmatter');
  if (!frontmatter) return;
  event.preventDefault();
  emit('frontmatterActivate');
}

function markUserEdited() {
  hasUserEdited = true;
}

function sanitizeRenderedLinks() {
  hostRef.value
    ?.querySelectorAll<HTMLAnchorElement>('a[href]')
    .forEach((anchor) => {
      const href = anchor.getAttribute('href') || '';
      if (!isSafeMarkdownLinkHref(href)) {
        anchor.removeAttribute('href');
        anchor.setAttribute('aria-disabled', 'true');
        return;
      }
      if (/^https?:\/\//i.test(href)) {
        anchor.rel = 'noopener noreferrer';
        anchor.target = '_blank';
      }
    });
}

function handleKeydown(event: KeyboardEvent) {
  if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
    event.preventDefault();
    if (!props.readonly) emit('save');
  }
}

function reportFidelityLoss(crepe: Crepe) {
  if (fidelityLoss.value) return;
  fidelityLoss.value = true;
  crepe.setReadonly(true);
  emit('fidelityLoss');
}

function hasMeaningfulMarkdownDifference(source: string, normalized: string) {
  return !hasEquivalentMarkdownSemantics(source, normalized);
}

function normalizeListSpreadAttributes(crepe: Crepe) {
  let repaired = false;
  crepe.editor.action((ctx) => {
    const state = ctx.get(editorStateCtx);
    const transaction = state.tr;
    let changed = false;
    state.doc.descendants((node, position) => {
      if (
        !['bullet_list', 'list_item', 'ordered_list'].includes(node.type.name)
      ) {
        return;
      }
      const spread = node.attrs.spread;
      if (spread !== 'true' && spread !== 'false') return;
      transaction.setNodeMarkup(
        position,
        undefined,
        { ...node.attrs, spread: spread === 'true' },
        node.marks,
      );
      changed = true;
    });
    if (changed) {
      repaired = true;
      transaction.setMeta('addToHistory', false);
      ctx.get(editorViewCtx).dispatch(transaction);
    }
  });
  return repaired;
}
</script>

<template>
  <div class="easyflow-markdown-live-editor">
    <div
      ref="hostRef"
      class="easyflow-markdown-live-editor__host"
      role="region"
      aria-label="Markdown 实时编辑器"
    ></div>
    <div
      v-if="loading"
      class="easyflow-markdown-live-editor__state"
      aria-live="polite"
    >
      正在加载编辑器…
    </div>
    <div
      v-else-if="failed"
      class="easyflow-markdown-live-editor__state is-error"
      role="alert"
    >
      实时编辑器加载失败，请切换到源码模式继续编辑。
    </div>
    <div
      v-else-if="fidelityLoss"
      class="easyflow-markdown-live-editor__state is-error"
      role="alert"
    >
      当前内容包含实时编辑器无法保真处理的语法，请切换到源码模式。
    </div>
  </div>
</template>

<style scoped>
.easyflow-markdown-live-editor {
  position: relative;
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: auto;
  background: hsl(var(--surface-panel));
}

.easyflow-markdown-live-editor__host {
  flex: 1;
  width: 100%;
  min-height: 100%;
}

.easyflow-markdown-live-editor__state {
  position: absolute;
  inset: 0;
  display: grid;
  place-items: center;
  color: hsl(var(--text-muted));
  background: hsl(var(--surface-panel) / 92%);
}

.easyflow-markdown-live-editor__state.is-error {
  color: hsl(var(--destructive));
}

.easyflow-markdown-live-editor :deep(.milkdown) {
  --crepe-color-background: hsl(var(--surface-panel));
  --crepe-color-on-background: hsl(var(--foreground));
  --crepe-color-surface: hsl(var(--surface-subtle));
  --crepe-color-surface-low: hsl(var(--surface-contrast-soft));
  --crepe-color-on-surface: hsl(var(--foreground));
  --crepe-color-on-surface-variant: hsl(var(--text-muted));
  --crepe-color-outline: hsl(var(--line-subtle));
  --crepe-color-primary: hsl(var(--primary));
  --crepe-color-secondary: hsl(var(--nav-item-active));
  --crepe-color-on-secondary: hsl(var(--nav-item-active-foreground));
  --crepe-color-inverse: hsl(var(--foreground));
  --crepe-color-on-inverse: hsl(var(--surface-panel));
  --crepe-color-inline-code: hsl(var(--destructive));
  --crepe-color-error: hsl(var(--destructive));
  --crepe-color-hover: hsl(var(--nav-item-hover));
  --crepe-color-selected: hsl(var(--nav-item-active));
  --crepe-color-inline-area: hsl(var(--surface-contrast-soft));
  --crepe-font-default: var(--font-family);
  --crepe-font-title: var(--font-family);
  --crepe-font-code:
    ui-monospace, sfmono-regular, menlo, monaco, consolas, monospace;
  --crepe-shadow-1: var(--shadow-subtle);
  --crepe-shadow-2: var(--shadow-toolbar);

  min-height: 100%;
  color: hsl(var(--foreground));
  background: transparent;
}

.easyflow-markdown-live-editor :deep(.ProseMirror) {
  box-sizing: border-box;
  width: min(100%, 960px);
  min-height: 100%;
  padding: var(--space-8) clamp(var(--space-4), 5vw, 72px) 64px;
  margin: 0 auto;
  font-size: 15px;
  line-height: 1.76;
  color: hsl(var(--text-strong));
  background: transparent;
  box-shadow: none;
}

.easyflow-markdown-live-editor :deep(.ProseMirror:focus-visible) {
  outline: none;
  box-shadow: inset 3px 0 hsl(var(--primary) / 28%);
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter) {
  box-sizing: border-box;
  margin-block: var(--space-4);
  padding: var(--space-3) var(--space-4);
  cursor: pointer;
  background: hsl(var(--surface-subtle));
  border: 0;
  border-left: 3px solid hsl(var(--primary) / 36%);
  border-radius: 0;
  transition:
    border-color var(--motion-duration-fast) var(--motion-ease-standard),
    background-color var(--motion-duration-fast) var(--motion-ease-standard);
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter:hover),
.easyflow-markdown-live-editor :deep(.milkdown-frontmatter:focus-visible) {
  background: hsl(var(--surface-contrast-soft));
  border-left-color: hsl(var(--primary));
  outline: none;
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter__title) {
  margin-bottom: var(--space-1);
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.02em;
  color: hsl(var(--text-muted));
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter__code) {
  margin: 0;
  padding: 0;
  font-family: ui-monospace, sfmono-regular, menlo, monaco, consolas, monospace;
  font-size: 12.5px;
  line-height: 1.65;
  color: hsl(var(--text-strong));
  white-space: pre-wrap;
  word-break: break-word;
  background: transparent;
  border: 0;
}

.easyflow-markdown-live-editor :deep(a) {
  color: hsl(var(--primary));
  text-underline-offset: 3px;
}

.easyflow-markdown-live-editor :deep(img) {
  max-width: 100%;
  border-radius: var(--radius);
}

.easyflow-markdown-live-editor :deep(h1),
.easyflow-markdown-live-editor :deep(h2),
.easyflow-markdown-live-editor :deep(h3),
.easyflow-markdown-live-editor :deep(h4) {
  color: hsl(var(--text-strong));
  letter-spacing: -0.012em;
}

.easyflow-markdown-live-editor :deep(h1) {
  padding-bottom: var(--space-3);
  margin-top: 0;
  font-size: 28px;
  border-bottom: 1px solid hsl(var(--line-subtle));
}

.easyflow-markdown-live-editor :deep(h2) {
  margin-top: var(--space-8);
  font-size: 21px;
}

.easyflow-markdown-live-editor :deep(h3) {
  margin-top: var(--space-6);
  font-size: 17px;
}

.easyflow-markdown-live-editor :deep(p),
.easyflow-markdown-live-editor :deep(ul),
.easyflow-markdown-live-editor :deep(ol),
.easyflow-markdown-live-editor :deep(blockquote),
.easyflow-markdown-live-editor :deep(pre),
.easyflow-markdown-live-editor :deep(table) {
  margin-block: var(--space-4);
}

.easyflow-markdown-live-editor :deep(blockquote) {
  padding: var(--space-2) var(--space-4);
  color: hsl(var(--text-muted));
  background: hsl(var(--surface-subtle));
  border-left: 3px solid hsl(var(--primary) / 48%);
}

.easyflow-markdown-live-editor :deep(pre) {
  padding: var(--space-4);
  overflow: auto;
  background: hsl(var(--surface-contrast-soft));
  border: 1px solid hsl(var(--line-subtle));
  border-radius: var(--radius-control);
}

.easyflow-markdown-live-editor :deep(code) {
  font-family: ui-monospace, sfmono-regular, menlo, monaco, consolas, monospace;
  font-size: 0.9em;
}

.easyflow-markdown-live-editor :deep(table) {
  width: 100%;
  border-collapse: collapse;
}

.easyflow-markdown-live-editor :deep(th),
.easyflow-markdown-live-editor :deep(td) {
  padding: var(--space-2) var(--space-3);
  text-align: left;
  border: 1px solid hsl(var(--line-subtle));
}

.easyflow-markdown-live-editor :deep(th) {
  font-weight: 600;
  background: hsl(var(--surface-subtle));
}

@supports not (color: color-mix(in srgb, red, blue)) {
  .easyflow-markdown-live-editor :deep(.ProseMirror code),
  .easyflow-markdown-live-editor :deep(.ProseMirror pre) {
    background: var(--crepe-color-inline-area);
  }

  .easyflow-markdown-live-editor :deep(.ProseMirror hr),
  .easyflow-markdown-live-editor :deep(.milkdown-toolbar .divider),
  .easyflow-markdown-live-editor :deep(.milkdown-top-bar .top-bar-divider) {
    background-color: var(--crepe-color-outline);
  }

  .easyflow-markdown-live-editor
    :deep(.ProseMirror hr.ProseMirror-selectednode) {
    background-color: var(--crepe-color-selected);
  }

  .easyflow-markdown-live-editor :deep(.milkdown-slash-menu .tab-group),
  .easyflow-markdown-live-editor :deep(.milkdown-table-block td),
  .easyflow-markdown-live-editor :deep(.milkdown-table-block th),
  .easyflow-markdown-live-editor :deep(.milkdown-top-bar) {
    border-color: var(--crepe-color-outline);
  }

  .easyflow-markdown-live-editor
    :deep(.milkdown-slash-menu .menu-groups .menu-group h6),
  .easyflow-markdown-live-editor
    :deep(.milkdown-code-block .preview-panel .preview-label) {
    color: var(--crepe-color-on-surface);
  }

  .easyflow-markdown-live-editor :deep(.crepe-placeholder::before),
  .easyflow-markdown-live-editor
    :deep(.milkdown-image-block .image-edit .link-importer .placeholder),
  .easyflow-markdown-live-editor
    :deep(.milkdown-image-inline .link-importer .placeholder) {
    color: var(--crepe-color-on-background);
  }

  .easyflow-markdown-live-editor
    :deep(.milkdown-image-block.selected > .image-edit::before),
  .easyflow-markdown-live-editor
    :deep(.milkdown-image-block.selected > .image-wrapper::before) {
    background: var(--crepe-color-selected);
  }

  .easyflow-markdown-live-editor :deep(.crepe-drop-cursor) {
    background-color: var(--crepe-color-outline);
  }
}

@media (max-width: 720px) {
  .easyflow-markdown-live-editor :deep(.ProseMirror) {
    padding: var(--space-6) var(--space-4) var(--space-8);
    box-shadow: none;
  }
}

@media (prefers-reduced-motion: reduce) {
  .easyflow-markdown-live-editor :deep(*) {
    scroll-behavior: auto !important;
    transition-duration: 0.01ms !important;
  }
}
</style>
