<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 Nuevo Servicio</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>

    <div class="create-service-page">
      <!-- Selector de tipo de servicio -->
      <div id="service-type-selector" class="service-type-selector">
        <h2>Selecciona el tipo de servicio</h2>
        <div class="service-types">
          <button
            class="type-button"
            :class="{ active: selectedType === 'espai' }"
            @click="selectType('espai')"
          >
            <i class="bi bi-house"></i>
            <span>Espacio</span>
          </button>
          <button
            class="type-button"
            :class="{ active: selectedType === 'catering' }"
            @click="selectType('catering')"
          >
            <img v-if="this.selectedType === 'catering'" :src="iconCateringInverse" class="service-type-img" alt="Icono catering">
            <img v-else :src="iconCatering" class="service-type-img" alt="Icono catering">
            <span>Catering</span>
          </button>
          <button
            class="type-button"
            :class="{ active: selectedType === 'mobiliari' }"
            @click="selectType('mobiliari')"
          >
            <img v-if="this.selectedType === 'mobiliari'" :src="iconMobiliariInverse" class="service-type-img" alt="Icono mobiliari">
            <img v-else :src="iconMobiliari" class="service-type-img" alt="Icono mobiliari">
            <span>Mobiliario</span>
          </button>
          <button
            class="type-button"
            :class="{ active: selectedType === 'decoracio' }"
            @click="selectType('decoracio')"
          >
            <i class="bi bi-flower1"></i>
            <span>Decoración</span>
          </button>
          <button
            class="type-button"
            :class="{ active: selectedType === 'musica' }"
            @click="selectType('musica')"
          >
            <i class="bi bi-music-note-beamed"></i>
            <span>Música</span>
          </button>
          <button
            class="type-button"
            :class="{ active: selectedType === 'fotografia' }"
            @click="selectType('fotografia')"
          >
            <i class="bi bi-camera"></i>
            <span>Fotografía</span>
          </button>
        </div>
        <p v-if="!selectedType" class="service-type-message">
          <i class="bi bi-info-circle"></i>
          Seleccione un tipo de servicio para empezar a crearlo
        </p>
      </div>

      <!-- Formulario común para todos los servicios -->
      <div v-if="selectedType" class="service-form-container">
        <div class="form-card">
          <h5 class="avis-campos">* campo obligatorio</h5>
          <!-- Botón de Vaciar -->
          <h5 class="avis-campos">
            <button class="btn-clear" @click="clearAllData">
              <i class="bi bi-arrow-clockwise"></i>
              Vaciar todos los datos
            </button>
          </h5>
          <!-- Información General -->
          <div class="form-section">
            <h3><i class="bi bi-info-circle"></i> Información General</h3>

            <!-- Nombre -->
            <div class="form-group">
              <label for="name">
                <i class="bi bi-tag"></i> Nombre del Servicio*
              </label>
              <input
                id="name"
                v-model="commonData.name"
                type="text"
                class="form-control"
                required
              />
            </div>

            <!-- Descripción -->
            <div class="form-group">
              <label for="description">
                <i class="bi bi-card-text"></i> Descripción*
              </label>
              <textarea
                id="description"
                v-model="commonData.description"
                class="form-control"
                rows="4"
                required
              ></textarea>
            </div>

            <!-- Imágenes -->
            <div class="form-group">
              <label>
                <i class="bi bi-images"></i> Imágenes*
              </label>
              <button class="btn-upload" @click="triggerImageUpload">
                <i class="bi bi-cloud-upload"></i>
                Subir Imágenes
              </button>
              <input
                type="file"
                ref="imageInput"
                @change="handleImageUpload"
                accept="image/*"
                multiple
                style="display: none"
              />

              <div class="image-preview-container" v-if="imagePreviews.length">
                <div class="image-preview-scroll">
                  <div class="image-preview-grid">
                    <div
                      v-for="(image, index) in imagePreviews"
                      :key="index"
                      class="image-preview-item"
                    >
                      <img :src="image" alt="Preview" />
                      <button @click="removeImage(index)" class="remove-image">
                        <i class="bi bi-x"></i>
                      </button>
                    </div>
                  </div>
                </div>
                <small class="text-muted">{{ imagePreviews.length }}/30 imágenes</small>
              </div>
            </div>
          </div>

          <!-- Ubicación -->
          <div class="form-section">
            <h3><i class="bi bi-geo-alt"></i> Ubicación</h3>
            <div class="form-group">
              <label for="direccion">Dirección*</label>
              <input
                id="direccion"
                v-model="commonData.address.direccion"
                type="text"
                class="form-control"
                required
              />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label for="ciudad">Ciudad*</label>
                <input
                  id="ciudad"
                  v-model="commonData.address.ciudad"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
              <div class="form-group">
                <label for="provincia">Provincia*</label>
                <input
                  id="provincia"
                  v-model="commonData.address.provincia"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
              <div class="form-group">
                <label for="codigo_postal">Código Postal*</label>
                <input
                  id="codigo_postal"
                  v-model="commonData.address.codigo_postal"
                  type="text"
                  class="form-control"
                  required
                />
              </div>
            </div>
          </div>

          <!-- Detalles Específicos -->
          <div class="form-section">
            <h3><i class="bi bi-list-check"></i> Detalles Específicos</h3>
            <component
              v-if="selectedType"
              :is="currentFormComponent"
              @service-data="handleServiceData"
              v-bind="selectedType === 'musica' ? { accountId } : {}"
            />
          </div>

          <!-- Disponibilidad -->
          <div class="form-section">
            <h3><i class="bi bi-calendar-check"></i> Disponibilidad</h3>
            <div class="availability-rules">
              <div v-for="(rule, index) in commonData.availability_rules" :key="index" class="availability-rule">
                <div class="rule-header">
                  <h4>Regla de Disponibilidad {{ index + 1 }}</h4>
                  <button v-if="index > 0" @click="removeAvailabilityRule(index)" class="remove-rule">
                    Quitar <i class="bi bi-trash"></i>
                  </button>
                </div>

                <!-- Días de la semana en una fila -->
                <div class="weekday-selector">
                  <button
                    v-for="day in weekDays"
                    :key="day.value"
                    type="button"
                    :class="['weekday-button', { active: rule.dias_semana.includes(day.value) }]"
                    @click="toggleWeekday(rule, day.value)"
                  >
                    {{ day.label }}
                  </button>
                </div>

                <!-- Resto de campos en otra fila -->
                <div class="availability-details">
                  <div class="form-row">
                    <div class="form-group">
                      <label><i class="bi bi-clock"></i>
                      Hora de Inicio*
                      </label>
                      <input
                        v-model="rule.hora_inicio"
                        type="time"
                        class="form-control"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-clock"></i>
                      Hora de Fin*
                      </label>
                      <input
                        v-model="rule.hora_fin"
                        type="time"
                        class="form-control"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-currency-euro"></i>
                        {{ getPriceLabel() }}
                      </label>
                      <input
                        v-model.number="rule.price"
                        type="number"
                        class="form-control"
                        min="0"
                        step="0.01"
                        required
                      />
                    </div>
                    <div class="form-group">
                      <label><i class="bi bi-calendar-check"></i>
                      Días Mín. de Antelación*
                      </label>
                      <input
                        v-model.number="rule.min_days_before"
                        type="number"
                        class="form-control"
                        min="1"
                        required
                      />
                    </div>
                  </div>
                </div>
              </div>

              <button @click="addAvailabilityRule" class="btn-add-rule">
                <i class="bi bi-plus-circle"></i>
                Añadir Regla de Disponibilidad
              </button>
            </div>
          </div>

          <!-- Botones de acción -->
          <div class="form-actions">
            <button type="button" class="cancel-btn" @click="handleCancel">
              <i class="bi bi-x"></i> Cancelar
            </button>
            <button type="button" class="submit-btn" @click="handleSubmit" :disabled="isSubmitting">
              <i class="bi bi-check2"></i> Crear Servicio
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import logo from '@/assets/LogoEventAiTransGran.png'
import iconCatering from '@/assets/icon_catering2.png'
import iconMobiliari from '@/assets/icon_mobiliari2.png'
import iconCateringInverse from '@/assets/iconCateringInvers.png'
import iconMobiliariInverse from '@/assets/iconMobiliariInvers2.png'
import CreateEspai from './create_services/CreateEspai.vue'
import CreateCatering from './create_services/CreateCatering.vue'
import CreateMobiliari from './create_services/CreateMobiliari.vue'
import CreateDecoracio from './create_services/CreateDecoracio.vue'
import CreateMusica from './create_services/CreateMusica.vue'
import CreateFotografia from './create_services/CreateFotografia.vue'
import EspaiService from '@/services/EspaiServices'
import CateringService from '@/services/CateringServices'
import MobiliariDecoracioService from '@/services/MobiliariDecoracioServices'
import MusicaService from '@/services/MusicaServices'
import FotografiaService from '@/services/FotografiaServices'
import Swal from 'sweetalert2'
import UploadServices from '@/services/UploadServices'

export default {
  name: 'CreateServices',
  components: {
    CreateEspai,
    CreateCatering,
    CreateMobiliari,
    CreateDecoracio,
    CreateMusica,
    CreateFotografia
  },
  setup () {
    const selectedType = ref('')
    const commonData = ref({
      name: '',
      description: '',
      images: [],
      address: {
        direccion: '',
        ciudad: '',
        provincia: '',
        codigo_postal: ''
      },
      availability_rules: [{
        dias_semana: [],
        hora_inicio: '',
        hora_fin: '',
        price: 0,
        min_days_before: 1
      }]
    })
    const imagePreviews = ref([])
    const isNavbarHidden = ref(false)
    const accountId = ref(null)
    const isSubmitting = ref(false)
    const response = ref(null)
    const imageFiles = ref([])
    const mouseY = ref(0)
    const observer = ref(null)
    const scrollTimeout = ref(null)
    const lastScrollTop = ref(0)
    const imageInput = ref(null)

    // Función para guardar el estado
    const saveState = () => {
      const state = {
        selectedType: selectedType.value,
        commonData: commonData.value,
        serviceData: response.value,
        scrollPosition: window.scrollY
      }
      sessionStorage.setItem('createServiceState', JSON.stringify(state))
    }

    // Función para restaurar el estado
    const restoreState = () => {
      const savedState = sessionStorage.getItem('createServiceState')
      if (savedState) {
        const state = JSON.parse(savedState)
        selectedType.value = state.selectedType
        commonData.value = state.commonData
        response.value = state.serviceData
        // Restaurar la posición del scroll después de que el componente se haya montado
        nextTick(() => {
          window.scrollTo(0, state.scrollPosition)
        })
      }
    }

    // Guardar estado antes de desmontar el componente
    onBeforeUnmount(() => {
      saveState()
    })

    // Restaurar estado al montar el componente
    onMounted(() => {
      restoreState()
      const user = JSON.parse(localStorage.getItem('user'))
      if (user && user.id) {
        accountId.value = user.id
      }
      console.log('accountId en CreateServices:', accountId.value)

      // Configurar el Intersection Observer
      observer.value = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            isNavbarHidden.value = false
          } else {
            // Solo ocultar el navbar si no estamos en la parte superior
            const currentScroll = window.pageYOffset || document.documentElement.scrollTop
            if (currentScroll > 200) {
              isNavbarHidden.value = true
            }
          }
        })
      }, {
        threshold: 0.1 // El callback se ejecutará cuando al menos el 10% del elemento sea visible
      })

      // Observar el primer elemento después del navbar
      const firstElement = document.querySelector('.create-service-page')
      if (firstElement) {
        observer.value.observe(firstElement)
      }
    })

    // Guardar estado cuando cambian los datos
    const handleServiceData = (data) => {
      response.value = data
      saveState()
    }

    const selectType = (type) => {
      selectedType.value = type
      saveState()
    }

    const handleImageUpload = (event) => {
      const files = Array.from(event.target.files)
      files.forEach(file => {
        if (imageFiles.value.length >= 30) return
        imageFiles.value.push(file)
        imagePreviews.value.push(URL.createObjectURL(file))
      })
      saveState()
    }

    const removeImage = (index) => {
      imageFiles.value.splice(index, 1)
      imagePreviews.value.splice(index, 1)
      saveState()
    }

    const handleMouseMove = (event) => {
      mouseY.value = event.clientY
      // Mostrar la barra cuando el ratón está en los primeros 100px de la ventana
      isNavbarHidden.value = mouseY.value > 110
    }

    const handleSubmit = async () => {
      try {
        isSubmitting.value = true
        const loadingPopup = Swal.fire({
          title: 'Creando servicio...',
          text: 'Por favor, espere mientras se procesa su solicitud',
          allowOutsideClick: false,
          allowEscapeKey: false,
          showConfirmButton: false,
          didOpen: () => {
            Swal.showLoading()
          }
        })

        console.log('[CreateServices] serviceData antes de submit:', response.value)
        if (!response.value) {
          throw new Error('Por favor, complete los datos específicos del servicio')
        }
        if (!commonData.value.name || !commonData.value.description) {
          throw new Error('Por favor, complete todos los campos obligatorios en la información general')
        }
        if (!commonData.value.address.direccion || !commonData.value.address.ciudad ||
            !commonData.value.address.codigo_postal || !commonData.value.address.provincia) {
          throw new Error('Por favor, complete todos los campos de la dirección')
        }
        if (imageFiles.value.length === 0) {
          throw new Error('Por favor, sube al menos una imagen')
        }

        // Subir imágenes
        const uploadPromises = imageFiles.value.map(file => {
          const uniqueName = `${Date.now()}_${file.name}`
          const renamedFile = new File([file], uniqueName, { type: file.type })
          return UploadServices.uploadImage(renamedFile)
        })
        const imageUrls = await Promise.all(uploadPromises)
        commonData.value.images = imageUrls

        let finalData
        if (selectedType.value === 'espai') {
          finalData = {
            type: 'espai',
            name: commonData.value.name,
            description: commonData.value.description,
            images: commonData.value.images,
            service_include: response.value.service_include,
            address: commonData.value.address,
            availability_rules: commonData.value.availability_rules.map(rule => ({
              hora_inicio: rule.hora_inicio,
              hora_fin: rule.hora_fin,
              price: rule.price,
              dias_semana: rule.dias_semana,
              min_days_before: rule.min_days_before
            })),
            espai: {
              capacitat_max: response.value.capacitat_max,
              espai_type: response.value.espai_type,
              capacitat_min: response.value.capacitat_min,
              caracteristicas: response.value.caracteristicas
            }
          }
          response.value = await EspaiService.createEspai(finalData)
        } else if (selectedType.value === 'mobiliari' || selectedType.value === 'decoracio') {
          // Agrupar servicios incluidos en objeto por grupo
          let serviceIncludeObj
          if (Array.isArray(response.value.servicios_incluidos)) {
            const logisticos = ['transporte', 'montaje', 'desmontaje', 'recolocacion', 'recogida']
            const tecnicos = ['supervision', 'asistencia', 'reemplazo']
            const seleccionados = response.value.servicios_incluidos
            const aspectosLogisticos = seleccionados.filter(v => logisticos.includes(v))
            const aspectosTecnicos = seleccionados.filter(v => tecnicos.includes(v))
            serviceIncludeObj = {}
            if (aspectosLogisticos.length) serviceIncludeObj['Aspectos logísticos'] = aspectosLogisticos
            if (aspectosTecnicos.length) serviceIncludeObj['Aspectos técnicos'] = aspectosTecnicos
            if (Object.keys(serviceIncludeObj).length === 0) serviceIncludeObj = undefined
          }

          // Preparar los datos del mobiliario
          const mobiliariData = {
            ...response.value,
            color: Array.isArray(response.value.color) ? response.value.color : [],
            material: Array.isArray(response.value.material) ? response.value.material : [],
            caracteristicas: Array.isArray(response.value.caracteristicas) ? response.value.caracteristicas : [],
            complement: (
              Array.isArray(response.value.complement)
                ? (response.value.complement.length > 0 ? response.value.complement.join(', ') : null)
                : (response.value.complement || null)
            ),
            dimensions: response.value.dimensions || { width: 0, height: 0, depth: 0 }
          }
          delete mobiliariData.servicios_incluidos

          finalData = {
            type: 'mobiliari-decoracio',
            name: commonData.value.name,
            description: commonData.value.description,
            images: commonData.value.images,
            service_include: serviceIncludeObj,
            address: commonData.value.address,
            availability_rules: commonData.value.availability_rules.map(rule => ({
              hora_inicio: rule.hora_inicio,
              hora_fin: rule.hora_fin,
              price: rule.price,
              dias_semana: rule.dias_semana,
              min_days_before: rule.min_days_before
            })),
            mobiliari_decoracio: mobiliariData
          }
          console.log('[CreateServices] Enviando a createMobiliari/Decoracio:', JSON.parse(JSON.stringify(finalData)))
          response.value = await MobiliariDecoracioService.createMobiliari(finalData)
        } else if (selectedType.value === 'musica') {
          // Agrupar servicios incluidos en objeto por grupo
          let serviceIncludeObj = {}
          const musicales = ['playlist_personalizada', 'cancion_peticion', 'karaoke', 'animacion_musical', 'efectos_sonido']
          const tecnicos = ['equipo_sonido', 'iluminacion_escenario', 'tecnico_sonido', 'montaje_equipo', 'backline']
          const seguridad = ['seguro_equipo', 'certificacion_sonido', 'cumplimiento_normativa']
          const seleccionados = Array.isArray(response.value.servicios_incluidos) ? response.value.servicios_incluidos : []
          const aspectosMusicales = seleccionados.filter(v => musicales.includes(v))
          const aspectosTecnicos = seleccionados.filter(v => tecnicos.includes(v))
          const aspectosSeguridad = seleccionados.filter(v => seguridad.includes(v))
          if (aspectosMusicales.length) serviceIncludeObj['Servicios musicales'] = aspectosMusicales
          if (aspectosTecnicos.length) serviceIncludeObj['Equipamiento y técnicos'] = aspectosTecnicos
          if (aspectosSeguridad.length) serviceIncludeObj['Seguridad y cumplimiento'] = aspectosSeguridad
          if (Object.keys(serviceIncludeObj).length === 0) serviceIncludeObj = undefined

          // Preparar datos de música
          const musicaData = { ...response.value }
          // Eliminar servicios_incluidos del objeto musica
          delete musicaData.servicios_incluidos
          // Si raider existe y tiene id, poner raider_id, si no, no poner nada
          delete musicaData.raider_id
          if (musicaData.raider && musicaData.raider.id) {
            musicaData.raider_id = musicaData.raider.id
          }
          delete musicaData.raider
          // Asegurar que duracion es float
          musicaData.duracion = parseFloat(musicaData.duracion)

          finalData = {
            ...commonData.value,
            type: 'musica',
            service_include: serviceIncludeObj,
            musica: musicaData
          }
          console.log('[CreateServices] FINAL DATA POST musica:', JSON.parse(JSON.stringify(finalData)))
          response.value = await MusicaService.createMusica(finalData)
        } else if (selectedType.value === 'fotografia') {
          // Preparar datos de fotografía
          const fotografiaData = { ...response.value }

          // Si raider existe y tiene id, poner raider_id, si no, no poner nada
          if (fotografiaData.raider && fotografiaData.raider.id) {
            fotografiaData.raider_id = fotografiaData.raider.id
          }
          delete fotografiaData.raider
          if (fotografiaData.servicio_especial_type === '') {
            delete fotografiaData.servicio_especial_type
          }

          // Estructurar service_include correctamente
          const serviceInclude = {
            'Entrega del material': fotografiaData.servicios_incluidos.filter(serv =>
              ['entrega_digital', 'entrega_fisica', 'album_digital', 'album_fisico', 'marco_regalo', 'tarjetas_agradecimiento', 'video_montaje', 'fotos_adicionales'].includes(serv)
            ),
            'Equipamiento y técnicos': fotografiaData.servicios_incluidos.filter(serv =>
              ['equipo_profesional', 'maquillador', 'iluminacion_estudio', 'fondo_croma', 'drone', 'estabilizador', 'monitor_calibrado', 'impresora_profesional', 'escanner_alta_resolucion'].includes(serv)
            ),
            'Seguridad y cumplimiento': fotografiaData.servicios_incluidos.filter(serv =>
              ['seguro_equipo', 'backup_archivos', 'certificacion_profesional', 'derechos_imagen'].includes(serv)
            )
          }

          // Eliminar servicios_incluidos del objeto fotografia
          delete fotografiaData.servicios_incluidos

          finalData = {
            ...commonData.value,
            type: 'fotografia',
            service_include: serviceInclude,
            fotografia: fotografiaData
          }

          console.log('[CreateServices] FINAL DATA POST fotografia:', JSON.parse(JSON.stringify(finalData)))
          response.value = await FotografiaService.createFotografia(finalData)
        } else {
          let serviceInclude
          if (selectedType.value === 'fotografia') {
            serviceInclude = response.value.service_include
          } else {
            serviceInclude = response.value.servicios_incluidos
          }

          finalData = {
            ...commonData.value,
            type: selectedType.value,
            service_include: serviceInclude || undefined,
            [selectedType.value]: response.value
          }
          console.log('[CreateServices] Enviando a create otro tipo:', JSON.parse(JSON.stringify(finalData)))
          switch (selectedType.value) {
            case 'catering':
              response.value = await CateringService.createCatering(finalData)
              break
            default:
              throw new Error('Tipo de servicio no válido')
          }
        }

        // Cerrar el popup de carga
        await loadingPopup.close()
        // Mostrar mensaje de éxito
        await Swal.fire({
          title: '¡Servicio creado!',
          text: 'El servicio se ha creado correctamente.',
          icon: 'success',
          confirmButtonText: 'OK'
        })
        nextTick(() => {
          this.$router.push(`/mydetallesService/${response.value.id}`)
        })
      } catch (error) {
        // Cerrar el popup de carga si está abierto
        if (Swal.isVisible()) {
          await Swal.close()
          await new Promise(resolve => setTimeout(resolve, 100))
        }
        await Swal.fire({
          title: 'Error',
          html: 'Error al crear el servicio.<br>Por favor, revise los datos e inténtelo de nuevo.',
          icon: 'error',
          confirmButtonText: 'OK'
        })
        console.error('Error creating service:', error)
      } finally {
        // Cerrar el popup de carga si por cualquier motivo sigue abierto
        if (Swal.isVisible()) {
          await Swal.close()
        }
        isSubmitting.value = false
      }
    }

    const handleCancel = () => {
      selectedType.value = null
      resetForm()
    }

    const resetForm = () => {
      commonData.value = {
        name: '',
        description: '',
        images: [],
        address: {
          direccion: '',
          ciudad: '',
          codigo_postal: '',
          provincia: ''
        },
        availability_rules: [{
          dias_semana: [],
          hora_inicio: '',
          hora_fin: '',
          price: 0,
          min_days_before: 1
        }]
      }
    }

    const triggerImageUpload = () => {
      imageInput.value.click()
    }

    const addAvailabilityRule = () => {
      commonData.value.availability_rules.push({
        dias_semana: [],
        hora_inicio: '',
        hora_fin: '',
        price: 0,
        min_days_before: 1
      })
    }

    const removeAvailabilityRule = (index) => {
      if (commonData.value.availability_rules.length > 1) {
        commonData.value.availability_rules.splice(index, 1)
      }
    }

    const toggleWeekday = (rule, day) => {
      const index = rule.dias_semana.indexOf(day)
      if (index === -1) {
        rule.dias_semana.push(day)
      } else {
        rule.dias_semana.splice(index, 1)
      }
    }

    const getPriceLabel = () => {
      switch (selectedType.value) {
        case 'espai':
          return 'Precio (€/h)*'
        case 'catering':
          return 'Precio (€/pax)*'
        case 'mobiliari':
          return 'Precio (€/u)*'
        case 'decoracio':
          return 'Precio (€/u)*'
        case 'musica':
          return 'Precio (€/h)*'
        case 'fotografia':
          return 'Precio (€/h)*'
        default:
          return 'Precio (€)*'
      }
    }

    const handleScroll = () => {
      if (scrollTimeout.value) {
        clearTimeout(scrollTimeout.value)
      }

      scrollTimeout.value = setTimeout(() => {
        const currentScroll = window.pageYOffset || document.documentElement.scrollTop

        // Si estamos en la parte superior de la página o scrollY <= 200, siempre mostrar el navbar
        if (currentScroll <= 200) {
          isNavbarHidden.value = false
          return
        }

        if (currentScroll > lastScrollTop.value && currentScroll > 200) {
          // Scrolling down & past threshold
          isNavbarHidden.value = true
        } else {
          // Scrolling up
          isNavbarHidden.value = false
        }
        lastScrollTop.value = currentScroll <= 0 ? 0 : currentScroll
      }, 50)
    }

    const clearAllData = () => {
      // Limpiar datos comunes
      commonData.value = {
        name: '',
        description: '',
        address: {
          direccion: '',
          ciudad: '',
          provincia: '',
          codigo_postal: ''
        },
        availability_rules: [{
          dias_semana: [],
          hora_inicio: '',
          hora_fin: '',
          price: 0,
          min_days_before: 1
        }]
      }

      // Limpiar imágenes
      imagePreviews.value = []
      imageFiles.value = []

      // Limpiar datos específicos del servicio
      response.value = {}

      // Forzar la actualización del componente hijo para limpiar sus datos
      const currentType = selectedType.value
      selectedType.value = null
      nextTick(() => {
        selectedType.value = currentType
      })
      // Mostrar mensaje de confirmación
      alert('Todos los datos han sido eliminados correctamente')
    }

    const weekDays = [
      { value: 1, label: 'L' },
      { value: 2, label: 'M' },
      { value: 3, label: 'X' },
      { value: 4, label: 'J' },
      { value: 5, label: 'V' },
      { value: 6, label: 'S' },
      { value: 7, label: 'D' }
    ]

    const currentFormComponent = computed(() => {
      const componentMap = {
        espai: 'CreateEspai',
        catering: 'CreateCatering',
        mobiliari: 'CreateMobiliari',
        decoracio: 'CreateDecoracio',
        musica: 'CreateMusica',
        fotografia: 'CreateFotografia'
      }
      return selectedType.value ? componentMap[selectedType.value] : null
    })

    return {
      selectedType,
      commonData,
      imagePreviews,
      isNavbarHidden,
      accountId,
      isSubmitting,
      response,
      imageFiles,
      mouseY,
      handleServiceData,
      selectType,
      handleImageUpload,
      removeImage,
      handleMouseMove,
      handleSubmit,
      handleCancel,
      resetForm,
      triggerImageUpload,
      addAvailabilityRule,
      removeAvailabilityRule,
      toggleWeekday,
      getPriceLabel,
      handleScroll,
      logo,
      iconCatering,
      iconMobiliari,
      iconMobiliariInverse,
      iconCateringInverse,
      weekDays,
      currentFormComponent,
      imageInput,
      clearAllData
    }
  }
}
</script>

<style scoped>
h5.avis-campos {
  color: #333;
  text-align: right;
  font-size: 0.9rem;
  font-weight: 600;
  margin: -0.5rem 1rem -1.5rem 0;
}
.submit-btn,
.cancel-btn {
  padding: 0.8rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn {
  background-color: #800020;
  color: white;
  border: none;
}

.submit-btn:hover {
  background-color: #600018;
}

.submit-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.cancel-btn {
  background-color: #e9ecef;
  color: #2C3E50;
  border: 1px solid #dee2e6;
}

.cancel-btn:hover {
  background-color: #dee2e6;
}

.service-type-img {
  width: 2.75rem;
  height: 2.75rem;
  margin-bottom: 0.5rem;
  object-fit: contain;
}

.page-container {
  padding-top: 140px; /* Ajusta este valor según la altura de tu navbar */
  min-height: 100vh;
  background: #f8f9fa;
  background-image: url('../assets/foto_horizontal_3colores.jpg');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  background-repeat: no-repeat;
}

.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-right {
  margin-right: 1rem;
}

.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);
}

.create-service-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem 2rem;
}

.service-type-selector {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  backdrop-filter: blur(5px);
}

.service-type-selector h2 {
  color: #800020;
  margin-bottom: 1.5rem;
  text-align: center;
}

.service-types {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  justify-content: center;
  margin-bottom: 0.1rem;
}

.type-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 1.5rem;
  border: 2px solid #ddd;
  border-radius: 10px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.type-button:hover {
  border-color: #800020;
  transform: translateY(-2px);
}

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

.type-button i {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.service-form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0rem;
}

.form-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
}

.form-section {
  margin-bottom: 2.5rem;
  padding-bottom: 1rem;
  border-bottom: 3px solid #eee;
  width: 100%;
}

.form-section:last-child {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: none;
}

h3 {
  color: #800020;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.25rem;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  width: 100%;
  margin-bottom: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  width: 100%;
  margin-bottom: 1.5rem;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
}

.form-control {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-control:focus {
  outline: none;
  border-color: #800020;
  box-shadow: 0 0 0 0.2rem rgba(128, 0, 32, 0.1);
}

label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
  color: #2C3E50;
  font-weight: 500;
}

.btn-upload {
  width: 100%;
  padding: 0.75rem;
  background: #f8f9fa;
  border: 2px dashed #ddd;
  border-radius: 8px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.3s;
  margin-bottom: 1rem;
}

.btn-upload:hover {
  border-color: #800020;
  color: #800020;
}

.image-preview-container {
  margin-top: 1rem;
  max-width: 100%;
}

.image-preview-scroll {
  overflow-x: auto;
  padding: 0.5rem;
  margin-bottom: 0.5rem;
}

.image-preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 1rem;
}

.image-preview-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ddd;
}

.image-preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #dc3545;
}

.availability-rule {
  background:rgb(245, 245, 245);
  border-radius: 8px;
  padding: 1.5rem;
  padding-bottom: -0.5rem;
  margin-bottom: 1rem;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0rem;
}

.rule-header h4 {
  margin: 0;
  color: #2C3E50;
  font-weight: 550;
}

.remove-rule {
  background: none;
  border: none;
  color: #dc3545;
  cursor: pointer;
  padding: 0.25rem;
  border-radius: 8px;
  transition: all 0.3s;
}

.remove-rule:hover {
  background: rgba(220, 53, 69, 0.1);
}

.weekday-selector {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
  flex-wrap: wrap;
  justify-content: center;
}

.weekday-button {
  width: 40px;
  height: 40px;
  border: 2px solid #ddd;
  border-radius: 50%;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

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

.availability-details {
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: -3.5rem;
}

.availability-details .form-row {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
}

.btn-add-rule {
  width: 100%;
  padding: 0.75rem;
  background: none;
  border: 2px dashed #ddd;
  border-radius: 8px;
  color: #666;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  transition: all 0.3s;
  margin-top: 1rem;
}

.btn-add-rule:hover {
  border-color: #800020;
  color: #800020;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
  padding: 0.2rem;
}

.text-muted {
  color: #6c757d;
  font-size: 0.875rem;
}

textarea.form-control {
  min-height: 120px;
}

.service-type-message {
  text-align: center;
  color: #666;
  margin-top: 3rem;
  font-size: 1.1rem;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.service-type-message i {
  color: #800020;
  font-size: 1.2rem;
}

.btn-clear {
  color: black;
  border: 1px solid #800020;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  margin-top: 2rem;
  transition: background-color 0.3s;
}

.btn-clear:hover {
  background-color: #c82333;
  color: white;
}

.btn-clear i {
  font-size: 1em;
}
</style>
