<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 { TextSelection } from '@milkdown/kit/prose/state';
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: '输入 Markdown 内容…',
    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.BlockEdit]: {
        textGroup: {
          label: '文本',
          text: { label: '正文' },
          h1: { label: '一级标题' },
          h2: { label: '二级标题' },
          h3: { label: '三级标题' },
          h4: { label: '四级标题' },
          h5: { label: '五级标题' },
          h6: { label: '六级标题' },
          quote: { label: '引用' },
          divider: { label: '分隔线' },
        },
        listGroup: {
          label: '列表',
          bulletList: { label: '无序列表' },
          orderedList: { label: '有序列表' },
          taskList: { label: '任务列表' },
        },
        advancedGroup: {
          label: '更多',
          image: { label: '图片' },
          codeBlock: { label: '代码块' },
          table: { label: '表格' },
          math: { label: '公式' },
        },
      },
      [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', handleBlockMenuClick);
  hostRef.value?.addEventListener('click', handleLinkClick);
  hostRef.value?.addEventListener('click', handleFrontmatterActivate);
  hostRef.value?.addEventListener('beforeinput', prepareUserEdit, true);
  hostRef.value?.addEventListener('drop', markUserEdited);
  hostRef.value?.addEventListener('keydown', handleKeydown, true);
  hostRef.value?.addEventListener('paste', prepareUserEdit, true);
  hostRef.value?.addEventListener('pointerup', prepareBlockMenuEdit, true);
  if (hostRef.value) {
    domObserver = new MutationObserver(refreshRenderedContent);
    domObserver.observe(hostRef.value, {
      attributeFilter: ['href'],
      attributes: true,
      childList: true,
      subtree: true,
    });
    refreshRenderedContent();
  }
});
onBeforeUnmount(async () => {
  destroyed = true;
  ready = false;
  hostRef.value?.removeEventListener('click', handleBlockMenuClick);
  hostRef.value?.removeEventListener('click', handleLinkClick);
  hostRef.value?.removeEventListener('click', handleFrontmatterActivate);
  hostRef.value?.removeEventListener('beforeinput', prepareUserEdit, true);
  hostRef.value?.removeEventListener('drop', markUserEdited);
  hostRef.value?.removeEventListener('keydown', handleKeydown, true);
  hostRef.value?.removeEventListener('paste', prepareUserEdit, true);
  hostRef.value?.removeEventListener('pointerup', prepareBlockMenuEdit, true);
  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 handleBlockMenuClick(event: MouseEvent) {
  const target = event.target as HTMLElement | null;
  const trigger = target?.closest<HTMLElement>(
    '.milkdown-block-handle .operation-item:last-child',
  );
  if (!trigger) return;
  event.preventDefault();
  event.stopPropagation();
  activateBlockMenu(trigger);
}

function activateBlockMenu(trigger: HTMLElement) {
  trigger.parentElement
    ?.querySelector<HTMLElement>('.operation-item:first-child')
    ?.dispatchEvent(
      new Event('pointerup', { bubbles: true, cancelable: true }),
    );
}

function markUserEdited() {
  hasUserEdited = true;
}

function prepareBlockMenuEdit(event: PointerEvent) {
  const target = event.target as HTMLElement | null;
  if (
    target?.closest(
      '.milkdown-block-handle .operation-item, .milkdown-slash-menu .menu-group li',
    )
  ) {
    markUserEdited();
  }
}

/**
 * Redirects typing and paste operations after the immutable frontmatter atom.
 * ProseMirror otherwise allows a gap selection before the first atom, which
 * would serialize body content ahead of the required YAML metadata block.
 */
function prepareUserEdit() {
  markUserEdited();
  const crepe = crepeRef.value;
  if (!crepe) return;
  crepe.editor.action((ctx) => {
    const state = ctx.get(editorStateCtx);
    const firstNode = state.doc.firstChild;
    if (
      firstNode?.type.name !== 'frontmatter' ||
      state.selection.from > firstNode.nodeSize
    ) {
      return;
    }
    const view = ctx.get(editorViewCtx);
    const bodySelection = TextSelection.near(
      state.doc.resolve(firstNode.nodeSize),
      1,
    );
    view.dispatch(state.tr.setSelection(bodySelection));
  });
}

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 refreshRenderedContent() {
  sanitizeRenderedLinks();
  enhanceBlockMenu();
}

function enhanceBlockMenu() {
  const host = hostRef.value;
  if (!host) return;
  host
    .querySelectorAll<HTMLElement>(
      '.milkdown-block-handle .operation-item:first-child',
    )
    .forEach((hiddenAddButton) => {
      hiddenAddButton.setAttribute('aria-hidden', 'true');
      hiddenAddButton.setAttribute('tabindex', '-1');
    });
  host
    .querySelectorAll<HTMLElement>(
      '.milkdown-block-handle .operation-item:last-child',
    )
    .forEach((trigger) => {
      trigger.setAttribute('aria-label', '打开内容块菜单');
      trigger.setAttribute('role', 'button');
      trigger.setAttribute('tabindex', '0');
      trigger.setAttribute('title', '打开内容块菜单');
    });
  host.querySelectorAll<HTMLElement>('.milkdown-slash-menu').forEach((menu) => {
    menu.setAttribute('aria-label', '内容块菜单');
  });
}

function handleKeydown(event: KeyboardEvent) {
  const target = event.target as HTMLElement | null;
  const blockMenuTrigger = target?.closest<HTMLElement>(
    '.milkdown-block-handle .operation-item:last-child',
  );
  if (blockMenuTrigger && (event.key === 'Enter' || event.key === ' ')) {
    event.preventDefault();
    activateBlockMenu(blockMenuTrigger);
    return;
  }
  if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') {
    event.preventDefault();
    if (!props.readonly) emit('save');
    return;
  }
  prepareUserEdit();
}

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;
  scrollbar-gutter: stable;
  background: hsl(var(--surface-panel));
}

.easyflow-markdown-live-editor__host {
  flex: 1;
  width: 100%;
  min-width: 0;
  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(--nav-item-active-foreground));
  --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));
  caret-color: hsl(var(--primary));
  background: transparent;
  box-shadow: none;
}

.easyflow-markdown-live-editor :deep(.ProseMirror::selection),
.easyflow-markdown-live-editor :deep(.ProseMirror *::selection) {
  color: hsl(var(--text-strong));
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor :deep(.ProseMirror .ProseMirror-selectednode) {
  outline: 2px solid hsl(var(--primary) / 64%);
  outline-offset: 2px;
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor
  :deep(.ProseMirror img.ProseMirror-selectednode) {
  outline-color: hsl(var(--primary));
  background: transparent;
}

.easyflow-markdown-live-editor :deep(.ProseMirror-focused) {
  --prosemirror-virtual-cursor-color: hsl(var(--primary));
}

.easyflow-markdown-live-editor :deep(.ProseMirror-gapcursor::after) {
  border-top: 2px solid hsl(var(--primary));
}

.easyflow-markdown-live-editor :deep(.crepe-drop-cursor) {
  height: 2px !important;
  background-color: hsl(var(--primary)) !important;
  border-radius: var(--radius-pill);
  opacity: 0.9 !important;
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter) {
  box-sizing: border-box;
  padding: var(--space-3) var(--space-4);
  margin-block: var(--space-4);
  cursor: pointer;
  background: hsl(var(--surface-subtle));
  border: 1px solid hsl(var(--line-subtle));
  border-left: 3px solid hsl(var(--primary) / 58%);
  border-radius: var(--radius-control);
  transition:
    border-color var(--motion-duration-fast) var(--motion-ease-standard),
    background-color var(--motion-duration-fast) var(--motion-ease-standard),
    box-shadow 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));
}

.easyflow-markdown-live-editor :deep(.milkdown-frontmatter:focus-visible) {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 2px;
}

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

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

.easyflow-markdown-live-editor :deep(a) {
  font-weight: 520;
  color: hsl(var(--primary));
  text-decoration-thickness: 1px;
  text-underline-offset: 3px;
}

.easyflow-markdown-live-editor :deep(a:hover) {
  text-decoration-thickness: 2px;
}

.easyflow-markdown-live-editor :deep(a:focus-visible) {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 2px;
  border-radius: 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(strong) {
  font-weight: 680;
  color: hsl(var(--text-strong));
}

.easyflow-markdown-live-editor :deep(em) {
  color: hsl(var(--foreground));
}

.easyflow-markdown-live-editor :deep(del) {
  color: hsl(var(--text-muted));
  text-decoration-thickness: 1.5px;
}

.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(--foreground));
  background: hsl(var(--surface-subtle));
  border-left: 3px solid hsl(var(--primary) / 64%);
  border-radius: 0 var(--radius-control) var(--radius-control) 0;
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block),
.easyflow-markdown-live-editor
  :deep(.ProseMirror pre:not(.milkdown-frontmatter__code)) {
  padding: var(--space-4);
  overflow: auto;
  color: hsl(var(--text-strong));
  background: hsl(var(--surface-subtle));
  border: 1px solid hsl(var(--line-subtle));
  border-radius: var(--radius-control);
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block) {
  padding: var(--space-2) var(--space-4) var(--space-4);
  box-shadow: var(--shadow-subtle);
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block.selected) {
  outline: 2px solid hsl(var(--primary) / 64%);
  outline-offset: 1px;
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block .cm-editor),
.easyflow-markdown-live-editor :deep(.milkdown-code-block .cm-gutters) {
  color: hsl(var(--text-strong));
  background: hsl(var(--surface-subtle));
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block .cm-gutters) {
  color: hsl(var(--text-muted));
  border-right: 1px solid hsl(var(--line-subtle));
}

.easyflow-markdown-live-editor :deep(.milkdown-code-block .cm-cursor) {
  border-left: 2px solid hsl(var(--primary));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-code-block .cm-selectionBackground) {
  background: hsl(var(--nav-item-active)) !important;
}

.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(.ProseMirror :not(pre) > code) {
  display: inline;
  padding: 2px 5px;
  font-weight: 560;
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--surface-contrast-soft));
  border: 1px solid hsl(var(--line-subtle));
  border-radius: 5px;
}

.easyflow-markdown-live-editor :deep(ul > li::marker),
.easyflow-markdown-live-editor :deep(ol > li::marker) {
  font-weight: 600;
  color: hsl(var(--text-muted));
}

.easyflow-markdown-live-editor :deep(.milkdown-list-item-block .label-wrapper) {
  min-height: 26px;
  font-weight: 600;
  color: hsl(var(--text-muted));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-list-item-block .label-wrapper svg) {
  color: currentcolor;
  fill: currentcolor;
}

.easyflow-markdown-live-editor
  :deep(.milkdown-list-item-block .label-wrapper .label) {
  height: auto;
  padding-block: 0;
  line-height: 1.76;
}

.easyflow-markdown-live-editor
  :deep(
    .milkdown-list-item-block > .list-item > .children > [data-content-dom] > p
  ) {
  margin-block: 0;
}

.easyflow-markdown-live-editor
  :deep(
    .milkdown-list-item-block
      > .list-item
      > .children
      > [data-content-dom]
      > p
      + p
  ) {
  margin-top: var(--space-2);
}

.easyflow-markdown-live-editor :deep(hr) {
  height: 1px;
  padding: 0;
  margin-block: var(--space-6);
  background: hsl(var(--line-subtle));
}

.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));
}

.easyflow-markdown-live-editor :deep(.crepe-placeholder::before) {
  color: hsl(var(--text-muted));
  opacity: 0.82;
}

.easyflow-markdown-live-editor :deep(.milkdown-toolbar),
.easyflow-markdown-live-editor :deep(.milkdown-link-preview),
.easyflow-markdown-live-editor :deep(.milkdown-link-edit),
.easyflow-markdown-live-editor :deep(.milkdown-slash-menu),
.easyflow-markdown-live-editor :deep(.language-picker) {
  color: hsl(var(--foreground));
  background: hsl(var(--surface-elevated));
  border: 1px solid hsl(var(--line-subtle));
  border-radius: var(--radius-toolbar);
  box-shadow: var(--shadow-toolbar);
}

.easyflow-markdown-live-editor :deep(.milkdown-block-handle) {
  gap: 0;
}

.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:first-child) {
  display: none;
}

.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:last-child) {
  width: 30px;
  height: 30px;
  color: hsl(var(--text-muted));
  border-radius: var(--radius-control);
}

.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:last-child svg) {
  width: 20px;
  height: 20px;
  fill: currentcolor;
}

.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:last-child:hover),
.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:last-child:focus-visible) {
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-block-handle .operation-item:last-child:focus-visible) {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 2px;
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu) {
  min-width: 280px;
  max-width: min(320px, calc(100vw - var(--space-8)));
  background: hsl(var(--surface-elevated));
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .tab-group) {
  padding: var(--space-2) var(--space-2) 0;
  border-bottom-color: hsl(var(--line-subtle));
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .tab-group ul) {
  gap: var(--space-1);
  padding: var(--space-1) var(--space-2);
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .tab-group li) {
  padding: 6px var(--space-2);
  color: hsl(var(--text-muted));
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .tab-group li:hover) {
  color: hsl(var(--foreground));
  background: hsl(var(--nav-item-hover));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-slash-menu .tab-group li.selected) {
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-slash-menu .menu-groups .menu-group h6) {
  padding: 10px var(--space-2);
  color: hsl(var(--text-muted));
  text-transform: none;
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .menu-groups) {
  max-height: min(216px, 28vh);
  padding: 0 var(--space-2) var(--space-2);
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .menu-group li) {
  gap: var(--space-3);
  min-width: 248px;
  padding: 10px var(--space-2);
  color: hsl(var(--foreground));
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .menu-group li:hover),
.easyflow-markdown-live-editor
  :deep(.milkdown-slash-menu .menu-group li.hover) {
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor :deep(.milkdown-slash-menu .menu-group li svg) {
  color: hsl(var(--text-muted));
  fill: hsl(var(--text-muted));
}

.easyflow-markdown-live-editor
  :deep(.milkdown-slash-menu .menu-group li:hover svg),
.easyflow-markdown-live-editor
  :deep(.milkdown-slash-menu .menu-group li.hover svg) {
  color: hsl(var(--primary));
  fill: hsl(var(--primary));
}

.easyflow-markdown-live-editor :deep(.milkdown button),
.easyflow-markdown-live-editor :deep(.milkdown input) {
  color: hsl(var(--foreground));
  border-radius: var(--radius-control);
}

.easyflow-markdown-live-editor :deep(.milkdown button:hover),
.easyflow-markdown-live-editor :deep(.milkdown button:active) {
  color: hsl(var(--nav-item-active-foreground));
  background: hsl(var(--nav-item-active));
}

.easyflow-markdown-live-editor :deep(.milkdown button:focus-visible),
.easyflow-markdown-live-editor :deep(.milkdown input:focus-visible) {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 2px;
}

.easyflow-markdown-live-editor :deep(.milkdown button:disabled) {
  cursor: not-allowed;
  opacity: 0.5;
}

@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: hsl(var(--text-muted));
  }

  .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: hsl(var(--primary));
  }
}

@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>
