<template>
  <button 
    :class="['logout-btn', { mobile }]" 
    @click="showDialog = true" 
    title="Выйти"
  >
    <i data-lucide="log-out"></i>
    <span v-if="showText" class="logout-text">Выйти из аккаунта</span>
  </button>
  
  <ConfirmDialog
    v-model:show="showDialog"
    type="logout"
    :action="logoutAll"
    :discard-action="logoutCurrent"
  />
</template>

<script setup>
import { ref, onMounted, onUpdated } from 'vue'
import { useRouter } from 'vue-router'
import { authApi } from '../../api'
import { clearAuthCache } from '../../router'
import { useProjectsStore } from '../../stores/projects'
import ConfirmDialog from '../ConfirmDialog.vue'

defineProps({
  showText: {
    type: Boolean,
    default: false
  },
  mobile: {
    type: Boolean,
    default: false
  }
})

const router = useRouter()
const store = useProjectsStore()
const showDialog = ref(false)

// Выход с текущей сессии (discard action)
const logoutCurrent = async () => {
  clearAuthCache()
  await authApi.logout()
  store.reset()
  router.push('/login')
}

// Выход со всех сессий (confirm action)
const logoutAll = async () => {
  clearAuthCache()
  await authApi.logoutAll()
  store.reset()
  router.push('/login')
}

const refreshIcons = () => {
  if (window.lucide) window.lucide.createIcons()
}

onMounted(refreshIcons)
onUpdated(refreshIcons)
</script>

<style scoped>
.logout-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid var(--border);
  border-radius: 10px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
  gap: 8px;
  font-family: inherit;
  font-size: 14px;
}

.logout-btn:hover {
  background: rgba(239, 68, 68, 0.15);
  border-color: rgba(239, 68, 68, 0.3);
  color: #ef4444;
}

.logout-btn i {
  width: 18px;
  height: 18px;
  flex-shrink: 0;
}

/* С текстом */
.logout-btn:has(.logout-text) {
  width: 100%;
  height: 48px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  color: var(--text-muted);
}

.logout-btn:has(.logout-text):hover {
  background: rgba(255, 255, 255, 0.06);
  border-color: rgba(255, 255, 255, 0.15);
  color: var(--text-secondary);
}

.logout-btn:has(.logout-text) i {
  width: 16px;
  height: 16px;
}

/* Мобильная версия (иконка) */
.logout-btn.mobile {
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  color: var(--text-muted);
  margin-left: auto;
}

.logout-btn.mobile:hover,
.logout-btn.mobile:active {
  background: rgba(239, 68, 68, 0.15);
  border-color: rgba(239, 68, 68, 0.3);
  color: #ef4444;
}
</style>
