<template>
  <div class="page-container" @mousemove="handleMouseMove">
    <!-- Navbar -->
    <nav class="navbar" :class="{ 'navbar-hidden': isNavbarHidden }">
      <div class="navbar-left">
        <img :src="logo" alt="EventAI Logo" class="logo" @click="$router.push('/mainPageVendor')" />
      </div>
      <div class="navbar-center">
        <h1>Crear Evento</h1>
      </div>
      <div class="navbar-right">
        <button class="nav-button back" @click="$router.back()">
          <i class="bi bi-arrow-left"></i>
          Volver
        </button>
      </div>
    </nav>

    <!-- Main Content -->
    <div class="main-content">
      <form @submit.prevent="handleSubmit" class="event-form">
        <!-- Información Básica -->
        <div class="form-section">
          <h2>Información Básica</h2>
          <div class="form-grid basic-info">
            <div class="form-group">
              <label for="name">Nombre del Evento</label>
              <input
                type="text"
                id="name"
                v-model="eventData.name"
                required
                placeholder="Ej: Boda María y Juan"
              >
            </div>

            <div class="form-group">
              <label for="type">Tipo de Evento</label>
              <select id="type" v-model="eventData.type" required>
                <option value="">Selecciona un tipo</option>
                <option v-for="type in eventTypes" :key="type.value" :value="type.value">
                  {{ type.label }}
                </option>
              </select>
            </div>

            <div class="form-group">
              <label for="startDate">Fecha de Inicio</label>
              <input
                type="date"
                id="startDate"
                v-model="eventData.startDate"
                required
                :min="minDate"
              >
            </div>

            <div class="form-group">
              <label for="startTime">Hora de Inicio</label>
              <input
                type="time"
                id="startTime"
                v-model="eventData.startTime"
                required
              >
            </div>

            <div class="form-group">
              <label for="endDate">Fecha de Fin</label>
              <input
                type="date"
                id="endDate"
                v-model="eventData.endDate"
                required
                :min="eventData.startDate"
              >
            </div>

            <div class="form-group">
              <label for="endTime">Hora de Fin</label>
              <input
                type="time"
                id="endTime"
                v-model="eventData.endTime"
                required
              >
            </div>

            <div class="form-group">
              <label for="guests">Número de Invitados</label>
              <input
                type="number"
                id="guests"
                v-model="eventData.num_invitats"
                required
                min="1"
              >
            </div>

            <div class="form-group">
              <label class="checkbox-label space-own-label">
                <input
                  type="checkbox"
                  v-model="eventData.has_espai_propi"
                >
                <span class="checkbox-text">Espacio Propio</span>
              </label>
            </div>
          </div>
        </div>

        <!-- Espacio Propio -->
        <div v-if="eventData.has_espai_propi" class="form-section">
          <h2>Información del Espacio Propio</h2>
          <!-- Selección de tipo de espacio -->
          <div class="space-type-selection">
            <h3>¿Qué tipo de espacio deseas utilizar?</h3>
            <div class="space-type-options">
              <button
                type="button"
                class="space-type-button"
                :class="{ active: eventData.useExistingSpace === true }"
                @click="eventData.useExistingSpace = true"
              >
                <i class="bi bi-building"></i>
                <span>Usar Espacio Propio Existente</span>
              </button>
              <button
                type="button"
                class="space-type-button"
                :class="{ active: eventData.useExistingSpace === false }"
                @click="eventData.useExistingSpace = false"
              >
                <i class="bi bi-plus-circle"></i>
                <span>Crear Nuevo Espacio Propio</span>
              </button>
            </div>
          </div>

          <!-- Espacio Existente -->
          <div v-if="eventData.useExistingSpace" class="existing-space-section">
            <div v-if="loading" class="loading-spinner">
              <i class="bi bi-arrow-repeat"></i>
              <span>Cargando espacios propios...</span>
            </div>
            <div v-else-if="userSpaces.length === 0" class="no-spaces-message">
              <i class="bi bi-building-x"></i>
              <h3>No tienes espacios propios creados</h3>
              <p>Para usar un espacio existente, primero debes crear uno.</p>
              <button
                type="button"
                class="button secondary small"
                @click="eventData.useExistingSpace = false"
              >
                Crear Nuevo Espacio Propio
              </button>
            </div>
            <div v-else class="spaces-table-container">
              <table class="spaces-table">
                <thead>
                  <tr>
                    <th>Nombre</th>
                    <th>Tipo</th>
                    <th>Capacidad</th>
                    <th>Ubicación</th>
                    <th>Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="space in userSpaces"
                    :key="space.id"
                    :class="{ selected: eventData.selectedSpace === space.id }"
                  >
                    <td>{{ space.nombre }}</td>
                    <td>{{ space.tipus }}</td>
                    <td>{{ space.capacitat }} persones</td>
                    <td class="location-cell">
                      <span class="location-text">{{ space.address.direccion }}, {{ space.address.codigo_postal }} {{ space.address.ciudad }}, {{ space.address.provincia }}</span>
                    </td>
                    <td class="actions-cell">
                      <button
                        type="button"
                        class="action-button use"
                        @click="toggleSpaceSelection(space.id)"
                        :class="{ active: eventData.selectedSpace === space.id }"
                      >
                        <i :class="eventData.selectedSpace === space.id ? 'bi bi-check-circle-fill' : 'bi bi-check-circle'"></i>
                        {{ eventData.selectedSpace === space.id ? 'Seleccionado' : 'Usar' }}
                      </button>
                      <button
                        type="button"
                        class="action-button view"
                        @click.stop="viewSpaceDetails(space)"
                      >
                        <i class="bi bi-eye"></i>
                      </button>
                      <button
                        type="button"
                        class="action-button delete"
                        @click.stop="deleteSpace(space.id)"
                      >
                        <i class="bi bi-trash"></i>
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Nuevo Espacio -->
          <div v-else>
            <!-- Información Principal -->
            <div class="form-grid space-main-info">
              <div class="form-group">
                <label for="spaceType">Tipo de Espacio</label>
                <select id="spaceType" v-model="eventData.spaceType" required>
                  <option value="">Selecciona un tipo</option>
                  <option v-for="type in spaceTypes" :key="type.value" :value="type.value">
                    {{ type.label }}
                  </option>
                </select>
              </div>

              <div class="form-group">
                <label for="spaceName">Nombre del Espacio</label>
                <input
                  type="text"
                  id="spaceName"
                  v-model="eventData.spaceName"
                  required
                >
              </div>

              <div class="form-group">
                <label for="spaceCapacity">Capacidad Aproximada</label>
                <input
                  type="number"
                  id="spaceCapacity"
                  v-model="eventData.spaceCapacity"
                  required
                  min="1"
                >
              </div>
            </div>

            <!-- Dirección -->
            <div class="form-section address-section">
              <h3>Dirección</h3>
              <div class="form-grid address-grid">
                <div class="form-group full-width">
                  <label for="spaceAddress">Dirección</label>
                  <input
                    type="text"
                    id="spaceAddress"
                    v-model="eventData.spaceAddress"
                    required
                    placeholder="Calle y número"
                  >
                </div>

                <div class="form-group">
                  <label for="spaceCity">Ciudad</label>
                  <input
                    type="text"
                    id="spaceCity"
                    v-model="eventData.spaceCity"
                    required
                  >
                </div>

                <div class="form-group">
                  <label for="spacePostalCode">Código Postal</label>
                  <input
                    type="text"
                    id="spacePostalCode"
                    v-model="eventData.spacePostalCode"
                    required
                    pattern="[0-9]{5}"
                  >
                </div>

                <div class="form-group">
                  <label for="spaceProvince">Provincia</label>
                  <input
                    type="text"
                    id="spaceProvince"
                    v-model="eventData.spaceProvince"
                    required
                  >
                </div>
              </div>
            </div>

            <!-- Descripción -->
            <div class="form-section description-section">
              <h3>Descripción</h3>
              <div class="form-group">
                <textarea
                  id="spaceDescription"
                  v-model="eventData.spaceDescription"
                  required
                  rows="4"
                  placeholder="Describe las características principales del espacio"
                ></textarea>
              </div>
            </div>

            <!-- Características -->
            <div class="form-section features-section">
              <h3>Características</h3>
              <div class="features-grid">
                <div v-for="feature in spaceFeatures" :key="feature.value" class="feature-checkbox">
                  <input
                    type="checkbox"
                    :id="feature.value"
                    v-model="eventData.spaceFeatures"
                    :value="feature.value"
                  >
                  <label :for="feature.value">
                    <i :class="feature.icon"></i>
                    {{ feature.label }}
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Botones de Acción -->
        <div class="form-actions">
          <button type="submit" class="button primary">
            Crear Evento
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import Swal from 'sweetalert2'
import EventServices from '../services/EventServices'
import EspaiPropiServices from '../services/EspaiPropiServices'
import EspaiPropiDetails from './event_services/EspaiPropiDetails.vue'

export default {
  name: 'CreateEvent',
  components: {
    EspaiPropiDetails
  },
  data () {
    return {
      logo: require('../assets/LogoEventAiTransGran.png'),
      eventData: {
        name: '',
        type: '',
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        num_invitats: '',
        has_espai_propi: false,
        useExistingSpace: true,
        selectedSpace: '',
        // Campos del espacio propio
        spaceType: '',
        spaceName: '',
        spaceAddress: '',
        spaceCity: '',
        spacePostalCode: '',
        spaceProvince: '',
        spaceCapacity: '',
        spaceDescription: '',
        spaceFeatures: []
      },
      eventTypes: [
        { value: 'boda', label: 'Boda' },
        { value: 'graduacio', label: 'Graduación' },
        { value: 'festa', label: 'Fiesta' },
        { value: 'celebracio', label: 'Celebración' },
        { value: 'menjar_grup', label: 'Comida de Grupo' },
        { value: 'altres', label: 'Otros' }
      ],
      spaceTypes: [
        { value: 'sala_privada', label: 'Sala Privada' },
        { value: 'finca', label: 'Finca' },
        { value: 'terraza', label: 'Terraza' },
        { value: 'salon', label: 'Salón' },
        { value: 'casa_particular', label: 'Casa Particular' },
        { value: 'jardin_privado', label: 'Jardín Privado' },
        { value: 'azotea', label: 'Azotea' },
        { value: 'piso', label: 'Piso' },
        { value: 'casa_rural', label: 'Casa Rural' },
        { value: 'nave_industrial', label: 'Nave Industrial' },
        { value: 'parcela', label: 'Parcela' },
        { value: 'local_propio', label: 'Local Propio' },
        { value: 'masia', label: 'Masía' },
        { value: 'otro', label: 'Otro' }
      ],
      spaceFeatures: [
        // 1. Ubicación / Tipo de Espacio
        { value: 'interior', label: 'Interior', icon: 'bi bi-house-door' },
        { value: 'exterior', label: 'Exterior', icon: 'bi bi-tree' },
        { value: 'both', label: 'Interior y Exterior', icon: 'bi bi-house-door-fill' },
        { value: 'natural_light', label: 'Luz Natural', icon: 'bi bi-sun' },

        // 2. Accesos / Transporte
        { value: 'car', label: 'Acceso en Coche', icon: 'bi bi-truck' },
        { value: 'bus', label: 'Acceso para Autocares', icon: 'bi bi-truck' },
        { value: 'motorcycle', label: 'Acceso en Moto', icon: 'bi bi-bicycle' },
        { value: 'wheelchair', label: 'Accesible en Silla de Ruedas', icon: 'bi bi-person-wheelchair' },
        { value: 'loading', label: 'Zona de Carga y Descarga', icon: 'bi bi-truck' },
        { value: 'parking', label: 'Parking Disponible', icon: 'bi bi-p-circle' },
        { value: 'free_parking', label: 'Parking Gratuito', icon: 'bi bi-p-circle-fill' },
        { value: 'elevator', label: 'Ascensor Disponible', icon: 'bi bi-arrow-up-circle' },

        // 3. Comodidades
        { value: 'heating', label: 'Calefacción', icon: 'bi bi-thermometer' },
        { value: 'ac', label: 'Aire Acondicionado', icon: 'bi bi-snow' },
        { value: 'smoking', label: 'Zona para Fumar', icon: 'bi bi-fire' },
        { value: 'piscina', label: 'Piscina', icon: 'bi bi-water' },
        { value: 'wifi', label: 'WiFi Disponible', icon: 'bi bi-wifi' },
        { value: 'storage', label: 'Espacio de Almacenaje', icon: 'bi bi-box' },
        { value: 'bathroom_adapted', label: 'Baños Adaptados', icon: 'bi bi-toilet' },
        { value: 'security', label: 'Seguridad / Vigilancia', icon: 'bi bi-shield' },
        { value: 'cloakroom', label: 'Guardarropa / Ropero', icon: 'bi bi-bag' },
        { value: 'cleaning_service', label: 'Servicio de Limpieza', icon: 'bi bi-broom' },

        // 4. Estilo / Ambiente
        { value: 'functional', label: 'Funcional', icon: 'bi bi-gear' },
        { value: 'modern', label: 'Moderno', icon: 'bi bi-stars' },
        { value: 'futuristic', label: 'Futurista', icon: 'bi bi-rocket' },
        { value: 'historical', label: 'Histórico', icon: 'bi bi-building' },
        { value: 'vintage', label: 'Vintage', icon: 'bi bi-clock-history' },
        { value: 'private', label: 'Espacio Privado / Exclusivo', icon: 'bi bi-lock' },

        // 5. Capacidad / Uso
        { value: 'standing_capacity', label: 'Capacidad en Pie', icon: 'bi bi-people' },
        { value: 'seating_capacity', label: 'Capacidad Sentados', icon: 'bi bi-person' },
        { value: 'modular_space', label: 'Espacio Modular', icon: 'bi bi-grid' },

        // 6. Extras para eventos
        { value: 'pet_friendly', label: 'Se Admiten Mascotas', icon: 'bi bi-heart' },
        { value: 'child_friendly', label: 'Espacio para Niños', icon: 'bi bi-emoji-smile' },
        { value: 'dance_floor', label: 'Pista de Baile', icon: 'bi bi-music-note' },
        { value: 'games', label: 'Zona de Juegos', icon: 'bi bi-controller' },
        { value: 'photo_spot', label: 'Zona para Fotos', icon: 'bi bi-camera' }
      ],
      userSpaces: [], // Aquí se cargarán los espacios del usuario
      loading: false,
      isNavbarHidden: false,
      lastScrollTop: 0,
      scrollTimeout: null,
      mouseY: 0
    }
  },
  computed: {
    minDate () {
      const today = new Date()
      return today.toISOString().split('T')[0]
    }
  },
  async created () {
    // Cargar los espacios propios del usuario al iniciar el componente
    await this.loadUserSpaces()
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll () {
      if (this.scrollTimeout) {
        clearTimeout(this.scrollTimeout)
      }

      this.scrollTimeout = setTimeout(() => {
        const element = document.getElementById('service-type-selector')
        if (element) {
          const rect = element.getBoundingClientRect()
          const isVisible = rect.top >= 0 && rect.bottom <= window.innerHeight
          this.isNavbarHidden = !isVisible
        } else {
          const currentScroll = window.pageYOffset || document.documentElement.scrollTop

          if (currentScroll <= 200) {
            this.isNavbarHidden = false
            this.lastScrollTop = currentScroll
            return
          }

          const scrollDifference = this.lastScrollTop - currentScroll

          if (currentScroll > this.lastScrollTop && currentScroll > 200) {
            this.isNavbarHidden = true
          } else if (scrollDifference > 10) {
            this.isNavbarHidden = false
          }

          this.lastScrollTop = currentScroll <= 0 ? 0 : currentScroll
        }
      }, 50)
    },
    handleMouseMove (event) {
      this.mouseY = event.clientY
      // Mostrar la barra cuando el ratón está en los primeros 100px de la ventana
      this.isNavbarHidden = this.mouseY > 110
    },
    async handleSubmit () {
      try {
        if (!this.validateForm()) {
          return
        }

        const eventPayload = {
          name: this.eventData.name,
          tipus: this.eventData.type,
          pressupost: 0, // Por defecto 0, se puede añadir campo después
          data_inici: `${this.eventData.startDate}T${this.eventData.startTime}`,
          data_fi: `${this.eventData.endDate}T${this.eventData.endTime}`,
          num_invitats: parseInt(this.eventData.num_invitats)
        }

        // Si tiene espacio propio
        if (this.eventData.has_espai_propi) {
          if (this.eventData.useExistingSpace) {
            // Si usa un espacio existente, solo añadir el ID
            eventPayload.espai_propi_id = this.eventData.selectedSpace
          } else {
            // Si crea un nuevo espacio, añadir toda la información
            eventPayload.espai_propi = {
              nombre: this.eventData.spaceName,
              tipus: this.eventData.spaceType,
              address: {
                direccion: this.eventData.spaceAddress,
                ciudad: this.eventData.spaceCity,
                codigo_postal: this.eventData.spacePostalCode,
                provincia: this.eventData.spaceProvince
              },
              descripcion: this.eventData.spaceDescription,
              capacitat_aproximada: parseInt(this.eventData.spaceCapacity),
              caracteristicas: this.eventData.spaceFeatures
            }
          }
        }

        const response = await EventServices.create(eventPayload)
        const eventId = response.id

        await Swal.fire({
          title: '¡Evento creado!',
          text: 'Tu evento se ha creado correctamente',
          icon: 'success',
          confirmButtonColor: '#800020'
        })

        this.$router.push(`/eventServices/${eventId}`)
      } catch (error) {
        console.error('Error al crear el evento:', error)
        Swal.fire({
          title: 'Error',
          text: 'Ha ocurrido un error al crear el evento',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    validateForm () {
      // Validación de campos requeridos básicos
      const requiredFields = ['name', 'type', 'startDate', 'startTime', 'endDate', 'endTime', 'num_invitats']
      const missingFields = requiredFields.filter(field => !this.eventData[field])

      if (missingFields.length > 0) {
        Swal.fire({
          title: 'Campos requeridos',
          text: 'Por favor, completa todos los campos obligatorios',
          icon: 'warning',
          confirmButtonColor: '#800020'
        })
        return false
      }

      // Validación de tipo de evento
      if (this.eventData.type === '') {
        Swal.fire({
          title: 'Tipo de evento',
          text: 'Por favor, selecciona un tipo de evento',
          icon: 'warning',
          confirmButtonColor: '#800020'
        })
        return false
      }

      // Validación de fechas
      const startDateTime = new Date(`${this.eventData.startDate}T${this.eventData.startTime}`)
      const endDateTime = new Date(`${this.eventData.endDate}T${this.eventData.endTime}`)
      if (startDateTime >= endDateTime) {
        Swal.fire({
          title: 'Fechas inválidas',
          text: 'La fecha y hora de inicio debe ser anterior a la fecha y hora de fin',
          icon: 'warning',
          confirmButtonColor: '#800020'
        })
        return false
      }

      if (startDateTime < new Date()) {
        Swal.fire({
          title: 'Fecha inválida',
          text: 'La fecha de inicio debe ser futura',
          icon: 'warning',
          confirmButtonColor: '#800020'
        })
        return false
      }

      // Validación de espacio propio si está marcado
      if (this.eventData.has_espai_propi) {
        if (this.eventData.useExistingSpace) {
          // Si se usa un espacio existente, solo validar que se haya seleccionado uno
          if (!this.eventData.selectedSpace) {
            Swal.fire({
              title: 'Espacio no seleccionado',
              text: 'Por favor, selecciona un espacio existente',
              icon: 'warning',
              confirmButtonColor: '#800020'
            })
            return false
          }
        } else {
          // Si se crea un nuevo espacio, validar todos los campos del espacio
          const spaceFields = [
            'spaceType', 'spaceName', 'spaceAddress', 'spaceCity',
            'spacePostalCode', 'spaceProvince', 'spaceCapacity',
            'spaceDescription', 'spaceFeatures'
          ]
          const missingSpaceFields = spaceFields.filter(field => !this.eventData[field])

          if (missingSpaceFields.length > 0) {
            Swal.fire({
              title: 'Información del espacio',
              text: 'Por favor, completa todos los campos del espacio propio',
              icon: 'warning',
              confirmButtonColor: '#800020'
            })
            return false
          }
        }
      }

      return true
    },
    async loadUserSpaces () {
      try {
        this.loading = true
        const response = await EspaiPropiServices.getMyEspaiPropis()
        // Cambiar el nombre del evento si hay espacios propios disponibles
        console.log('Espacios propios:', response)
        this.userSpaces = response.data || []
      } catch (error) {
        console.error('Error al cargar los espacios propios:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los espacios propios',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      } finally {
        this.loading = false
      }
    },
    toggleSpaceSelection (spaceId) {
      if (this.eventData.selectedSpace === spaceId) {
        this.eventData.selectedSpace = ''
      } else {
        this.eventData.selectedSpace = spaceId
      }
    },
    async viewSpaceDetails (space) {
      try {
        const spaceDetails = await EspaiPropiServices.getEspaiPropiById(space.id)
        // Renderizar el componente EspaiPropiDetails en el modal
        const container = document.createElement('div')
        const EspaiPropiClass = this.$options.components.EspaiPropiDetails
        const vm = new this.$root.constructor({
          render: h => h(EspaiPropiClass, { props: { espai: spaceDetails } })
        }).$mount(container)
        await Swal.fire({
          title: '',
          html: vm.$el,
          width: '700px',
          showConfirmButton: true,
          confirmButtonColor: '#800020',
          customClass: {
            container: 'space-details-modal'
          }
        })
      } catch (error) {
        console.error('Error al cargar los detalles del espacio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudieron cargar los detalles del espacio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    },
    async deleteSpace (spaceId) {
      try {
        // Primero verificar si el espacio está en uso
        const events = await EventServices.getMyEvents()
        const spaceInUse = events.data.some(event => event.espai_propi_id === spaceId)

        if (spaceInUse) {
          await Swal.fire({
            title: 'No se puede eliminar',
            text: 'Este espacio está siendo utilizado en uno o más eventos y no puede ser eliminado',
            icon: 'warning',
            confirmButtonColor: '#800020'
          })
          return
        }

        const result = await Swal.fire({
          title: '¿Estás seguro?',
          text: 'Esta acción no se puede deshacer',
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#800020',
          cancelButtonColor: '#666',
          confirmButtonText: 'Sí, eliminar',
          cancelButtonText: 'Cancelar'
        })

        if (result.isConfirmed) {
          await EspaiPropiServices.deleteEspaiPropi(spaceId)
          // Si el espacio eliminado era el seleccionado, deseleccionarlo
          if (this.eventData.selectedSpace === spaceId) {
            this.eventData.selectedSpace = ''
          }
          // Recargar la lista de espacios
          await this.loadUserSpaces()

          await Swal.fire({
            title: '¡Eliminado!',
            text: 'El espacio ha sido eliminado correctamente',
            icon: 'success',
            confirmButtonColor: '#800020'
          })
        }
      } catch (error) {
        console.error('Error al eliminar el espacio:', error)
        Swal.fire({
          title: 'Error',
          text: 'No se pudo eliminar el espacio',
          icon: 'error',
          confirmButtonColor: '#800020'
        })
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  padding-top: 140px;
  min-height: 100vh;
  background: #f8f9fa;
  background-image: url('../assets/fondoPage3.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  background-repeat: no-repeat;
  max-height: auto;
}

.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: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  width: auto;
  margin-bottom: 2rem;
  backdrop-filter: blur(5px);
  transition: transform 0.3s ease-in-out;
}

.navbar-hidden {
  transform: translateY(-100%);
}

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

.navbar-center h1 {
  color: #800020;
  font-size: 2rem;
  margin: 0;
  flex-grow: 1;
  text-align: center;
}

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

.back {
  background-color: #2C3E50;
  color: white;
}

.back:hover {
  background-color: #1a252f;
  transform: translateY(-2px);
}

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

h1 {
  color: #800020;
  text-align: center;
  margin-bottom: 2rem;
  font-size: 2rem;
}

.form-section {
  background-color: white;
  padding: 2.5rem;
  border-radius: 20px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  margin-bottom: 2.5rem;
  transition: transform 0.3s ease;
  border: 1px solid #800020;
}

.form-section:hover {
  transform: translateY(-2px);
}

.form-section h2 {
  color: #800020;
  margin-bottom: 2rem;
  font-size: 1.5rem;
  text-align: center;
  position: relative;
  padding-bottom: 0.5rem;
}

.form-section h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background-color: #800020;
  border-radius: 2px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}

label {
  font-weight: 600;
  color: #2C3E50;
  font-size: 1.1rem;
}

input, select, textarea {
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 1.1rem;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
}

input:focus, select:focus, textarea:focus {
  outline: none;
  border-color: #800020;
  box-shadow: 0 0 0 3px rgba(128, 0, 32, 0.1);
  background-color: white;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-top: 1rem;
}

.feature-checkbox {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
}

.feature-checkbox:hover {
  border-color: #800020;
  background-color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(128, 0, 32, 0.1);
}

.feature-checkbox input[type="checkbox"] {
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: #800020;
}

.feature-checkbox label {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  cursor: pointer;
  font-weight: 500;
  font-size: 1rem;
  flex: 1;
}

.feature-checkbox i {
  font-size: 1.4rem;
  color: #800020;
  width: 24px;
  text-align: center;
}

.feature-checkbox:hover i {
  transform: scale(1.1);
  transition: transform 0.3s ease;
}

/* Form actions */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  margin-top: 2rem;
}

.button {
  padding: 1.2rem 2.5rem;
  border: none;
  border-radius: 12px;
  font-size: 1.2rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.button.primary {
  background-color: #800020;
  color: white;
  box-shadow: 0 4px 6px rgba(128, 0, 32, 0.2);
}

.button.primary:hover {
  background-color: #600018;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(128, 0, 32, 0.3);
}

.button.secondary {
  background-color: #2C3E50;
  color: white;
  box-shadow: 0 4px 6px rgba(44, 62, 80, 0.2);
}

.button.secondary:hover {
  background-color: #1a252f;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(44, 62, 80, 0.3);
}

.button.small {
  padding: 0.75rem 1rem;
  font-size: 0.75rem;
}

/* Responsive design */
@media (max-width: 768px) {
  .navbar {
    padding: 1rem;
  }

  .navbar-left .logo {
    height: 40px;
  }

  .main-content {
    margin: 1rem auto;
  }

  .form-section {
    padding: 1.5rem;
  }

  .features-grid {
    grid-template-columns: 1fr;
  }

  .button {
    width: 100%;
    padding: 1rem;
  }
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  margin-top: 0.5rem;
}

.checkbox-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.checkbox-item input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  color: #2C3E50;
}

.checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.basic-info {
  grid-template-columns: repeat(4, 1fr);
}

.space-main-info {
  grid-template-columns: repeat(3, 1fr);
}

.address-section, .description-section, .features-section {
  background-color: #f8f9fa;
  padding: 1.5rem;
  border-radius: 15px;
  margin-top: 1.5rem;
}

.address-section h3, .description-section h3, .features-section h3 {
  color: #800020;
  margin-bottom: 1rem;
  font-size: 1.2rem;
  text-align: center;
}

.address-grid {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  gap: 1rem;
  align-items: start;
}

.form-group.full-width {
  grid-column: auto;
}

@media (max-width: 1200px) {
  .address-grid {
    grid-template-columns: 1fr 1fr;
  }
  .form-group.full-width {
    grid-column: 1 / -1;
  }
}

@media (max-width: 768px) {
  .address-grid {
    grid-template-columns: 1fr;
  }
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
}

@media (max-width: 1200px) {
  .basic-info {
    grid-template-columns: repeat(2, 1fr);
  }
  .address-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  .features-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .basic-info, .space-main-info, .address-grid {
    grid-template-columns: 1fr;
  }
  .features-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.space-own-label {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
  cursor: pointer;
}

.space-own-label:hover {
  border-color: #800020;
  background-color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(128, 0, 32, 0.1);
}

.space-own-label input[type="checkbox"] {
  width: 24px;
  height: 24px;
  cursor: pointer;
  accent-color: #800020;
}

.checkbox-text {
  font-size: 1.2rem;
  font-weight: 600;
  color: #2C3E50;
  margin-top: 1rem;
  margin-bottom: 1rem;
}

.space-type-selection {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: #f8f9fa;
  border-radius: 15px;
}

.space-type-selection h3 {
  color: #800020;
  margin-bottom: 1rem;
  font-size: 1.2rem;
  text-align: center;
}

.space-type-options {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.space-type-button {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  padding: 1rem 1.5rem;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background-color: white;
  color: #2C3E50;
  font-size: 1.1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.space-type-button i {
  font-size: 1.4rem;
  color: #800020;
}

.space-type-button:hover {
  border-color: #800020;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(128, 0, 32, 0.1);
}

.space-type-button.active {
  background-color: #800020;
  border-color: #800020;
  color: white;
}

.space-type-button.active i {
  color: white;
}

.existing-space-section {
  margin-top: 1.5rem;
  padding: 1.5rem;
  background-color: #f8f9fa;
  border-radius: 15px;
}

.existing-space-section select {
  width: 100%;
  padding: 1rem;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 1.1rem;
  transition: all 0.3s ease;
}

.existing-space-section select:focus {
  border-color: #800020;
  box-shadow: 0 0 0 3px rgba(128, 0, 32, 0.1);
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  padding: 2rem;
  color: #800020;
}

.loading-spinner i {
  font-size: 2rem;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.no-spaces-message {
  text-align: center;
  padding: 2rem;
  background-color: #f8f9fa;
  border-radius: 12px;
}

.no-spaces-message i {
  font-size: 3rem;
  color: #800020;
  margin-bottom: 1rem;
}

.no-spaces-message h3 {
  color: #2C3E50;
  margin-bottom: 0.5rem;
}

.no-spaces-message p {
  color: #666;
  margin-bottom: 1.5rem;
}

.spaces-table-container {
  overflow-x: auto;
  margin-top: 1rem;
}

.spaces-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.spaces-table th,
.spaces-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.spaces-table th {
  background-color: #800020;
  color: white;
  font-weight: 600;
}

.spaces-table tr:hover {
  background-color: #f8f9fa;
  cursor: pointer;
}

.spaces-table tr.selected {
  background-color: rgba(128, 0, 32, 0.1);
}

.location-cell {
  max-width: 300px;
}

.location-text {
  font-size: 0.9rem;
  color: #666;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.actions-cell {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-start;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  padding: 0.5rem 0.8rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.action-button.use {
  background-color: #800020;
  color: white;
}

.action-button.use:hover {
  background-color: #600018;
}

.action-button.use.active {
  background-color: #4CAF50;
}

.action-button.delete {
  background-color: #dc3545;
  color: white;
}

.action-button.delete:hover {
  background-color: #c82333;
}

.action-button i {
  font-size: 1rem;
}

.action-button.view {
  background-color:rgb(0, 128, 255);
  color: white;
}

.action-button.view:hover {
  background-color:rgb(0, 73, 142);
}

.space-details {
  text-align: left;
  padding: 1rem;
}

.space-details p {
  margin: 0.5rem 0;
}

.features-list {
  margin-top: 1rem;
}

.features-list ul {
  list-style: none;
  padding-left: 1rem;
  margin: 0.5rem 0;
}

.features-list li {
  margin: 0.3rem 0;
  color: #666;
}

:deep(.space-details-modal) {
  max-width: 600px;
}
</style>
