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

const { chatEnabled } = useChatToggle();

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

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

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

const unreadCount = ref(0);

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

const fetchMessages = async () => {
  try {
    const res = await fetch(props.fetchUrl);
    if (!res.ok) return;
    const data = await res.json();
    const fetched = data.messages || [];
    const prevLen = messages.value.length;
    messages.value = fetched;
    if (!showModal.value) {
      unreadCount.value = messages.value.length - lastSeenCount.value;
    }
    if (showModal.value && fetched.length > prevLen) {
      await scrollToBottom();
    }
  } catch {
    // silent
  }
};

const sendMessage = async () => {
  const msg = newMessage.value.trim();
  if (!msg || sending.value) return;
  sending.value = true;
  try {
    const res = await fetch(props.storeUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
      credentials: 'same-origin',
      body: JSON.stringify({ message: msg }),
    });
    if (res.ok) {
      newMessage.value = '';
      fetchMessages();
      emit('new-message');
    } else {
      console.error('Chat error:', res.status, await res.text().catch(() => ''));
    }
  } catch (e) {
    console.error('Chat exception:', e);
  } finally {
    sending.value = false;
  }
};

const openModal = () => {
  lastSeenCount.value = messages.value.length;
  unreadCount.value = 0;
  showModal.value = true;
  nextTick(() => {
    scrollToBottom();
    document.body.style.overflow = 'hidden';
  });
};

const closeModal = () => {
  showModal.value = false;
  document.body.style.overflow = '';
};

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

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

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

onUnmounted(() => {
  stopPolling();
  document.body.style.overflow = '';
});

watch(() => props.casoId, () => {
  messages.value = [];
  lastSeenCount.value = 0;
  unreadCount.value = 0;
  fetchMessages();
  startPolling();
});

watch(chatEnabled, (val) => {
  if (!val) {
    showModal.value = false;
    document.body.style.overflow = '';
    stopPolling();
  } else {
    fetchMessages();
    startPolling();
  }
});
</script>

<template>
  <template v-if="chatEnabled">
  <!-- Floating button -->
  <button @click="openModal"
          class="fixed bottom-6 right-6 z-[1000] w-14 h-14 rounded-full bg-blue-600 text-white shadow-xl hover:bg-blue-700 hover:scale-105 active:scale-95 transition-all flex items-center justify-center"
          :class="{ 'animate-bounce': unreadCount > 0 }">
    <svg class="w-6 h-6" 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>
    <span v-if="unreadCount > 0"
          class="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center shadow-lg">
      {{ unreadCount > 99 ? '99+' : unreadCount }}
    </span>
  </button>

  <!-- Modal -->
  <Teleport to="body">
    <div v-if="showModal" class="fixed inset-0 z-[1100] flex items-end sm:items-center justify-center">
      <div @click="closeModal" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"></div>
      <div class="relative w-full sm:max-w-lg sm:mx-4 bg-white rounded-t-3xl sm:rounded-3xl shadow-2xl border border-slate-200 overflow-hidden flex flex-col"
           style="max-height: 85vh; height: 100%; sm:height: auto;">
        <!-- Header -->
        <div class="flex items-center justify-between px-5 py-4 border-b border-slate-200 bg-blue-600 flex-shrink-0">
          <div class="flex items-center gap-3">
            <div class="w-9 h-9 rounded-full bg-blue-500 flex items-center justify-center">
              <svg class="w-5 h-5 text-white" 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>
            </div>
            <div>
              <h3 class="text-sm font-bold text-white">Chat</h3>
              <p class="text-[10px] text-blue-200">{{ otherPartyName ? `Conversando con ${otherPartyName}` : (currentUserType === 'admin' ? 'Conversando con Ajustador' : 'Conversando con Administrador') }}</p>
            </div>
          </div>
          <button @click="closeModal" class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white hover:bg-blue-700 transition-colors flex-shrink-0">
            <svg 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="M6 18L18 6M6 6l12 12"></path></svg>
          </button>
        </div>

        <!-- Messages -->
        <div ref="chatContainer" class="flex-1 overflow-y-auto px-5 py-4 space-y-3 scroll-smooth bg-slate-50/50">
          <div v-if="loading && messages.length === 0" class="flex items-center justify-center py-16">
            <svg class="w-8 h-8 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-16">
              <div class="w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center mx-auto mb-3">
                <svg class="w-7 h-7 text-slate-300" 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>
              </div>
              <p class="text-sm text-slate-400 font-medium">Sin mensajes aún</p>
              <p class="text-xs text-slate-300 mt-1">Escribe el primer mensaje</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-[85%] rounded-2xl px-4 py-2.5 shadow-sm"
                   :class="msg.sender_type === currentUserType
                     ? 'bg-blue-600 text-white rounded-br-sm'
                     : 'bg-white text-slate-800 rounded-bl-sm border border-slate-200'">
                <p class="text-[10px] font-bold opacity-80 mb-0.5"
                   :class="msg.sender_type === currentUserType ? 'text-blue-200' : 'text-slate-400'">
                  {{ msg.sender_name }}
                </p>
                <p class="text-sm leading-relaxed whitespace-pre-wrap">{{ msg.message }}</p>
                <p class="text-[9px] mt-1 opacity-60 text-right">{{ msg.created_at_diff }}</p>
              </div>
            </div>
          </template>
        </div>

        <!-- Input -->
        <div class="flex gap-2 px-5 py-4 border-t border-slate-100 bg-white flex-shrink-0">
          <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-blue-500 outline-none transition-shadow"
                 placeholder="Escribe un mensaje..." />
          <button @click="sendMessage" :disabled="sending || !newMessage.trim()"
                  class="px-5 py-2.5 bg-blue-600 text-white font-bold rounded-xl hover:bg-blue-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>
    </div>
  </Teleport>
  </template>
</template>
