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

type HubTab = 'messages' | 'support';

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const auth = useAuthStore();
const { inboxEnabled, hubTitleKey } = useInboxFeature();
const {
  unreadCount,
  messages,
  listLoaded,
  refreshUnreadCount,
  markAllRead,
  deleteAllMessages,
} = usePlayerMessages();

const markingAll = ref(false);
const deletingAll = ref(false);
const deleteAllConfirmVisible = ref(false);

const activeTab = computed<HubTab>(() => {
  if (!inboxEnabled.value) return 'support';
  return route.query.tab === 'support' ? 'support' : 'messages';
});

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,
);

function switchTab(tab: HubTab) {
  if (!inboxEnabled.value || tab === activeTab.value) return;
  router.replace({ path: '/messages', query: tab === 'support' ? { tab: 'support' } : {} });
}

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

function onDeleteAll() {
  if (deletingAll.value || !messages.value.length) return;
  deleteAllConfirmVisible.value = true;
}

async function confirmDeleteAll() {
  if (deletingAll.value || !messages.value.length) return;
  deletingAll.value = true;
  try {
    await deleteAllMessages();
    await refreshUnreadCount();
    deleteAllConfirmVisible.value = false;
  } finally {
    deletingAll.value = false;
  }
}

function ensureSupportTabWhenDisabled() {
  if (inboxEnabled.value || route.path !== '/messages') return;
  if (route.query.tab === 'support') return;
  void router.replace({ path: '/messages', query: { tab: 'support' } });
}

function goBack() {
  router.back();
}

watch(inboxEnabled, (enabled, prev) => {
  if (prev && !enabled) ensureSupportTabWhenDisabled();
});

watch(
  () => route.query.tab,
  () => {
    if (inboxEnabled.value && activeTab.value === 'messages') void refreshUnreadCount();
  },
);

onMounted(ensureSupportTabWhenDisabled);

onActivated(() => {
  if (inboxEnabled.value) {
    void refreshUnreadCount();
    return;
  }
  ensureSupportTabWhenDisabled();
});
</script>

<template>
  <div class="inbox-hub" :class="{ 'inbox-hub--tabs': inboxEnabled }">
    <header class="page-header">
      <button type="button" class="back-btn" :aria-label="t('messages.back')" @click="goBack">‹</button>
      <h1>{{ t(hubTitleKey) }}</h1>
    </header>

    <div v-if="inboxEnabled" class="hub-top-bar">
      <nav class="hub-tabs" role="tablist">
        <button
          type="button"
          role="tab"
          class="hub-tab"
          :class="{ active: activeTab === 'messages' }"
          :aria-selected="activeTab === 'messages'"
          @click="switchTab('messages')"
        >
          <span class="hub-tab-label">{{ t('inbox_hub.tab_messages') }}</span>
          <span v-if="auth.token && unreadCount > 0" class="hub-tab-badge">
            {{ unreadCount > 99 ? '99+' : unreadCount }}
          </span>
        </button>
        <button
          type="button"
          role="tab"
          class="hub-tab"
          :class="{ active: activeTab === 'support' }"
          :aria-selected="activeTab === 'support'"
          @click="switchTab('support')"
        >
          {{ t('inbox_hub.tab_support') }}
        </button>
      </nav>
    </div>

    <div v-if="showMessageActions" class="message-actions">
      <button
        type="button"
        class="action-btn"
        :disabled="!unreadInList || markingAll"
        @click="onMarkAllRead"
      >
        {{ t('messages.mark_all_read') }}
      </button>
      <button
        type="button"
        class="action-btn danger"
        :disabled="deletingAll"
        @click="onDeleteAll"
      >
        {{ t('messages.delete_all') }}
      </button>
    </div>

    <MessageListPanel v-if="inboxEnabled" v-show="activeTab === 'messages'" />
    <CustomerServicePanel v-if="activeTab === 'support'" />

    <ConfirmDialog
      v-model:visible="deleteAllConfirmVisible"
      :title="t('messages.delete_all')"
      :message="t('messages.delete_all_confirm')"
      :confirm-text="t('messages.delete_all')"
      danger
      :loading="deletingAll"
      @confirm="confirmDeleteAll"
    />
  </div>
</template>

<style scoped>
.inbox-hub {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  padding: 0 0 24px;
}

.inbox-hub--tabs {
  margin: -12px -16px 0;
  padding: max(12px, env(safe-area-inset-top, 0px)) 16px 0;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 0 14px;
  border-bottom: 1px solid var(--border);
  margin-bottom: 0;
}

.back-btn {
  width: 36px;
  height: 36px;
  border: 1px solid var(--border);
  border-radius: 10px;
  background: #141414;
  color: var(--gold);
  font-size: 22px;
  line-height: 1;
  cursor: pointer;
}

.page-header h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #fff;
}

.hub-top-bar {
  margin: 0;
  border-bottom: 1px solid var(--border);
}



.hub-tabs {
  flex: 1;
  display: flex;
  gap: 0;
  margin: 0;
  min-width: 0;
}

.hub-tab {
  flex: 1;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 10px 8px;
  border: none;
  border-bottom: 2px solid transparent;
  background: transparent;
  color: var(--text-muted);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: color 0.15s, border-color 0.15s;
}

.hub-tab.active {
  color: var(--gold);
  border-bottom-color: var(--gold);
}

.hub-tab-label {
  line-height: 1.2;
}

.hub-tab-badge {
  min-width: 18px;
  padding: 0 5px;
  border-radius: 9px;
  background: var(--gold);
  color: #111;
  font-size: 11px;
  font-weight: 700;
  line-height: 18px;
  text-align: center;
}

.message-actions {
  display: flex;
  gap: 8px;
  padding: 10px 0 4px;
}

.action-btn {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid var(--border-gold-soft);
  border-radius: 8px;
  background: rgba(212, 175, 55, 0.08);
  color: var(--gold);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
}

.action-btn:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.action-btn.danger {
  border-color: rgba(255, 80, 80, 0.35);
  background: rgba(255, 80, 80, 0.08);
  color: #f88;
}
</style>
