<template>
  <FullCalendar :options="calendarOptions" />
</template>

<script>
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'

// gapi 스크립트 로드 함수
function loadGapiScript() {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = 'https://apis.google.com/js/api.js';
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

export default {
  name: 'GoogleCalendar',
  components: {
    FullCalendar
  },
  data() {
    return {
      events: [],
      calendarOptions: {
        plugins: [dayGridPlugin],
        initialView: 'dayGridMonth',
        events: [],
        locale: 'ko',
        titleFormat: {
          year: 'numeric',
          month: '2-digit'
        },
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,dayGridWeek,dayGridDay'
        },
        buttonText: {
          today: '오늘',
          month: '월',
          week: '주',
          day: '일'
        },
        showNonCurrentDates: false,
        fixedWeekCount: false
      }
    }
  },
  mounted() {
    this.initGoogleApi();
  },
  methods: {
    async initGoogleApi() {
      try {
        await loadGapiScript();
        if (window.gapi) {
          window.gapi.load('client', this.loadClient);
        } else {
          console.error('gapi is not defined after loading script');
        }
      } catch (error) {
        console.error('Error loading gapi script:', error);
      }
    },
    loadClient() {
      window.gapi.client.init({
        apiKey: 'AIzaSyCNthSbTXgMrCG_dbuIhnk9BEVlp0ME5gM',
        discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
      }).then(() => {
        this.loadCalendarEvents();
      }).catch(error => {
        console.error('Error initializing gapi client:', error);
      });
    },
    loadCalendarEvents() {
      window.gapi.client.calendar.events.list({
        calendarId: 'ko.south_korea#holiday@group.v.calendar.google.com',
        timeMin: new Date().toISOString(),
        showDeleted: false,
        singleEvents: true,
        orderBy: 'startTime',
      }).then((response) => {
        this.events = response.result.items;
        this.calendarOptions.events = this.events.map(event => ({
          title: event.summary,
          start: event.start.dateTime || event.start.date,
          end: event.end.dateTime || event.end.date
        }));
      }).catch(error => {
        console.error('Error loading calendar events:', error);
      });
    }
  }
}
</script>

<style scoped>
::v-deep(.fc .fc-daygrid-day-frame) {
  background-color: #fff !important;
}

::v-deep(.fc-icon-chevron-right::before),
::v-deep(.fc-icon-chevron-left::before) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
