<template>
  <div class="no-projects-page" :class="{ 'is-mobile': isMobile }">
    <!-- Левитирующие иконки на фоне -->
    <div class="floating-icons">
      <div class="float-icon icon-1"><i data-lucide="folder"></i></div>
      <div class="float-icon icon-2"><i data-lucide="clipboard-list"></i></div>
      <div class="float-icon icon-3"><i data-lucide="calendar"></i></div>
      <div class="float-icon icon-4"><i data-lucide="users"></i></div>
      <div class="float-icon icon-5"><i data-lucide="check-square"></i></div>
      <div class="float-icon icon-6"><i data-lucide="target"></i></div>
      <div class="float-icon icon-7"><i data-lucide="star"></i></div>
      <div class="float-icon icon-8"><i data-lucide="zap"></i></div>
      <div class="float-icon icon-9"><i data-lucide="flag"></i></div>
      <div class="float-icon icon-10"><i data-lucide="layers"></i></div>
      <div class="float-icon icon-11"><i data-lucide="clock"></i></div>
      <div class="float-icon icon-12"><i data-lucide="inbox"></i></div>
    </div>

    <!-- Контент -->
    <div class="content" :class="{ 'is-success': showSuccess }">
      
      <!-- Состояние успеха -->
      <Transition name="success-fade">
        <div v-if="showSuccess" class="success-state">
          <div class="success-icon">
            <i data-lucide="check"></i>
          </div>
          <h1 class="success-title">{{ successType === 'create' ? 'Ура!' : 'Поздравляем!' }}</h1>
          <p class="success-text">{{ successType === 'create' ? 'Вы создали первый проект' : 'Ваш первый проект ждёт вас' }}</p>
          <div class="success-loader">
            <span></span><span></span><span></span>
          </div>
        </div>
      </Transition>
      
      <!-- Основной контент -->
      <Transition name="form-fade">
        <div v-if="!showSuccess" class="main-content">
          <div class="icon-wrapper">
            <i data-lucide="folder-plus"></i>
          </div>
          
          <h1>Нет доступных проектов</h1>
          
          <p class="description">
            <template v-if="invites.length > 0">
              Примите приглашение или<br>создайте свой проект
            </template>
            <template v-else>
              Создайте новый проект или попросите<br>пригласить вас в существующий
            </template>
          </p>

          <!-- Приглашения -->
          <div v-if="invites.length > 0" class="invites-section">
            <div class="invites-header">
              <i data-lucide="mail"></i>
              <span>{{ invites.length }} {{ invitesLabel }}</span>
            </div>
            
            <div class="invites-list">
              <NotificationCard
                v-for="invite in invites"
                :key="invite.id"
                type="invite"
                :title="invite.project_name"
                :subtitle="'от ' + (invite.from_user.name || invite.from_user.username)"
                :avatar-url="invite.from_user.avatar_url ? getFullUrl(invite.from_user.avatar_url) : ''"
                :avatar-name="invite.from_user.name || invite.from_user.username"
                :badge="invite.is_admin ? 'Админ' : ''"
                :processing="processingId === invite.id"
                @accept="acceptInvite(invite)"
                @decline="declineInvite(invite)"
              />
            </div>
          </div>
          
          <button class="btn-create" @click="openCreateProject">
            <i data-lucide="plus"></i>
            <span>Создать проект</span>
          </button>
          
          <LogoutButton :show-text="true" />
        </div>
      </Transition>
    </div>
    
    <!-- Панель создания проекта -->
    <ProjectPanel
      :show="showProjectPanel"
      :project="null"
      @close="showProjectPanel = false"
      @saved="onProjectCreated"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUpdated, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import ProjectPanel from '../components/ProjectPanel.vue'
import NotificationCard from '../components/ui/NotificationCard.vue'
import LogoutButton from '../components/ui/LogoutButton.vue'
import { useProjectsStore } from '../stores/projects'
import { useMobile } from '../composables/useMobile'
import { useAutoRefresh } from '../composables/useAutoRefresh'
import { projectInviteApi, getFullUrl, cardsApi } from '../api'

const { isMobile } = useMobile()
const router = useRouter()
const store = useProjectsStore()

const showProjectPanel = ref(false)
const invites = ref([])
const processingId = ref(null)
const showSuccess = ref(false)
const successType = ref('invite') // 'invite' | 'create'

// Склонение слова "приглашение"
const invitesLabel = computed(() => {
  const count = invites.value.length
  if (count === 1) return 'приглашение'
  if (count >= 2 && count <= 4) return 'приглашения'
  return 'приглашений'
})

// Загрузка приглашений
const loadInvites = async () => {
  try {
    const result = await projectInviteApi.getMyPending()
    if (result.success) {
      invites.value = result.data
      store.pendingInvitesCount = result.count
    }
  } catch (error) {
    console.error('Ошибка загрузки приглашений:', error)
  }
}

// Предзагрузка данных пока показывается анимация успеха
const prefetchData = async (projectId) => {
  try {
    // Перезагружаем проекты принудительно
    await store.refreshProjects()
    await store.selectProject(projectId)
    
    // Загружаем карточки
    if (store.currentProjectId) {
      const result = await cardsApi.getAll(store.currentProjectId)
      if (result.success) {
        sessionStorage.setItem('prefetchedCards', JSON.stringify(result.data))
      }
    }
  } catch (e) {
    console.error('Prefetch error:', e)
  }
}

// Принять приглашение
const acceptInvite = async (invite) => {
  processingId.value = invite.id
  try {
    const result = await projectInviteApi.accept(invite.id)
    if (result.success) {
      // Показываем анимацию успеха
      successType.value = 'invite'
      showSuccess.value = true
      await nextTick()
      refreshIcons()
      
      // Параллельно: предзагрузка данных + ожидание анимации
      const prefetchPromise = prefetchData(result.project_id)
      const animationPromise = new Promise(resolve => setTimeout(resolve, 1800))
      
      // Ждём обоих (минимум 1.8 сек анимации)
      await Promise.all([prefetchPromise, animationPromise])
      
      router.push('/')
    }
  } catch (error) {
    console.error('Ошибка принятия приглашения:', error)
  } finally {
    processingId.value = null
  }
}

// Отклонить приглашение
const declineInvite = async (invite) => {
  processingId.value = invite.id
  try {
    const result = await projectInviteApi.decline(invite.id)
    if (result.success) {
      invites.value = invites.value.filter(i => i.id !== invite.id)
      store.pendingInvitesCount = invites.value.length
    }
  } catch (error) {
    console.error('Ошибка отклонения приглашения:', error)
  } finally {
    processingId.value = null
  }
}

const openCreateProject = () => {
  showProjectPanel.value = true
}

const onProjectCreated = async (projectId) => {
  showProjectPanel.value = false
  
  // Показываем анимацию успеха
  successType.value = 'create'
  showSuccess.value = true
  await nextTick()
  refreshIcons()
  
  // createProject() в store уже добавил проект и выбрал его
  // Нужно только загрузить карточки для предзагрузки
  const prefetchPromise = (async () => {
    try {
      if (store.currentProjectId) {
        const result = await cardsApi.getAll(store.currentProjectId)
        if (result.success) {
          sessionStorage.setItem('prefetchedCards', JSON.stringify(result.data))
        }
      }
    } catch (e) {
      console.error('Prefetch error:', e)
    }
  })()
  
  const animationPromise = new Promise(resolve => setTimeout(resolve, 1800))
  
  // Ждём обоих (минимум 1.8 сек анимации)
  await Promise.all([prefetchPromise, animationPromise])
  
  router.push('/')
}

// Обновление иконок
const refreshIcons = () => {
  if (window.lucide) {
    window.lucide.createIcons()
  }
}

// Периодическое обновление приглашений
const { start: startInvitesRefresh, stop: stopInvitesRefresh } = useAutoRefresh('invites', async () => {
  // Не обновляем если показывается анимация успеха
  if (!showSuccess.value) {
    await loadInvites()
  }
})

onMounted(() => {
  loadInvites()
  refreshIcons()
  startInvitesRefresh()
})

onUnmounted(() => {
  stopInvitesRefresh()
})

onUpdated(refreshIcons)

// Обновляем иконки при смене состояния успеха
watch(showSuccess, () => {
  nextTick(refreshIcons)
})
</script>

<style scoped>
.no-projects-page {
  min-height: 100vh;
  min-height: 100dvh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #0a0a0c 0%, #111113 50%, #0d1117 100%);
  position: relative;
  overflow: hidden;
  padding: 20px;
}

/* Левитирующие иконки */
.floating-icons {
  position: absolute;
  inset: 0;
  pointer-events: none;
  overflow: hidden;
}

.float-icon {
  position: absolute;
  color: rgba(255, 255, 255, 0.04);
  transition: color 0.3s;
}

.float-icon i,
.float-icon svg {
  width: 100%;
  height: 100%;
}

.icon-1 { width: 48px; height: 48px; top: 8%; left: 12%; animation: float1 6s ease-in-out infinite; }
.icon-2 { width: 36px; height: 36px; top: 15%; right: 18%; animation: float2 7s ease-in-out infinite; }
.icon-3 { width: 42px; height: 42px; top: 25%; left: 8%; animation: float3 8s ease-in-out infinite; }
.icon-4 { width: 32px; height: 32px; top: 35%; right: 10%; animation: float1 5s ease-in-out infinite; }
.icon-5 { width: 40px; height: 40px; top: 55%; left: 15%; animation: float2 9s ease-in-out infinite; }
.icon-6 { width: 44px; height: 44px; top: 65%; right: 20%; animation: float3 6s ease-in-out infinite; }
.icon-7 { width: 28px; height: 28px; top: 75%; left: 10%; animation: float1 7s ease-in-out infinite; }
.icon-8 { width: 38px; height: 38px; top: 85%; right: 15%; animation: float2 8s ease-in-out infinite; }
.icon-9 { width: 34px; height: 34px; bottom: 20%; left: 25%; animation: float3 5s ease-in-out infinite; }
.icon-10 { width: 46px; height: 46px; top: 45%; left: 5%; animation: float1 10s ease-in-out infinite; }
.icon-11 { width: 30px; height: 30px; top: 20%; left: 25%; animation: float2 6s ease-in-out infinite; }
.icon-12 { width: 36px; height: 36px; bottom: 30%; right: 8%; animation: float3 7s ease-in-out infinite; }

@keyframes float1 {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  25% { transform: translateY(-15px) rotate(5deg); }
  75% { transform: translateY(10px) rotate(-3deg); }
}

@keyframes float2 {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(-5deg); }
  66% { transform: translateY(15px) rotate(3deg); }
}

@keyframes float3 {
  0%, 100% { transform: translateY(0) translateX(0); }
  50% { transform: translateY(-12px) translateX(8px); }
}

/* Контент */
.content {
  position: relative;
  z-index: 10;
  text-align: center;
  max-width: 400px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-content {
  animation: contentAppear 0.6s ease;
  width: 100%;
}

/* ========== ПРИГЛАШЕНИЯ ========== */
.invites-section {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 24px;
  text-align: left;
}

.invites-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 14px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  color: var(--accent);
  font-size: 14px;
  font-weight: 600;
}

.invites-header i {
  width: 18px;
  height: 18px;
}

.invites-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

@keyframes contentAppear {
  0% { opacity: 0; transform: translateY(20px); }
  100% { opacity: 1; transform: translateY(0); }
}

.icon-wrapper {
  width: 88px;
  height: 88px;
  margin: 0 auto 28px;
  background: linear-gradient(135deg, var(--accent) 0%, #00e6b8 100%);
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 20px 60px rgba(0, 212, 170, 0.3);
  animation: iconFloat 4s ease-in-out infinite;
}

.icon-wrapper :deep(svg) {
  width: 40px;
  height: 40px;
  color: #000;
}

@keyframes iconFloat {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-8px); }
}

h1 {
  font-size: 26px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 12px;
  letter-spacing: -0.5px;
}

.description {
  font-size: 15px;
  color: var(--text-muted);
  line-height: 1.6;
  margin: 0 0 36px;
}

.btn-create {
  width: 100%;
  height: 56px;
  background: linear-gradient(135deg, var(--accent) 0%, #00e6b8 100%);
  border: none;
  border-radius: 14px;
  color: #000;
  font-family: inherit;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  transition: all 0.3s ease;
  margin-bottom: 14px;
  box-shadow: 0 10px 40px rgba(0, 212, 170, 0.3);
}

.btn-create:hover {
  transform: translateY(-2px);
  box-shadow: 0 15px 50px rgba(0, 212, 170, 0.4);
}

.btn-create:active {
  transform: translateY(0);
}

.btn-create :deep(svg) {
  width: 22px;
  height: 22px;
}

/* Мобильная адаптация */
.no-projects-page.is-mobile h1 {
  font-size: 22px;
}

.no-projects-page.is-mobile .description {
  font-size: 14px;
}

.no-projects-page.is-mobile .icon-wrapper {
  width: 76px;
  height: 76px;
}

.no-projects-page.is-mobile .icon-wrapper :deep(svg) {
  width: 34px;
  height: 34px;
}

.no-projects-page.is-mobile .float-icon {
  opacity: 0.5;
}

/* Мобильные стили для приглашений */
.no-projects-page.is-mobile .invites-section {
  padding: 14px;
  margin-bottom: 20px;
}

/* ========== СОСТОЯНИЕ УСПЕХА ========== */
.success-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  animation: successAppear 0.6s ease;
}

@keyframes successAppear {
  0% { opacity: 0; transform: scale(0.9); }
  100% { opacity: 1; transform: scale(1); }
}

.success-icon {
  width: 100px;
  height: 100px;
  background: linear-gradient(135deg, var(--accent) 0%, #00e6b8 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 28px;
  box-shadow: 0 25px 80px rgba(0, 212, 170, 0.4);
  animation: successPulse 1.5s ease-in-out infinite;
}

.success-icon :deep(svg) {
  width: 48px;
  height: 48px;
  color: #000;
  animation: successCheck 0.5s ease 0.2s both;
}

@keyframes successPulse {
  0%, 100% { transform: scale(1); box-shadow: 0 25px 80px rgba(0, 212, 170, 0.4); }
  50% { transform: scale(1.05); box-shadow: 0 30px 100px rgba(0, 212, 170, 0.5); }
}

@keyframes successCheck {
  0% { transform: scale(0) rotate(-45deg); opacity: 0; }
  50% { transform: scale(1.2) rotate(10deg); }
  100% { transform: scale(1) rotate(0); opacity: 1; }
}

.success-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.success-text {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0 0 32px 0;
}

.success-loader {
  display: flex;
  gap: 8px;
}

.success-loader span {
  width: 10px;
  height: 10px;
  background: var(--accent);
  border-radius: 50%;
  animation: successLoaderBounce 1.4s ease-in-out infinite;
}

.success-loader span:nth-child(2) { animation-delay: 0.16s; }
.success-loader span:nth-child(3) { animation-delay: 0.32s; }

@keyframes successLoaderBounce {
  0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
  40% { transform: scale(1); opacity: 1; }
}

/* Transitions */
.form-fade-enter-active,
.form-fade-leave-active {
  transition: opacity 0.4s ease, transform 0.4s ease;
}

.form-fade-enter-from {
  opacity: 0;
  transform: scale(0.95);
}

.form-fade-leave-to {
  opacity: 0;
  transform: scale(0.95);
  position: absolute;
  width: 100%;
}

.success-fade-enter-active {
  transition: opacity 0.5s ease 0.2s, transform 0.5s ease 0.2s;
}

.success-fade-enter-from {
  opacity: 0;
  transform: scale(0.9);
}

/* Мобильная адаптация успеха */
.no-projects-page.is-mobile .success-icon {
  width: 80px;
  height: 80px;
}

.no-projects-page.is-mobile .success-icon :deep(svg) {
  width: 40px;
  height: 40px;
}

.no-projects-page.is-mobile .success-title {
  font-size: 24px;
}

.no-projects-page.is-mobile .success-text {
  font-size: 14px;
}
</style>
