<!--
  JobReplyBox — répondre au fil d'un job (note INTERNE par défaut ; au client si coché, quand un billet legacy est lié).
  Module RÉUTILISABLE extrait du volet jobDetail. Poste via roster.postJobComment ; émet `sent` pour que le parent
  recharge le fil (ex. JobThread.reload()). Attribution = agent connecté (prénom+nom) via usePermissions.
-->
<template>
  <div v-if="lid || name" class="q-mt-sm">
    <q-input v-model="reply" dense outlined type="textarea" autogrow placeholder="Écrire une note / réponse…"
      :input-style="{ minHeight: '48px' }" @keydown.ctrl.enter="send" @keydown.meta.enter="send" />
    <div class="row items-center q-mt-xs">
      <q-checkbox v-if="lid" v-model="replyPublic" dense size="sm" label="Envoyer aussi au client" />
      <q-space />
      <q-btn dense unelevated color="primary" no-caps icon="send"
        :label="replyPublic ? 'Répondre au client' : 'Note interne'"
        :disable="!reply.trim()" :loading="sending" @click="send" />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Notify } from 'quasar'
import * as roster from 'src/api/roster'
import { usePermissions } from 'src/composables/usePermissions'

const props = defineProps({
  name: { type: String, default: '' }, // docname du Dispatch Job
  lid: { type: [String, Number], default: null }, // n° ticket legacy (permet « au client »)
})
const emit = defineEmits(['sent'])

const { userName } = usePermissions()
const reply = ref('')
const replyPublic = ref(false)
const sending = ref(false)

async function send () {
  const text = reply.value.trim(); if (!text || sending.value) return
  sending.value = true
  try {
    const r = await roster.postJobComment({ job: props.name, lid: props.lid, text, isPublic: replyPublic.value, agentName: userName.value || '' })
    if (r && r.ok) {
      const wasPublic = replyPublic.value
      reply.value = ''; replyPublic.value = false
      Notify.create({ type: 'positive', message: wasPublic ? 'Réponse envoyée au client' : 'Note interne ajoutée', timeout: 2200 })
      emit('sent', { public: wasPublic })
    } else { Notify.create({ type: 'negative', message: (r && r.error) || "Échec de l'envoi", timeout: 3000 }) }
  } catch (e) { Notify.create({ type: 'negative', message: "Échec de l'envoi", timeout: 3000 }) } finally { sending.value = false }
}
</script>
