<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { router } from '@inertiajs/vue3';

const props = defineProps({
  casoId: [Number, String],
  fetchUrl: String,
  storeUrl: String,
  currentUserType: { type: String, default: 'admin' },
  currentUserName: { type: String, default: '' },
});

const emit = defineEmits(['new-message']);

const messages = ref([]);
const newMessage = ref('');
const loading = ref(false);
const sending = ref(false);
const chatContainer = ref(null);
const pollInterval = ref(null);

const scrollToBottom = async () => {
  await nextTick();
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  }
};

const fetchMessages = async () => {
  if (loading.value) return;
  loading.value = true;
  try {
    const res = await fetch(props.fetchUrl);
    const data = await res.json();
    messages.value = data.messages || [];
    await scrollToBottom();
  } catch {
    // silent
  } finally {
    loading.value = false;
  }
};

const sendMessage = () => {
  const msg = newMessage.value.trim();
  if (!msg || sending.value) return;
  sending.value = true;
  router.post(props.storeUrl, { message: msg }, {
    preserveScroll: true,
    preserveState: true,
    onSuccess: () => {
      newMessage.value = '';
      fetchMessages();
      emit('new-message');
    },
    onFinish: () => {
      sending.value = false;
    },
  });
};

const startPolling = () => {
  stopPolling();
  pollInterval.value = setInterval(fetchMessages, 8000);
};

const stopPolling = () => {
  if (pollInterval.value) {
    clearInterval(pollInterval.value);
    pollInterval.value = null;
  }
};

onMounted(() => {
  fetchMessages();
  startPolling();
});

onUnmounted(() => {
  stopPolling();
});

watch(() => props.casoId, () => {
  messages.value = [];
  fetchMessages();
  startPolling();
});
</script>

<template>
  <div class="flex flex-col h-full">
    <div ref="chatContainer" class="flex-1 overflow-y-auto space-y-3 px-1 scroll-smooth" style="max-height: 320px; min-height: 200px;">
      <div v-if="loading && messages.length === 0" class="flex items-center justify-center py-12">
        <svg class="w-6 h-6 text-slate-300 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
      </div>
      <template v-else-if="messages.length === 0">
        <div class="text-center py-12">
          <svg class="w-10 h-10 mx-auto text-slate-300 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path></svg>
          <p class="text-sm text-slate-400">Sin mensajes aún. Escribe el primero.</p>
        </div>
      </template>
      <template v-else>
        <div v-for="msg in messages" :key="msg.id"
             class="flex" :class="msg.sender_type === currentUserType ? 'justify-end' : 'justify-start'">
          <div class="max-w-[80%] rounded-2xl px-4 py-2.5 shadow-sm"
               :class="msg.sender_type === currentUserType
                 ? 'bg-indigo-600 text-white rounded-br-md'
                 : 'bg-slate-100 text-slate-800 rounded-bl-md'">
            <p class="text-xs font-bold opacity-80 mb-0.5"
               :class="msg.sender_type === currentUserType ? 'text-indigo-200' : 'text-slate-400'">
              {{ msg.sender_name }}
            </p>
            <p class="text-sm leading-relaxed whitespace-pre-wrap">{{ msg.message }}</p>
            <p class="text-[10px] mt-1 opacity-60 text-right">{{ msg.created_at_diff }}</p>
          </div>
        </div>
      </template>
    </div>

    <div class="flex gap-2 pt-3 border-t border-slate-100 mt-3">
      <input v-model="newMessage" type="text"
             @keyup.enter="sendMessage"
             class="flex-1 px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none transition-shadow"
             placeholder="Escribe un mensaje..." />
      <button @click="sendMessage" :disabled="sending || !newMessage.trim()"
              class="px-5 py-2.5 bg-indigo-600 text-white font-bold rounded-xl hover:bg-indigo-700 transition-colors disabled:opacity-50 flex items-center gap-2">
        <svg v-if="sending" class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
        <svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
        {{ sending ? 'Enviando...' : 'Enviar' }}
      </button>
    </div>
  </div>
</template>
