<template>
  <div class="group relative my-6">
    <!-- Language badge -->
    <div
      v-if="language"
      class="absolute top-3 right-3 z-10 px-2 py-1 text-xs font-medium uppercase tracking-wider text-neutral-400 bg-neutral-800/80 rounded"
    >
      {{ language }}
    </div>

    <!-- Copy button -->
    <UButton
      v-if="showCopy"
      :icon="copied ? 'i-lucide-check' : 'i-lucide-copy'"
      :color="copied ? 'success' : 'neutral'"
      variant="ghost"
      size="xs"
      class="absolute top-3 z-10"
      :class="language ? 'right-28' : 'right-3'"
      @click="copyCode"
      :aria-label="copied ? 'Copied!' : 'Copy code'"
    />

    <!-- Shiki Highlighter - wrapped in ClientOnly for SSR compatibility -->
    <ClientOnly>
      <Shiki :code="code" :lang="language" />
      <template #fallback>
        <pre class="shiki-fallback"><code>{{ code }}</code></pre>
      </template>
    </ClientOnly>
  </div>
</template>

<script setup>
const props = defineProps({
  /** Code string to highlight */
  code: {
    type: String,
    required: true,
  },
  /** Language for syntax highlighting */
  language: {
    type: String,
    default: '',
  },
  /** Show copy button */
  showCopy: {
    type: Boolean,
    default: false,
  },
});

const copied = ref(false);

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(props.code);
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  } catch (err) {
    console.error("Failed to copy:", err);
  }
};
</script>

<style scoped>
/* Fallback styling while Shiki loads */
.shiki-fallback {
  margin: 0;
  padding: 1.25rem 1.5rem;
  border-radius: 0.75rem;
  overflow-x: auto;
  background-color: #0d1117;
  color: #c9d1d9;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
  font-size: 0.875rem;
  line-height: 1.7;
}
</style>
