<template>
  <div>
    <div class="pb-5 border-b border-gray-200 sm:flex sm:items-center sm:justify-between">
      <h3 class="text-lg leading-6 font-medium text-gray-900">
        {{ $t('calendar.title') }}
      </h3>
      <div class="mt-3 sm:mt-0 sm:ml-4">
        <button
          @click="showNewUploadModal = true"
          class="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          <svg class="-ml-1 mr-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-11a1 1 0 10-2 0v2H7a1 1 0 100 2h2v2a1 1 0 102 0v-2h2a1 1 0 100-2h-2V7z" clip-rule="evenodd" />
          </svg>
          {{ $t('calendar.scheduleUpload') }}
        </button>
      </div>
    </div>

    <div class="mt-6">
      <div v-if="loading" class="flex justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-10 w-10 text-primary" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
      </div>
      <div v-else>
        <!-- Calendar View -->
        <div class="bg-white shadow rounded-lg p-4">
          <div class="flex space-x-4 mb-4">
            <button 
              @click="currentView = 'month'"
              :class="[
                currentView === 'month' 
                  ? 'bg-primary-100 text-primary' 
                  : 'bg-white text-gray-700 hover:bg-gray-50',
                'px-3 py-2 rounded-md text-sm font-medium'
              ]"
            >
              {{ $t('calendar.month') }}
            </button>
            <button 
              @click="currentView = 'week'"
              :class="[
                currentView === 'week' 
                  ? 'bg-primary-100 text-primary' 
                  : 'bg-white text-gray-700 hover:bg-gray-50',
                'px-3 py-2 rounded-md text-sm font-medium'
              ]"
            >
              {{ $t('calendar.week') }}
            </button>
            <button 
              @click="currentView = 'day'"
              :class="[
                currentView === 'day' 
                  ? 'bg-primary-100 text-primary' 
                  : 'bg-white text-gray-700 hover:bg-gray-50',
                'px-3 py-2 rounded-md text-sm font-medium'
              ]"
            >
              {{ $t('calendar.day') }}
            </button>
          </div>
          
          <!-- Calendar Navigation -->
          <div class="flex justify-between items-center mb-4">
            <div>
              <button 
                @click="navigatePrevious()" 
                class="p-1 rounded-full hover:bg-gray-100"
              >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </button>
            </div>
            <div class="text-lg font-semibold text-gray-800">
              {{ formatNavigationHeader() }}
            </div>
            <div>
              <button 
                @click="navigateNext()" 
                class="p-1 rounded-full hover:bg-gray-100"
              >
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
              </button>
              <button 
                @click="navigateToday()" 
                class="ml-2 px-3 py-1 text-sm bg-primary-50 text-primary rounded-md hover:bg-primary-100"
              >
                {{ $t('calendar.today') }}
              </button>
            </div>
          </div>
          
          <div class="calendar-container">
            <!-- Month View -->
            <div v-if="currentView === 'month'" class="month-view">
              <div class="grid grid-cols-7 gap-px bg-gray-200">
                <div v-for="day in [
                  $t('calendar.days.sun'), 
                  $t('calendar.days.mon'), 
                  $t('calendar.days.tue'), 
                  $t('calendar.days.wed'), 
                  $t('calendar.days.thu'), 
                  $t('calendar.days.fri'), 
                  $t('calendar.days.sat')
                ]" :key="day" class="bg-gray-50 p-2 text-center text-xs font-medium text-gray-700">
                  {{ day }}
                </div>
                <div v-for="(day, index) in daysInMonth" :key="index" 
                  class="bg-white p-2 min-h-[100px] relative"
                  :class="{ 'bg-gray-50': !day.isCurrentMonth }"
                >
                  <div class="text-right text-xs text-gray-500">{{ day.date }}</div>
                  <div v-for="event in getEventsForDay(day.fullDate)" :key="event.id" 
                    class="mt-1 p-1 text-xs rounded truncate cursor-pointer"
                    :class="getEventClass(event)"
                    @click="showEventDetails(event)"
                  >
                    {{ event.title }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- Week View -->
            <div v-else-if="currentView === 'week'" class="week-view">
              <div class="grid grid-cols-7 gap-px bg-gray-200">
                <div v-for="day in weekDays" :key="day.date" class="bg-gray-50 p-2 text-center text-xs font-medium text-gray-700">
                  {{ day.dayName }}<br>{{ day.date }}
                </div>
                <div v-for="day in weekDays" :key="day.date + '-content'" 
                  class="bg-white p-2 min-h-[400px] relative"
                >
                  <div v-for="event in getEventsForDay(day.fullDate)" :key="event.id" 
                    class="mt-1 p-1 text-xs rounded truncate cursor-pointer"
                    :class="getEventClass(event)"
                    @click="showEventDetails(event)"
                  >
                    {{ event.title }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- Day View -->
            <div v-else class="day-view">
              <div class="bg-gray-50 p-2 text-center text-sm font-medium text-gray-700 mb-2">
                {{ formatDayViewHeader() }}
              </div>
              <div class="bg-white p-4 min-h-[600px] relative">
                <div v-for="hour in 24" :key="hour" class="border-t border-gray-200 py-2">
                  <div class="text-xs text-gray-500 w-16 inline-block">{{ formatHour(hour - 1) }}</div>
                  <div class="inline-block w-full">
                    <div v-for="event in getEventsForHour(selectedDate, hour - 1)" :key="event.id" 
                      class="ml-16 p-1 text-xs rounded truncate cursor-pointer"
                      :class="getEventClass(event)"
                      @click="showEventDetails(event)"
                    >
                      {{ event.title }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- New Upload Modal -->
    <div v-if="showNewUploadModal" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" @click="showNewUploadModal = false"></div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
          <div>
            <div class="mt-3 text-center sm:mt-0 sm:text-left">
              <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                {{ $t('calendar.newUpload.title') }}
              </h3>
              <div class="mt-4">
                <form @submit.prevent="scheduleUpload">
                  <div class="space-y-4">
                    <div>
                      <label for="title" class="block text-sm font-medium text-gray-700">{{ $t('calendar.newUpload.videoTitle') }}</label>
                      <input 
                        type="text" 
                        name="title" 
                        id="title" 
                        v-model="newUpload.title"
                        class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm" 
                        :placeholder="$t('calendar.newUpload.videoTitle')" 
                        required
                      />
                    </div>
                    
                    <div>
                      <label for="platform" class="block text-sm font-medium text-gray-700">{{ $t('calendar.newUpload.platform') }}</label>
                      <select 
                        id="platform" 
                        name="platform" 
                        v-model="newUpload.platform"
                        class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm rounded-md"
                        required
                      >
                        <option value="">{{ $t('calendar.newUpload.selectPlatform') }}</option>
                        <option value="TikTok">TikTok</option>
                        <option value="YouTube">YouTube</option>
                        <option value="Instagram">Instagram</option>
                      </select>
                    </div>
                    
                    <div>
                      <label for="upload-date" class="block text-sm font-medium text-gray-700">{{ $t('calendar.newUpload.uploadDate') }}</label>
                      <input 
                        type="datetime-local" 
                        name="upload-date" 
                        id="upload-date" 
                        v-model="newUpload.uploadDate"
                        class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm" 
                        required
                      />
                    </div>
                    
                    <div>
                      <label for="description" class="block text-sm font-medium text-gray-700">{{ $t('calendar.newUpload.description') }}</label>
                      <textarea 
                        id="description" 
                        name="description" 
                        rows="3" 
                        v-model="newUpload.description"
                        class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm" 
                        :placeholder="$t('calendar.newUpload.videoDescription')"
                      ></textarea>
                    </div>
                    
                    <div>
                      <label for="hashtags" class="block text-sm font-medium text-gray-700">{{ $t('calendar.newUpload.hashtags') }}</label>
                      <input 
                        type="text" 
                        name="hashtags" 
                        id="hashtags" 
                        v-model="newUpload.hashtags"
                        class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm" 
                        placeholder="#asmr #relaxing"
                      />
                    </div>
                  </div>
                  
                  <div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">
                    <button 
                      type="submit"
                      class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:col-start-2 sm:text-sm"
                    >
                      {{ $t('calendar.newUpload.schedule') }}
                    </button>
                    <button 
                      type="button"
                      @click="showNewUploadModal = false"
                      class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:col-start-1 sm:text-sm"
                    >
                      {{ $t('calendar.newUpload.cancel') }}
                    </button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Event Details Modal -->
    <div v-if="showEventModal" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true" @click="showEventModal = false"></div>

        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

        <div class="inline-block align-bottom bg-white rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
          <div>
            <div class="mt-3 text-center sm:mt-0 sm:text-left">
              <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                {{ selectedEvent?.title }}
              </h3>
              <div class="mt-4 space-y-4">
                <div class="flex items-center">
                  <div class="flex-shrink-0">
                    <div class="h-10 w-10 rounded-full bg-primary-100 flex items-center justify-center">
                      <svg v-if="selectedEvent?.extendedProps?.platform === 'TikTok'" class="h-6 w-6 text-primary-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M12.53.02C13.84 0 15.14.01 16.44 0c.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z"/>
                      </svg>
                      <svg v-else-if="selectedEvent?.extendedProps?.platform === 'YouTube'" class="h-6 w-6 text-primary-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/>
                      </svg>
                      <svg v-else class="h-6 w-6 text-primary-600" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                        <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/>
                      </svg>
                    </div>
                  </div>
                  <div class="ml-3">
                    <div class="text-sm text-gray-500">
                      {{ selectedEvent?.extendedProps?.platform }}
                    </div>
                    <div class="text-sm text-gray-500">
                      {{ formatDate(selectedEvent?.start) }}
                    </div>
                  </div>
                  <div class="ml-auto">
                    <span :class="[
                      selectedEvent?.extendedProps?.status === 'geplant' ? 'bg-green-100 text-green-800' : 
                      selectedEvent?.extendedProps?.status === 'hochgeladen' ? 'bg-blue-100 text-blue-800' : 
                      'bg-red-100 text-red-800',
                      'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium'
                    ]">
                      {{ 
                        selectedEvent?.extendedProps?.status === 'geplant' ? $t('calendar.eventDetails.status.scheduled') : 
                        selectedEvent?.extendedProps?.status === 'hochgeladen' ? $t('calendar.eventDetails.status.uploaded') : 
                        $t('calendar.eventDetails.status.failed')
                      }}
                    </span>
                  </div>
                </div>
                
                <div v-if="selectedEvent?.extendedProps?.description">
                  <h4 class="text-sm font-medium text-gray-700">{{ $t('calendar.eventDetails.description') }}</h4>
                  <p class="mt-1 text-sm text-gray-500">{{ selectedEvent.extendedProps.description }}</p>
                </div>
                
                <div v-if="selectedEvent?.extendedProps?.hashtags">
                  <h4 class="text-sm font-medium text-gray-700">{{ $t('calendar.eventDetails.hashtags') }}</h4>
                  <p class="mt-1 text-sm text-gray-500">{{ selectedEvent.extendedProps.hashtags }}</p>
                </div>
              </div>
              
              <div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">
                <button 
                  type="button"
                  @click="editEvent"
                  class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-primary-600 text-base font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:col-start-2 sm:text-sm"
                >
                  {{ $t('calendar.eventDetails.edit') }}
                </button>
                <button 
                  type="button"
                  @click="showEventModal = false"
                  class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500 sm:mt-0 sm:col-start-1 sm:text-sm"
                >
                  {{ $t('calendar.eventDetails.close') }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';

export default {
  name: 'ContentCalendar',
  setup() {
    const { t, locale } = useI18n();
    const loading = ref(true);
    const currentView = ref('month');
    const events = ref([]);
    const showNewUploadModal = ref(false);
    const showEventModal = ref(false);
    const selectedEvent = ref(null);
    const selectedDate = ref(new Date());
    
    const newUpload = ref({
      title: '',
      platform: '',
      uploadDate: '',
      description: '',
      hashtags: ''
    });
    
    // Generate days for the current month
    const daysInMonth = computed(() => {
      const year = selectedDate.value.getFullYear();
      const month = selectedDate.value.getMonth();
      const daysArray = [];
      
      // Get the first day of the month
      const firstDay = new Date(year, month, 1);
      const startingDayOfWeek = firstDay.getDay();
      
      // Get the last day of the month
      const lastDay = new Date(year, month + 1, 0);
      const totalDays = lastDay.getDate();
      
      // Get the last day of the previous month
      const prevMonthLastDay = new Date(year, month, 0).getDate();
      
      // Fill in the days from the previous month
      for (let i = startingDayOfWeek - 1; i >= 0; i--) {
        const day = prevMonthLastDay - i;
        const date = new Date(year, month - 1, day);
        daysArray.push({
          date: day,
          isCurrentMonth: false,
          fullDate: date
        });
      }
      
      // Fill in the days of the current month
      for (let i = 1; i <= totalDays; i++) {
        const date = new Date(year, month, i);
        daysArray.push({
          date: i,
          isCurrentMonth: true,
          fullDate: date
        });
      }
      
      // Fill in the days from the next month
      const remainingDays = 42 - daysArray.length; // 6 rows of 7 days
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month + 1, i);
        daysArray.push({
          date: i,
          isCurrentMonth: false,
          fullDate: date
        });
      }
      
      return daysArray;
    });
    
    // Generate days for the current week
    const weekDays = computed(() => {
      const currentDate = new Date(selectedDate.value);
      const day = currentDate.getDay(); // 0 = Sunday, 6 = Saturday
      const diff = currentDate.getDate() - day;
      
      const weekStart = new Date(currentDate);
      weekStart.setDate(diff);
      
      const days = [];
      const dayNames = [
        t('calendar.days.sun'),
        t('calendar.days.mon'),
        t('calendar.days.tue'),
        t('calendar.days.wed'),
        t('calendar.days.thu'),
        t('calendar.days.fri'),
        t('calendar.days.sat')
      ];
      
      for (let i = 0; i < 7; i++) {
        const date = new Date(weekStart);
        date.setDate(weekStart.getDate() + i);
        
        days.push({
          date: date.getDate(),
          dayName: dayNames[i],
          fullDate: date
        });
      }
      
      return days;
    });
    
    // Get events for a specific day
    const getEventsForDay = (date) => {
      if (!date) return [];
      
      return events.value.filter(event => {
        const eventDate = new Date(event.start);
        return eventDate.getDate() === date.getDate() &&
               eventDate.getMonth() === date.getMonth() &&
               eventDate.getFullYear() === date.getFullYear();
      });
    };
    
    // Get events for a specific hour
    const getEventsForHour = (date, hour) => {
      if (!date) return [];
      
      return events.value.filter(event => {
        const eventDate = new Date(event.start);
        return eventDate.getDate() === date.getDate() &&
               eventDate.getMonth() === date.getMonth() &&
               eventDate.getFullYear() === date.getFullYear() &&
               eventDate.getHours() === hour;
      });
    };
    
    // Get CSS class for event based on platform
    const getEventClass = (event) => {
      if (event.extendedProps.platform === 'TikTok') {
        return 'bg-secondary-lavender-light text-secondary-lavender-dark';
      } else if (event.extendedProps.platform === 'YouTube') {
        return 'bg-secondary-mint-light text-secondary-mint-dark';
      } else {
        return 'bg-accent-coral-light text-accent-coral-dark';
      }
    };
    
    // Format the header for day view
    const formatDayViewHeader = () => {
      const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
      return selectedDate.value.toLocaleDateString(locale.value, options);
    };
    
    // Format hour for day view
    const formatHour = (hour) => {
      return `${hour % 12 || 12}:00 ${hour < 12 ? 'AM' : 'PM'}`;
    };
    
    // Show event details
    const showEventDetails = (event) => {
      selectedEvent.value = event;
      showEventModal.value = true;
    };
    
    const fetchEvents = async () => {
      loading.value = true;
      try {
        // For demo purposes, we'll use mock data
        setTimeout(() => {
          events.value = [
            {
              id: '1',
              title: 'Relaxing ASMR Whispers',
              start: new Date(Date.now() + 86400000), // Tomorrow
              extendedProps: {
                platform: 'TikTok',
                status: 'geplant',
                description: 'Soft whispers for relaxation and sleep.',
                hashtags: '#ASMR #Whispers #Relaxing'
              }
            },
            {
              id: '2',
              title: 'Tapping & Scratching Sounds',
              start: new Date(Date.now() + 172800000), // Day after tomorrow
              extendedProps: {
                platform: 'YouTube',
                status: 'geplant',
                description: 'Various tapping and scratching sounds on different surfaces.',
                hashtags: '#ASMR #Tapping #Scratching'
              }
            },
            {
              id: '3',
              title: 'Ear Cleaning Session',
              start: new Date(Date.now() + 259200000), // 3 days from now
              extendedProps: {
                platform: 'Instagram',
                status: 'geplant',
                description: 'Binaural ear cleaning sounds for deep relaxation.',
                hashtags: '#ASMR #EarCleaning #Binaural'
              }
            },
            {
              id: '4',
              title: 'Soft Spoken ASMR',
              start: new Date(Date.now() - 86400000), // Yesterday
              extendedProps: {
                platform: 'YouTube',
                status: 'hochgeladen',
                description: 'Soft spoken ASMR for sleep and relaxation.',
                hashtags: '#ASMR #SoftSpoken #Sleep'
              }
            },
            {
              id: '5',
              title: 'Keyboard Typing Sounds',
              start: new Date(Date.now() - 172800000), // 2 days ago
              extendedProps: {
                platform: 'TikTok',
                status: 'hochgeladen',
                description: 'Relaxing keyboard typing sounds.',
                hashtags: '#ASMR #Keyboard #Typing'
              }
            }
          ];
          loading.value = false;
        }, 1000);
      } catch (error) {
        console.error('Error fetching events:', error);
        loading.value = false;
      }
    };
    
    const handleDateClick = (date) => {
      selectedDate.value = date;
      newUpload.value.uploadDate = formatDateForInput(date);
      showNewUploadModal.value = true;
    };
    
    const scheduleUpload = async () => {
      try {
        // For demo purposes, we'll just add it to the events array
        const newEvent = {
          id: (events.value.length + 1).toString(),
          title: newUpload.value.title,
          start: new Date(newUpload.value.uploadDate),
          extendedProps: {
            platform: newUpload.value.platform,
            status: 'geplant',
            description: newUpload.value.description,
            hashtags: newUpload.value.hashtags
          }
        };
        
        events.value.push(newEvent);
        
        // Reset form and close modal
        newUpload.value = {
          title: '',
          platform: '',
          uploadDate: '',
          description: '',
          hashtags: ''
        };
        
        showNewUploadModal.value = false;
      } catch (error) {
        console.error('Error scheduling upload:', error);
      }
    };
    
    const editEvent = () => {
      // In a real app, this would open an edit form
      // For now, we'll just close the modal
      showEventModal.value = false;
    };
    
    const formatDate = (date) => {
      if (!date) return '';
      
      const d = new Date(date);
      const options = { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' };
      return d.toLocaleDateString(locale.value, options);
    };
    
    const formatDateForInput = (date) => {
      if (!date) return '';
      
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day}T${hours}:${minutes}`;
    };
    
    // Format the navigation header based on current view
    const formatNavigationHeader = () => {
      if (currentView.value === 'month') {
        const options = { month: 'long', year: 'numeric' };
        return new Date(selectedDate.value).toLocaleDateString(locale.value, options);
      } else if (currentView.value === 'week') {
        const weekStart = weekDays.value[0].fullDate;
        const weekEnd = weekDays.value[6].fullDate;
        
        if (weekStart.getMonth() === weekEnd.getMonth()) {
          const options = { month: 'long', year: 'numeric' };
          return `${weekStart.toLocaleDateString(locale.value, options)} - ${t('calendar.week')} ${getWeekNumber(weekStart)}`;
        } else {
          const startOptions = { month: 'short', day: 'numeric' };
          const endOptions = { month: 'short', day: 'numeric', year: 'numeric' };
          return `${weekStart.toLocaleDateString(locale.value, startOptions)} - ${weekEnd.toLocaleDateString(locale.value, endOptions)}`;
        }
      } else {
        const options = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' };
        return selectedDate.value.toLocaleDateString(locale.value, options);
      }
    };
    
    // Get week number
    const getWeekNumber = (date) => {
      const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
      const pastDaysOfYear = (date - firstDayOfYear) / 86400000;
      return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
    };
    
    // Navigate to previous period based on current view
    const navigatePrevious = () => {
      const newDate = new Date(selectedDate.value);
      
      if (currentView.value === 'month') {
        newDate.setMonth(newDate.getMonth() - 1);
      } else if (currentView.value === 'week') {
        newDate.setDate(newDate.getDate() - 7);
      } else {
        newDate.setDate(newDate.getDate() - 1);
      }
      
      selectedDate.value = newDate;
    };
    
    // Navigate to next period based on current view
    const navigateNext = () => {
      const newDate = new Date(selectedDate.value);
      
      if (currentView.value === 'month') {
        newDate.setMonth(newDate.getMonth() + 1);
      } else if (currentView.value === 'week') {
        newDate.setDate(newDate.getDate() + 7);
      } else {
        newDate.setDate(newDate.getDate() + 1);
      }
      
      selectedDate.value = newDate;
    };
    
    // Navigate to today
    const navigateToday = () => {
      selectedDate.value = new Date();
    };
    
    onMounted(() => {
      fetchEvents();
    });
    
    return {
      loading,
      currentView,
      events,
      daysInMonth,
      weekDays,
      selectedDate,
      showNewUploadModal,
      showEventModal,
      selectedEvent,
      newUpload,
      getEventsForDay,
      getEventsForHour,
      getEventClass,
      formatDayViewHeader,
      formatHour,
      showEventDetails,
      handleDateClick,
      scheduleUpload,
      editEvent,
      formatDate,
      formatNavigationHeader,
      navigatePrevious,
      navigateNext,
      navigateToday
    };
  }
};
</script>

<style scoped>
.calendar-container {
  min-height: 700px;
}

@media (max-width: 640px) {
  .calendar-container {
    min-height: 500px;
  }
}
</style> 