<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import MessageListPanel from './MessageListPanel.vue';
import CustomerServicePanel from './CustomerServicePanel.vue';
import MobileMessageDetailView from '../views/MobileMessageDetailView.vue';
import { useAuthStore } from '../stores/auth';
import { usePlayerMessages } from '../composables/usePlayerMessages';
import { useInboxFeature } from '../composables/useInboxFeature';
import { useFloatingMailbox } from '../composables/useFloatingMailbox';
import { useViewport } from '../composables/useViewport';
import { useRoute } from 'vue-router';

type HubTab = 'messages' | 'support';

const { t } = useI18n();
const route = useRoute();
const { isDesktop } = useViewport();
const auth = useAuthStore();
const { inboxEnabled, hubTitleKey } = useInboxFeature();
const { unreadCount, messages, listLoaded, refreshUnreadCount, markAllRead, deleteAllMessages } = usePlayerMessages();
const { isOpen, toggle, close } = useFloatingMailbox();

const markingAll = ref(false);
const deletingAll = ref(false);
const activeTab = ref<HubTab>('messages');
const selectedMessageId = ref<string | null>(null);

const unreadInList = computed(() => messages.value.filter((item) => !item.isRead).length);
const hasMessages = computed(() => listLoaded.value && messages.value.length > 0);
const showMessageActions = computed(
  () => inboxEnabled.value && activeTab.value === 'messages' && auth.token && hasMessages.value && !selectedMessageId.value,
);

const hideOnMessagesPage = computed(
  () => isDesktop.value && route.path.startsWith('/messages'),
);

const offsetForBetSlip = computed(() => {
  if (!isDesktop.value || hideOnMessagesPage.value) return false;
  const p = route.path;
  if (p === '/bets' || p.startsWith('/bets/')) return false;
  if (p.startsWith('/wallet') || p.startsWith('/profile')) return false;
  return true;
});

watch(
  () => route.path,
  (path) => {
    if (isDesktop.value && path.startsWith('/messages') && isOpen.value) {
      close();
    }
  },
);

watch(isOpen, (opened) => {
  if (opened) {
    if (!inboxEnabled.value) activeTab.value = 'support';
    refreshUnreadCount();
  } else {
    selectedMessageId.value = null;
  }
});

function switchTab(tab: HubTab) {
  if (!inboxEnabled.value || tab === activeTab.value) return;
  activeTab.value = tab;
  selectedMessageId.value = null;
}

async function onMarkAllRead() {
  if (!unreadInList.value || markingAll.value) return;
  markingAll.value = true;
  try {
    await markAllRead();
    await refreshUnreadCount();
  } finally {
    markingAll.value = false;
  }
}

async function onDeleteAll() {
  if (deletingAll.value || !messages.value.length) return;
  if (!confirm(t('messages.delete_all_confirm'))) return;
  deletingAll.value = true;
  try {
    await deleteAllMessages();
    await refreshUnreadCount();
  } finally {
    deletingAll.value = false;
  }
}

function handleMessageClick(id: string) {
  selectedMessageId.value = id;
}

onMounted(() => {
  if (isOpen.value) refreshUnreadCount();
});
</script>

<template>
  <div
    v-if="!hideOnMessagesPage"
    class="floating-mailbox"
    :class="{ 'is-betting-desktop': offsetForBetSlip }"
  >
    <!-- Floating Button -->
    <button
      type="button"
      class="fab-btn"
      :class="{ 'fab-active': isOpen }"
      @click="toggle"
      :aria-label="t(hubTitleKey)"
    >
      <svg class="fab-icon" viewBox="0 0 24 24" aria-hidden="true">
        <path
          d="M12 3C7.03 3 3 6.58 3 11c0 2.02.9 3.86 2.38 5.24L4 21l4.2-1.02A10.8 10.8 0 0 0 12 19c4.97 0 9-3.58 9-8s-4.03-8-9-8Z"
          fill="none"
          stroke="currentColor"
          stroke-width="1.8"
          stroke-linejoin="round"
        />
        <circle cx="9" cy="11" r="1" fill="currentColor" />
        <circle cx="12" cy="11" r="1" fill="currentColor" />
        <circle cx="15" cy="11" r="1" fill="currentColor" />
      </svg>
      <span v-if="auth.user && inboxEnabled && unreadCount > 0" class="badge">
        {{ unreadCount > 99 ? '99+' : unreadCount }}
      </span>
    </button>

    <!-- Popup Panel -->
    <Transition name="fade-slide">
      <div v-if="isOpen" class="popup-panel">
        <div class="popup-header">
          <div class="tabs">
            <button
              v-if="inboxEnabled"
              type="button"
              class="tab-btn"
              :class="{ active: activeTab === 'messages' }"
              @click="switchTab('messages')"
            >
              {{ t('messages.tab_inbox') }}
              <span v-if="unreadInList > 0" class="tab-badge">{{ unreadInList }}</span>
            </button>
            <button
              type="button"
              class="tab-btn"
              :class="{ active: activeTab === 'support' }"
              @click="switchTab('support')"
            >
              {{ t('messages.tab_support') }}
            </button>
          </div>
          
          <div class="header-actions">
            <button v-if="showMessageActions && unreadInList > 0" type="button" class="action-btn" @click="onMarkAllRead" :disabled="markingAll">
              <svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>
            </button>
            <button v-if="showMessageActions" type="button" class="action-btn danger" @click="onDeleteAll" :disabled="deletingAll">
              <svg viewBox="0 0 24 24" width="16" height="16"><path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></svg>
            </button>
            <button type="button" class="action-btn close" @click="close">
              <svg viewBox="0 0 24 24" width="18" height="18"><path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg>
            </button>
          </div>
        </div>

        <div class="popup-body">
          <template v-if="activeTab === 'messages' && inboxEnabled">
            <MobileMessageDetailView
              v-if="selectedMessageId"
              :id="selectedMessageId"
              embedded
              @back="selectedMessageId = null"
            />
            <MessageListPanel v-else class="panel-content" @click-message="handleMessageClick" />
          </template>
          <CustomerServicePanel v-else class="panel-content" />
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.floating-mailbox {
  position: fixed;
  bottom: 32px;
  right: 32px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.fab-btn {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  background: var(--primary);
  color: #fff;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.2s, background 0.2s;
  position: relative;
}

.fab-btn:hover {
  transform: scale(1.05);
  background: var(--primary-light);
}

.fab-active {
  transform: scale(0.95);
}

.fab-icon {
  width: 28px;
  height: 28px;
}

.badge {
  position: absolute;
  top: 0;
  right: 0;
  background: var(--danger, #ff4d4f);
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  padding: 2px 6px;
  border-radius: 10px;
  border: 2px solid var(--bg-card);
  line-height: 1;
}

.popup-panel {
  position: absolute;
  bottom: 76px;
  right: 0;
  width: 380px;
  height: 600px;
  max-height: calc(100vh - 120px);
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 12px;
  box-shadow: var(--shadow-md);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  isolation: isolate;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  border-bottom: 1px solid var(--border);
  background: var(--bg-body);
  height: 48px;
}

.tabs {
  display: flex;
  height: 100%;
}

.tab-btn {
  background: transparent;
  border: none;
  border-bottom: 2px solid transparent;
  color: var(--text-muted);
  font-size: 14px;
  font-weight: 600;
  padding: 0 16px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.tab-btn:hover {
  color: var(--primary);
}

.tab-btn.active {
  color: var(--primary-light);
  border-bottom-color: var(--primary);
}

.tab-badge {
  background: var(--bg-hover);
  color: var(--text-muted);
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
}

.tab-btn.active .tab-badge {
  background: var(--primary);
  color: #fff;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn {
  background: transparent;
  border: none;
  color: var(--text-muted);
  width: 32px;
  height: 32px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.action-btn:hover {
  background: var(--bg-hover);
  color: var(--primary);
}

.action-btn.danger:hover {
  color: var(--danger, #ff4d4f);
  background: rgba(255, 77, 79, 0.1);
}

.action-btn.close:hover {
  background: var(--bg-hover);
}

.popup-body {
  height: calc(100% - 48px);
  position: relative;
  background: var(--bg-body);
  overflow-y: auto;
}

.panel-content {
  display: flex;
  flex-direction: column;
}

/* Transitions */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  transform-origin: bottom right;
}

.fade-slide-enter-from,
.fade-slide-leave-to {
  opacity: 0;
  transform: scale(0.9) translateY(20px);
}

.floating-mailbox.is-betting-desktop {
  right: calc(var(--desktop-right-betslip-w, 288px) + 12px);
  bottom: 24px;
}
</style>
