<script setup lang="ts">
import { computed, ref } from 'vue'
import { highlightCode } from '@/utils/markdown'

const props = withDefaults(defineProps<{
  code: string
  lang?: string
  maxHeight?: string
}>(), {
  lang: '',
  maxHeight: '250px',
})

const highlighted = computed(() =>
  highlightCode(props.code, props.lang || undefined)
)

const copyState = ref<'idle' | 'copied'>('idle')

function copy() {
  navigator.clipboard.writeText(props.code).then(() => {
    copyState.value = 'copied'
    setTimeout(() => { copyState.value = 'idle' }, 1500)
  })
}
</script>

<template>
  <div class="code-block">
    <button class="copy-btn" @click.stop="copy">
      {{ copyState === 'copied' ? 'Copied!' : 'Copy' }}
    </button>
    <pre class="code-pre" :style="{ maxHeight }" v-html="highlighted"></pre>
  </div>
</template>

<style scoped>
.code-block {
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.04);
  background: var(--bg-secondary, #1a1a2e);
  border-radius: 0 0 6px 6px;
}

.code-pre {
  margin: 0;
  padding: 0.35rem 0.6rem;
  font-size: 11px;
  line-height: 1.2;
  color: var(--text-secondary);
  white-space: pre;
  word-break: normal;
  overflow: auto;
  background: transparent;
  font-family: 'Consolas', 'Lucida Console', 'SF Mono', 'Fira Code', monospace;
  letter-spacing: 0;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  tab-size: 4;
}

.copy-btn {
  position: absolute;
  top: 2px;
  right: 4px;
  font-size: 10px;
  padding: 0.15em 0.4em;
  color: var(--text-muted, #94a3b8);
  background: rgba(255, 255, 255, 0.06);
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-family: inherit;
  opacity: 0;
  transition: opacity 0.15s ease, color 0.15s ease, background 0.15s ease;
  z-index: 1;
}

.code-block:hover .copy-btn { opacity: 1; }
.copy-btn:hover { color: var(--text-primary, #e2e8f0); background: rgba(255, 255, 255, 0.1); }
</style>
