<template>
    <div>
      <FullCalendar  :options="calendarOptions" />
    </div>
  </template>
  
  <script>
  import { ref, onMounted } from 'vue';
  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
    },
    setup() {
      const events = ref([]);
      const calendarOptions = ref({
        plugins: [dayGridPlugin],
        initialView: 'dayGridMonth',
        events: [],
        titleFormat: {
  year: 'numeric',
  month: '2-digit'
},
      locale: 'ko', // 한국어로 설정
      headerToolbar: {
        left: 'prev,next today',
        center: 'title',
        right: 'dayGridMonth,dayGridWeek,dayGridDay'
      },
      buttonText: {
        today: '오늘',
        month: '월',
        week: '주',
        day: '일'
      },
      showNonCurrentDates: false,
      fixedWeekCount: false, 
      });

      const loadClient = () => {
        if (window.gapi) {
          window.gapi.client.init({
            apiKey: 'AIzaSyCNthSbTXgMrCG_dbuIhnk9BEVlp0ME5gM', // 공개 캘린더에 접근하기 위한 API Key
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
          }).then(() => {
            loadCalendarEvents();  // 공개 캘린더 이벤트 불러오기
          }).catch(error => {
            console.error('Error initializing gapi client:', error);
          });
        } else {
          console.error('gapi is not defined');
        }
      };
  
      const loadCalendarEvents = () => {
        window.gapi.client.calendar.events.list({
          calendarId: 'ko.south_korea#holiday@group.v.calendar.google.com', // 공개 캘린더 ID
          timeMin: new Date().toISOString(), // 현재 시점 이후의 이벤트 가져오기
          showDeleted: false,
          singleEvents: true,
          orderBy: 'startTime',
        }).then((response) => {
          events.value = response.result.items;
          calendarOptions.value.events = events.value.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);
        });
      };
  
      onMounted(async () => {
        try {
          await loadGapiScript();
          if (window.gapi) {
            window.gapi.load('client', loadClient);
          } else {
            console.error('gapi is not defined after loading script');
          }
        } catch (error) {
          console.error('Error loading gapi script:', error);
        }
      });
  
      return {
        calendarOptions
      };
    },
  };
  </script>
  
  <style scoped>
  .fc .fc-daygrid-day-frame {
  background-color: #fff !important;
}
</style>