<template>
  <div class="space-y-3">
    <div class="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
      <div class="flex flex-col gap-1">
        <div class="flex items-center gap-3 flex-wrap">
          <h1 class="text-2xl font-bold">{{ title }}</h1>
          <div
            v-if="siteName"
            class="badge badge-outline font-semibold"
            :style="siteStyle"
          >
            {{ siteName }}
          </div>
          <div v-if="reference" class="badge badge-outline">{{ reference }}</div>
        </div>
        <p v-if="description" class="text-sm text-base-content/60">{{ description }}</p>
      </div>
      <div class="flex items-center gap-2 print:hidden">
        <button
          v-if="canEdit"
          type="button"
          class="btn btn-primary btn-sm md:btn-md"
          :class="{ 'btn-outline': isEditMode }"
          @click="$emit('toggle-edit')"
        >
          <IconLucideSquarePen v-if="!isEditMode" class="w-4 h-4 mr-1" aria-hidden="true" />
          <IconLucideEye v-else class="w-4 h-4 mr-1" aria-hidden="true" />
          {{ isEditMode ? 'Voir d\u00e9tails' : 'Modifier' }}
        </button>
        <button
          v-if="!isEditMode"
          type="button"
          class="btn btn-ghost btn-sm md:btn-md"
          title="Imprimer"
          @click="$emit('open-print')"
        >
          <IconLucidePrinter class="w-4 h-4" aria-hidden="true" />
        </button>
        <button type="button" class="btn btn-ghost btn-sm md:btn-md" @click="goBack">
          <IconLucideArrowLeft class="w-4 h-4 mr-1" aria-hidden="true" />
          Parc machines
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import IconLucideSquarePen from '~icons/lucide/square-pen'
import IconLucideEye from '~icons/lucide/eye'
import IconLucidePrinter from '~icons/lucide/printer'
import IconLucideArrowLeft from '~icons/lucide/arrow-left'

const { canEdit } = usePermissions()
const router = useRouter()

// Retour : revient à l'URL précédente pour préserver la recherche/filtres du
// parc machines (persistés en query params). Fallback vers /machines si pas
// d'historique applicatif (accès direct, refresh, lien partagé).
const goBack = () => {
  if (window.history.state?.back) {
    router.back()
    return
  }
  router.push('/machines')
}

const props = defineProps<{
  title: string
  description?: string
  siteName?: string
  siteColor?: string
  reference?: string
  isEditMode: boolean
}>()

defineEmits<{
  'toggle-edit': []
  'open-print': []
}>()

const siteStyle = computed(() => {
  if (!props.siteColor) return {}
  return {
    borderColor: props.siteColor + '60',
    backgroundColor: props.siteColor + '25',
    color: props.siteColor,
  }
})
</script>
