<template>
  <div class="app" :class="{ mobile: isMobile }">
    <Sidebar />
    
    <div class="main-wrapper">
      <Header title="Команда" subtitle="Наша команда специалистов" />

      <main class="main">
        <Loader v-if="loading" />

        <!-- Desktop: grid -->
        <div v-else-if="!isMobile" class="team-grid">
          <div 
            v-for="user in users" 
            :key="user.id" 
            class="team-card"
          >
            <div class="card-avatar">
              <img v-if="user.avatar_url" :src="getFullUrl(user.avatar_url)" :alt="user.name || ''">
              <span v-else class="avatar-placeholder">{{ (user.name || '?')[0] }}</span>
            </div>
            <div class="card-info">
              <h3 class="card-name">{{ user.name || 'Без имени' }}</h3>
              <div class="card-meta">
                <span v-if="user.department" class="card-department">{{ user.department }}</span>
                <span v-if="user.username" class="card-username">@{{ user.username }}</span>
              </div>
              <a 
                v-if="user.telegram"
                :href="'https://t.me/' + user.telegram.replace('@', '')" 
                target="_blank" 
                class="card-telegram"
              >
                <i data-lucide="send"></i>
                {{ user.telegram }}
              </a>
            </div>
          </div>
        </div>

        <!-- Mobile: swipe cards -->
        <template v-else>
          <div class="mobile-cards" ref="mobileCardsRef" @scroll="onCardsScroll">
            <div 
              v-for="user in users" 
              :key="user.id" 
              class="mobile-card"
            >
              <div class="mobile-avatar">
                <img v-if="user.avatar_url" :src="getFullUrl(user.avatar_url)" :alt="user.name || ''">
                <span v-else class="avatar-placeholder">{{ (user.name || '?')[0] }}</span>
              </div>
              
              <div class="mobile-info">
                <h2 class="mobile-name">{{ user.name || 'Без имени' }}</h2>
                <span v-if="user.username" class="mobile-username">@{{ user.username }}</span>
                <span v-if="user.department" class="mobile-department">{{ user.department }}</span>
              </div>

              <a 
                v-if="user.telegram"
                :href="'https://t.me/' + user.telegram.replace('@', '')" 
                target="_blank" 
                class="mobile-telegram"
              >
                <i data-lucide="send"></i>
                Написать в Telegram
              </a>
            </div>
          </div>
        </template>
      </main>
    </div>

    <!-- Фиксированные индикаторы над навигацией -->
    <div v-if="isMobile && !loading && users.length > 0" class="mobile-team-footer">
      <div class="team-indicators">
        <button 
          v-for="(user, index) in users" 
          :key="user.id" 
          class="indicator-dot"
          :class="{ active: currentUserIndex === index }"
          @click="scrollToUser(index)"
        >
          <img v-if="user.avatar_url" :src="getFullUrl(user.avatar_url)" :alt="user.name || ''">
          <span v-else class="avatar-placeholder-small">{{ (user.name || '?')[0] }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUpdated } from 'vue'
import { useRoute } from 'vue-router'
import Sidebar from '../components/Sidebar.vue'
import Header from '../components/Header.vue'
import Loader from '../components/ui/Loader.vue'
import { usersApi, getFullUrl } from '../api'
import { useMobile } from '../composables/useMobile'

const route = useRoute()
const { isMobile } = useMobile()

const users = ref([])
const loading = ref(true)
const mobileCardsRef = ref(null)
const currentUserIndex = ref(0)

const fetchUsers = async () => {
  loading.value = true
  try {
    const data = await usersApi.getAll()
    if (data.success) {
      users.value = data.data
    }
  } catch (error) {
    console.error('Ошибка загрузки команды:', error)
  } finally {
    loading.value = false
  }
}

const onCardsScroll = () => {
  if (!mobileCardsRef.value) return
  const container = mobileCardsRef.value
  const cardWidth = container.offsetWidth
  const scrollLeft = container.scrollLeft
  currentUserIndex.value = Math.round(scrollLeft / cardWidth)
}

const scrollToUser = (index) => {
  if (!mobileCardsRef.value) return
  const container = mobileCardsRef.value
  const cardWidth = container.offsetWidth
  container.scrollTo({
    left: index * cardWidth,
    behavior: 'smooth'
  })
}

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

// Загружаем при входе на страницу
watch(() => route.path, async (path) => {
  if (path === '/team') {
    await fetchUsers()
    refreshIcons()
  }
}, { immediate: true })

onUpdated(refreshIcons)
</script>

<style scoped>
.app {
  display: flex;
  min-height: 100vh;
}

.main-wrapper {
  flex: 1;
  margin-left: 64px;
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: 100vh;
}

.main {
  flex: 1;
  padding: 0 20px 20px;
  overflow-y: auto;
  min-height: 0;
}

.main::-webkit-scrollbar {
  width: 6px;
}

.main::-webkit-scrollbar-track {
  background: transparent;
}

.main::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 3px;
}

.main::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.25);
}


.team-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.team-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 24px;
  background: var(--card-bg);
  border: 1px solid var(--border);
  border-radius: 16px;
  transition: all 0.2s ease;
}

.team-card:hover {
  border-color: var(--accent);
}

.card-avatar {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.1);
}

.card-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 600;
  color: var(--text-secondary);
  background: rgba(255, 255, 255, 0.1);
  text-transform: uppercase;
}

.card-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.card-name {
  font-size: 18px;
  font-weight: 600;
  color: var(--text);
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.card-username {
  font-size: 14px;
  color: var(--text-muted);
}

.card-department {
  padding: 2px 8px;
  font-size: 10px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  color: var(--accent);
  background: var(--accent-soft);
  border-radius: 4px;
}

.card-telegram {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 6px 12px;
  background: rgba(0, 136, 204, 0.15);
  color: #0088cc;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  text-decoration: none;
  transition: all 0.15s ease;
  width: fit-content;
}

.card-telegram:hover {
  background: rgba(0, 136, 204, 0.25);
}

.card-telegram i {
  width: 14px;
  height: 14px;
}

/* Mobile styles */
.app.mobile {
  flex-direction: column;
  height: 100vh;
  height: 100dvh;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.app.mobile .main-wrapper {
  margin-left: 0;
  flex: 1;
  min-height: 0;
  max-height: none;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.app.mobile .main {
  flex: 1;
  min-height: 0;
  padding: 0;
  overflow: hidden;
}

/* Mobile swipe cards */
.mobile-cards {
  width: 100%;
  /* Высота = экран - header(60px) - индикаторы(70px) - навигация(64px) - safe-area */
  height: calc(100dvh - 60px - 70px - 64px - var(--safe-area-bottom, 0px));
  display: flex;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.mobile-cards::-webkit-scrollbar {
  display: none;
}

.mobile-card {
  flex: 0 0 100%;
  width: 100%;
  scroll-snap-align: start;
  scroll-snap-stop: always;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24px;
  padding-top: 0;
  gap: 20px;
  box-sizing: border-box;
}

.mobile-avatar {
  width: 160px;
  height: 160px;
  border-radius: 50%;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.1);
  box-shadow: 
    0 0 0 4px rgba(0, 212, 170, 0.3),
    0 20px 60px rgba(0, 0, 0, 0.4);
}

.mobile-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mobile-avatar .avatar-placeholder {
  font-size: 64px;
}

.mobile-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  text-align: center;
}

.mobile-name {
  font-size: 28px;
  font-weight: 700;
  color: var(--text);
  margin: 0;
}

.mobile-username {
  font-size: 16px;
  color: var(--text-muted);
}

.mobile-department {
  padding: 6px 16px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  color: var(--accent);
  background: var(--accent-soft);
  border-radius: 20px;
  margin-top: 4px;
}

.mobile-telegram {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 14px 28px;
  background: linear-gradient(135deg, #0088cc 0%, #00a0dc 100%);
  color: white;
  border-radius: 30px;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  transition: all 0.2s ease;
  box-shadow: 0 8px 24px rgba(0, 136, 204, 0.3);
  margin-top: 8px;
}

.mobile-telegram:active {
  transform: scale(0.96);
}

.mobile-telegram i {
  width: 20px;
  height: 20px;
}

/* Mobile team footer - фиксированный над навигацией */
.mobile-team-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(64px + var(--safe-area-bottom, 0px));
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: var(--bg-body);
  z-index: 100;
}

.team-indicators {
  display: flex;
  justify-content: center;
  gap: 12px;
  flex-wrap: wrap;
}

.team-indicators .indicator-dot {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid transparent;
  padding: 0;
  cursor: pointer;
  transition: all 0.2s ease;
  opacity: 0.5;
}

.team-indicators .indicator-dot img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.team-indicators .indicator-dot.active {
  border-color: var(--accent);
  opacity: 1;
  transform: scale(1.15);
  box-shadow: 0 4px 12px rgba(0, 212, 170, 0.3);
}

.avatar-placeholder-small {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-secondary);
  text-transform: uppercase;
}
</style>
