<script setup lang="ts">
import type { EditorLanguage } from './types';

import { computed, onBeforeUnmount, onMounted, ref } from 'vue';

import CodeEditor from './CodeEditor.vue';

const props = withDefaults(
  defineProps<{
    content: string;
    downloadMode?: 'emit' | 'local';
    filename?: string;
    hash?: string;
    highlight?: boolean;
    language?: EditorLanguage;
    size?: number;
  }>(),
  {
    filename: 'source.txt',
    downloadMode: 'local',
    hash: '',
    highlight: true,
    language: 'text',
    size: undefined,
  },
);

const emit = defineEmits<{
  download: [];
  error: [error: Error];
}>();

const editorRef = ref<InstanceType<typeof CodeEditor>>();
const fullscreen = ref(false);
const copied = ref(false);
let copiedTimer: number | undefined;
const sizeLabel = computed(() => {
  const bytes = props.size ?? new TextEncoder().encode(props.content).length;
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
});

async function copyContent() {
  try {
    await navigator.clipboard.writeText(props.content);
    copied.value = true;
    window.clearTimeout(copiedTimer);
    copiedTimer = window.setTimeout(() => (copied.value = false), 1600);
  } catch (error_) {
    copied.value = false;
    emit('error', error_ instanceof Error ? error_ : new Error('复制失败'));
  }
}

function downloadContent() {
  if (props.downloadMode === 'emit') {
    emit('download');
    return;
  }
  const url = URL.createObjectURL(
    new Blob([props.content], { type: 'text/plain;charset=utf-8' }),
  );
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = props.filename;
  try {
    anchor.click();
  } finally {
    URL.revokeObjectURL(url);
  }
}

function handleKeydown(event: KeyboardEvent) {
  if (event.key === 'Escape' && fullscreen.value) {
    event.preventDefault();
    fullscreen.value = false;
  }
}

onMounted(() => window.addEventListener('keydown', handleKeydown));
onBeforeUnmount(() => {
  window.clearTimeout(copiedTimer);
  window.removeEventListener('keydown', handleKeydown);
});
</script>

<template>
  <section
    class="easyflow-code-viewer"
    :class="{ 'is-fullscreen': fullscreen }"
    :aria-label="`${filename} 只读内容`"
  >
    <header class="easyflow-code-viewer__toolbar">
      <div class="easyflow-code-viewer__identity">
        <strong>{{ filename }}</strong>
        <span>{{ language }}</span>
        <span>{{ sizeLabel }}</span>
        <span v-if="hash" :title="hash">{{ hash.slice(0, 10) }}</span>
      </div>
      <div class="easyflow-code-viewer__actions">
        <button type="button" @click="editorRef?.openSearch()">搜索</button>
        <button type="button" @click="copyContent">
          <span aria-live="polite">{{ copied ? '已复制' : '复制' }}</span>
        </button>
        <button
          type="button"
          :aria-pressed="fullscreen"
          @click="fullscreen = !fullscreen"
        >
          {{ fullscreen ? '退出全屏' : '全屏' }}
        </button>
        <button type="button" @click="downloadContent">下载</button>
      </div>
    </header>
    <CodeEditor
      ref="editorRef"
      class="easyflow-code-viewer__editor"
      :language="highlight ? language : 'text'"
      :model-value="content"
      readonly
    />
  </section>
</template>

<style scoped>
.easyflow-code-viewer {
  display: flex;
  flex: 1;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
  background: hsl(var(--surface-panel));
}

.easyflow-code-viewer.is-fullscreen {
  position: fixed;
  inset: var(--space-4);
  z-index: var(--popup-z-index);
  border: 1px solid hsl(var(--line-subtle));
  border-radius: var(--radius-panel);
  box-shadow: var(--shadow-float);
}

.easyflow-code-viewer__toolbar {
  display: flex;
  gap: var(--space-4);
  align-items: center;
  justify-content: space-between;
  min-height: 48px;
  padding: 0 var(--space-4);
  border-bottom: 1px solid hsl(var(--line-subtle));
}

.easyflow-code-viewer__identity,
.easyflow-code-viewer__actions {
  display: flex;
  gap: var(--space-2);
  align-items: center;
}

.easyflow-code-viewer__identity span {
  font-size: 12px;
  color: hsl(var(--text-muted));
}

.easyflow-code-viewer__actions button {
  padding: 5px 9px;
  color: hsl(var(--text-muted));
  cursor: pointer;
  background: transparent;
  border: 0;
  border-radius: var(--radius-control);
}

.easyflow-code-viewer__actions button:hover {
  color: hsl(var(--foreground));
  background: hsl(var(--nav-item-hover));
}

.easyflow-code-viewer__actions button:focus-visible {
  outline: 2px solid hsl(var(--primary) / 72%);
  outline-offset: 2px;
}

.easyflow-code-viewer__editor {
  flex: 1;
}
</style>
