<script setup lang="ts">
import { onErrorCaptured, ref } from 'vue'

const hasError = ref(false)
const errorMessage = ref('')
const isDev = import.meta.env.DEV

onErrorCaptured((err) => {
  hasError.value = true
  errorMessage.value = err instanceof Error ? err.message : String(err)

  if (import.meta.env.DEV) {
    console.error('[ErrorBoundary] Caught error:', err)
  }

  // Prevent error from propagating further
  return false
})

function retry() {
  hasError.value = false
  errorMessage.value = ''
}
</script>

<template>
  <div v-if="hasError" class="flex flex-col items-center justify-center py-12 px-4 text-center">
    <UIcon name="i-lucide-alert-triangle" class="size-12 text-warning mb-4" />
    <h3 class="text-lg font-semibold text-default mb-2">
      Something went wrong
    </h3>
    <p class="text-sm text-muted mb-4 max-w-md">
      An unexpected error occurred. Please try again.
    </p>
    <p v-if="isDev && errorMessage" class="text-xs text-error mb-4 max-w-lg font-mono bg-error/5 p-2 rounded">
      {{ errorMessage }}
    </p>
    <UButton
      label="Try Again"
      icon="i-lucide-refresh-cw"
      color="primary"
      variant="outline"
      @click="retry"
    />
  </div>
  <slot v-else />
</template>
