<template>
  <div class="main-page">
    <!-- Navbar -->
    <nav class="navbar">
      <div class="navbar-left">
        <img :src="logo" alt="EventAI Logo" class="logo" />
      </div>
      <div class="navbar-search">
        <div class="search-box">
          <input
            type="text"
            v-model="searchQuery"
            @input="onSearchInput"
            @focus="showDropdown = true"
            @blur="hideDropdown"
            placeholder="Buscar usuarios..."
            class="search-input"
          />
          <i class="bi bi-search search-icon"></i>
          <ul v-if="showDropdown && filteredAccounts.length > 0" class="search-dropdown">
            <li v-for="account in filteredAccounts" :key="account.id" @mousedown.prevent="goToUserProfile(account)" class="search-result">
              <img :src="account.photo || DEFAULT_AVATAR" class="search-avatar" />
              <span class="search-username">{{ account.username }}</span>
              <span class="search-role">{{ getRoleLabel(account.role) }}</span>
            </li>
          </ul>
        </div>
      </div>
      <div class="navbar-right">
        <button class="nav-button profile" @click="goToProfile">
          <i class="bi bi-person-circle"></i>
          Mi Perfil
        </button>
        <div class="menu-hamburger-wrapper">
          <button class="nav-button hamburger" @click="toggleMenu">
            <i class="bi bi-list"></i>
          </button>
          <div v-if="showMenu" class="dropdown-menu-hamburger" @mouseleave="showMenu = false">
            <button class="dropdown-item" @click="logout">
              <i class="bi bi-box-arrow-right"></i> Cerrar sesión
            </button>
            <button class="dropdown-item" @click="goToHelp">
              <i class="bi bi-question-circle"></i> Ayuda
            </button>
            <button class="dropdown-item" @click="goToContact">
              <i class="bi bi-envelope"></i> Contacto
            </button>
          </div>
        </div>
      </div>
    </nav>

    <!-- Carrusel con título -->
    <div class="carousel-container">
      <div class="carousel">
        <div class="carousel-item"
             v-for="(image, index) in carouselImages"
             :key="index"
             :class="{ active: index === currentImage }"
             :style="{ backgroundImage: `url(${image})` }">
          <div class="carousel-overlay"></div>
          <div class="carousel-content" :class="{ active: index === currentImage }">
            <h1>Bienvenido a EventAI</h1>
            <p class="subtitle">Tu plataforma inteligente para la gestión de eventos</p>
          </div>
        </div>
      </div>
      <div class="carousel-controls">
        <div class="carousel-indicators">
          <span v-for="(_, index) in carouselImages"
                :key="index"
                :class="{ active: index === currentImage }"
                @click="currentImage = index">
          </span>
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="vendor-actions-bg">
      <div class="main-content">
        <div class="vendor-actions-grid">
          <!-- Columna Izquierda -->
          <div class="vendor-actions-col">
            <h3 class="vendor-actions-title">Gestión deServicios</h3>
            <button class="action-button create-service" @click="goToCreateService">
              <i class="bi bi-plus-circle"></i>
              Crear servicio
            </button>
            <button class="action-button view-services" @click="viewServices">
              <i class="bi bi-list-check"></i>
              Ver servicios
            </button>
            <button class="action-button my-services" @click="myServices">
              <i class="bi bi-gear"></i>
              Mis servicios
            </button>
          </div>
          <!-- Columna Centro -->
          <div class="vendor-actions-col center-col">
            <h3 class="vendor-actions-title">Asistente Inteligente</h3>
            <button class="action-button ai-event big-ai-event" @click="createAIEvent">
              <span class="ai-icon-wrapper">
                <i class="bi bi-robot"></i>
              </span>
              <span class="ai-label">Generar evento IA</span>
            </button>
          </div>
          <!-- Columna Derecha -->
          <div class="vendor-actions-col">
            <h3 class="vendor-actions-title">Gestión de Eventos</h3>
            <button class="action-button create-event" @click="createEvent">
              <i class="bi bi-calendar-plus"></i>
              Crear mi evento
            </button>
            <button class="action-button my-events" @click="myEvents">
              <i class="bi bi-calendar-event"></i>
              Mis eventos
            </button>
            <button class="action-button my-spaces" @click="mySpaces">
              <i class="bi bi-house"></i>
              Mis Espacios propios
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Swal from 'sweetalert2'
import UserServices from '../services/UserServices'
import AccountServices from '../services/AccountServices'

const DEFAULT_AVATAR = require('../assets/account_icon.png')

export default {
  data () {
    return {
      logo: require('../assets/LogoEventAiTransGran.png'),
      userInfo: null,
      currentImage: 0,
      carouselImages: [
        require('../assets/foto_horizontal_3colores.jpg'),
        require('../assets/banquete.jpg'),
        require('../assets/masia_event.jpg'),
        require('../assets/banquete.jpg'),
        require('../assets/foto_horizontal_3colores2.jpg'),
        require('../assets/foto_horizontal_3colores3.jpg')
      ],
      searchQuery: '',
      accounts: [],
      filteredAccounts: [],
      showDropdown: false,
      DEFAULT_AVATAR,
      searchTimeout: null,
      showMenu: false
    }
  },
  async created () {
    try {
      this.userInfo = await UserServices.getActualUser()
      this.startCarousel()
    } catch (error) {
      console.error('Error al obtener información del usuario:', error)
      this.$router.push('/login')
    }
  },
  methods: {
    startCarousel () {
      setInterval(() => {
        this.nextImage()
      }, 5000)
    },
    nextImage () {
      this.currentImage = (this.currentImage + 1) % this.carouselImages.length
    },
    prevImage () {
      this.currentImage = (this.currentImage - 1 + this.carouselImages.length) % this.carouselImages.length
    },
    async goToProfile () {
      this.$router.push('/myProfile')
    },
    async createEvent () {
      this.$router.push('/createEvent')
    },
    async createAIEvent () {
      this.$router.push('/intelligentAssistant')
    },
    async viewServices () {
      this.$router.push('/services')
    },
    async myServices () {
      this.$router.push('/myServices')
    },
    async myEvents () {
      this.$router.push('/myEvents')
    },
    async goToCreateService () {
      this.$router.push('/createService')
    },
    async mySpaces () {
      this.$router.push('/myEspaisPropis')
    },
    async logout () {
      try {
        await Swal.fire({
          title: '¿Estás seguro?',
          text: '¿Quieres cerrar sesión?',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#800020',
          cancelButtonColor: '#2C3E50',
          confirmButtonText: 'Sí, cerrar sesión',
          cancelButtonText: 'Cancelar'
        }).then((result) => {
          if (result.isConfirmed) {
            localStorage.removeItem('user')
            localStorage.removeItem('token')
            this.$router.push('/login')
          }
        })
      } catch (error) {
        console.error('Error al cerrar sesión:', error)
      }
    },
    onSearchInput () {
      const q = this.searchQuery.trim().toLowerCase()
      if (this.searchTimeout) clearTimeout(this.searchTimeout)
      if (!q) {
        this.filteredAccounts = []
        return
      }
      this.searchTimeout = setTimeout(async () => {
        try {
          const res = await AccountServices.getAllAccountsByText(q)
          this.filteredAccounts = res.data || []
          this.showDropdown = true
          console.log('[NAVBAR BUSCADOR] Query:', q, '| Resultados:', this.filteredAccounts)
        } catch (e) {
          this.filteredAccounts = []
        }
      }, 250)
    },
    hideDropdown () {
      setTimeout(() => { this.showDropdown = false }, 180)
    },
    goToUserProfile (account) {
      this.searchQuery = ''
      this.filteredAccounts = []
      this.showDropdown = false
      this.$router.push({ path: `/profile/${account.id}` })
    },
    getRoleLabel (role) {
      if (!role) return ''
      if (role.includes('vendor')) return 'Proveedor'
      if (role.includes('client')) return 'Cliente'
      return role.charAt(0).toUpperCase() + role.slice(1)
    },
    toggleMenu () {
      this.showMenu = !this.showMenu
    },
    goToHelp () {
      this.showMenu = false
      this.$router.push('/ayudaFAQ')
    },
    goToContact () {
      this.showMenu = false
      this.$router.push('/contacto')
    }
  }
}
</script>

<style scoped>
.main-page {
  min-height: 100vh;
  background-color: #ffffff;
}

/* Navbar styles */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 2rem;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 1000;
  width: auto;
  backdrop-filter: blur(5px);
}

.navbar-right {
  display: flex;
  align-items: center; /* centra verticalmente */
  gap: 1rem; /* espacio entre botones */
}

.navbar-left .logo {
  height: 80px;
  width: auto;
  cursor: pointer;
}

.navbar-search {
  flex: 1 1 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 2rem;
}

.search-box {
  position: relative;
  width: 320px;
}

.search-input {
  width: 100%;
  padding: 0.5rem 2.2rem 0.5rem 1rem;
  border-radius: 20px;
  border: 1.5px solid #800020;
  font-size: 1rem;
  background: #fff;
  color: #2C3E50;
  outline: none;
  transition: border 0.2s;
  box-sizing: border-box;
}

.search-input:focus {
  border: 2px solid #800020;
}

.search-icon {
  position: absolute;
  right: 0.8rem;
  top: 50%;
  transform: translateY(-50%);
  color: #800020;
  font-size: 1.2rem;
  pointer-events: none;
}

.search-dropdown {
  position: absolute;
  top: 110%;
  left: 0;
  width: 100%;
  min-width: 100%;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 0 0 12px 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  z-index: 100;
  max-height: 220px;
  overflow-y: auto;
  padding: 0.2rem 0;
  box-sizing: border-box;
}

.search-result {
  padding: 0.5rem 1rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.7rem;
  border-bottom: 1px solid #f2f2f2;
  transition: background 0.15s;
}

.search-result:last-child {
  border-bottom: none;
}

.search-result:hover {
  background: #f8e6ee;
}

.search-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  background: #eee;
}

.search-username {
  font-weight: 600;
  color: #800020;
  font-size: 1rem;
}

.search-role {
  font-size: 0.7rem;
  color: #555;
  margin-left: auto;
  font-style: italic;
}

.search-scroll-indicator {
  text-align: center;
  padding: 0.3rem 0;
  color: #888;
  font-size: 0.93rem;
  background: #f7f7f7;
}

.search-scroll-bar {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-button {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.4rem 1rem;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
}

.nav-button i {
  font-size: 1.2rem;
}

.profile {
  background-color: #800020;
  color: white;
}

.profile:hover {
  background-color: #600018;
  transform: translateY(-2px);
}

.logout {
  background-color: rgb(21, 19, 19);
  color: white;
}

.logout:hover {
  background-color: #000;
  transform: translateY(-2px);
}

/* Carrusel styles */
.carousel-container {
  position: relative;
  height: 400px;
  overflow: hidden;
}

.carousel {
  height: 100%;
  position: relative;
}

.carousel-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  opacity: 0;
  transition: opacity 1s ease-in-out;
  z-index: 1;
}

.carousel-item.active {
  opacity: 1;
  z-index: 2;
}

.carousel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2;
}

.carousel-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  z-index: 3;
  width: 80%;
  padding: 2rem;
  border-radius: 15px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.carousel-content.active {
  opacity: 1;
}

.carousel-content h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.carousel-content .subtitle {
  font-size: 1.2rem;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.carousel-controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 3;
  padding: 0.5rem 1rem;
}

.carousel-indicators {
  display: flex;
  gap: 0.8rem;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0.5rem 1rem;
  border-radius: 25px;
}

.carousel-indicators span {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.carousel-indicators span.active {
  background-color: white;
  transform: scale(1.2);
}

.carousel-indicators span:hover {
  background-color: rgba(255, 255, 255, 0.5);
  transform: scale(1.1);
}

/* Main content styles */
.main-content {
  max-width: 1200px;
  margin: 3rem auto;
  padding: 0 1rem;
}

.vendor-actions-bg {
  background-image: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)), url('../assets/fondoPage9.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 500px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.vendor-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 2.5rem;
  margin: 0 auto;
  max-width: 1100px;
  padding: 2.5rem 0 2rem 0;
}
.vendor-actions-col {
  background: rgba(255,255,255,0.5);
  border-radius: 15px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.09);
  padding: 2rem 1.5rem 2.5rem 1.5rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 220px;
}
.vendor-actions-title {
  color: #800020;
  font-size: 1.2rem;
  font-weight: 700;
  margin-bottom: 1.2rem;
  text-align: center;
}
.center-col {
  justify-content: center;
}
.action-button {
  width: 100%;
  margin-bottom: 1.1rem;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 0.8rem;
  padding: 1.1rem;
  border: none;
  border-radius: 12px;
  font-size: 1.08rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0,0,0,0.08);
  background-color: #f8f9fa;
  color: #2C3E50;
}
.action-button i {
  font-size: 1.4rem;
}
.action-button:hover {
  background-color: #800020;
  color: #fff;
}
.create-service, .view-services, .my-services, .create-event, .my-events, .my-spaces {
  background-color: #800020;
  color: #fff;
}
.create-service i, .view-services i, .my-services i, .create-event i, .my-events i, .my-spaces i {
  color: #fff;
}
.create-service:hover, .view-services:hover, .my-services:hover, .create-event:hover, .my-events:hover, .my-spaces:hover {
  background-color: #600018;
  color: #fff;
}
/* Botón IA especial */
.big-ai-event {
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 170px;
  min-width: 220px;
  padding: 2.2rem 1.5rem 2rem 1.5rem;
  font-size: 1.35rem;
  background: linear-gradient(135deg, #800020 60%, #2C3E50 100%);
  color: #fff;
  box-shadow: 0 6px 18px rgba(128,0,32,0.10);
  margin-bottom: 0;
}
.big-ai-event .ai-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.5rem;
}
.big-ai-event i {
  font-size: 3.2rem;
  color: #fff;
}
.big-ai-event .ai-label {
  font-size: 1.25rem;
  font-weight: 700;
  text-align: center;
  letter-spacing: 0.5px;
}
.big-ai-event:hover {
  background: linear-gradient(135deg, #2C3E50 60%, #800020 100%);
  color: #fff;
}
@media (max-width: 900px) {
  .vendor-actions-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  .vendor-actions-col {
    min-width: 0;
    padding: 1.5rem 0.7rem 2rem 0.7rem;
  }
}
.menu-hamburger-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}
.nav-button.hamburger {
  background: black;
  color:rgb(255, 255, 255);
  font-size: 1.7rem;
  padding: 0.4rem 0.8rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
}
.nav-button.hamburger:hover {
  background: #800020;
  color: #fff;
}
.dropdown-menu-hamburger {
  position: absolute;
  top: 120%;
  right: 0;
  background: #800020;
  border: 1px solid #800020;
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(128,0,32,0.10);
  min-width: 180px;
  z-index: 2000;
  display: flex;
  flex-direction: column;
  padding: 0.5rem 0;
}
.dropdown-item {
  background: none;
  border: none;
  color: #fff;
  font-size: 1rem;
  padding: 0.7rem 1.2rem;
  text-align: left;
  display: flex;
  align-items: center;
  gap: 0.7rem;
  cursor: pointer;
  transition: background 0.18s, color 0.18s;
}
.dropdown-item i {
  color: #fff;
  font-size: 1.2rem;
}
.dropdown-item:hover {
  background: #fff;
  color: #800020;
}
.dropdown-item:hover i {
  color: #800020;
}
</style>
