function academy_event_calendar_init() {
    let calendar_ins = document.getElementById("academy-calendar-body");
    if(!calendar_ins) {
        return;
    }
    let event_container = {},
        calender = document.querySelector("div.academy-calendar"),
        calender_title = document.getElementById("academy-calendar-title"),
        event_lists = document.getElementById("academy-calendar-event-lists"),
        calendar_body = calendar_ins.getElementsByTagName("tbody")[0],
        prev_month_btn = document.getElementById("academy-prev-month"),
        next_month_btn = document.getElementById("academy-next-month"),
        date_object = new Date(),
        today = new Date(),
        insert_html = function (obj) {
            event_lists.innerHTML = ``;
            Object.entries(event_container).forEach(function (e) {
                let content = '';
                if (e[1] instanceof Array) {
                    let count_events = e[1].length;
                    e[1].forEach(function (obj, index) {
                        let current_index = index + 1;

                        let status = '',
                            start_date = new Date(obj.start_date),
                            end_date = new Date(obj.end_date);
                        if (
                            today > end_date
                        ) {
                            status = calendar_ins.dataset.transExpired;
                        }
                        else if (
                            today >= start_date &&
                            today <= end_date
                        ) {
                            status = calendar_ins.dataset.transOngoing;
                        }
                        else if (today < end_date) {
                            status = calendar_ins.dataset.transUpcoming;
                        }


                        let date_time = new Date(obj.start_date);

                        content += `
                        <div class="academy-calendar-event">
                            <div class="academy-calendar-event__row">
                                <a href="${obj.link}" class="academy-calendar-event__title">${obj.post_title}</a>
                                <span class="academy-calendar-event__status academy-calendar-event__status__${status.toLowerCase()}">${status}</span>
                            </div>
                            <div class="academy-calendar-event__row">
                                <div class="academy-calendar-event__details">
                                    <div class="academy-calendar-event__platform">
                                        <i class="academy-icon academy-icon--meeting"></i>
                                        <span class="academy-calendar-event__platform">${calendar_ins.dataset.transPlatform}: ${obj.platform_type}</span>
                                    </div>

                                    <div class="academy-calendar-event__duration">
                                        <i class="academy-icon academy-icon--clock"></i>
                                        <span class="academy-calendar-event__duration">${calendar_ins.dataset.transDuration}: ${obj.duration}</span>
                                    </div>
                                    
                                    <div class="academy-calendar-event__host">
                                        <i class="academy-icon academy-icon--profile-two"></i>
                                        <span class="academy-calendar-event__host">${calendar_ins.dataset.transHost}: ${obj.host}</span>
                                    </div>
                                </div>
                                <div class="academy-calendar-event__start">
                                    ${date_time.toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"})}
                                </div>
                            </div>
                        </div>
                        `;

                        if (current_index != count_events) {
                            content += `<div class="academy-event-divider"></div>`;
                        }
                    })
                }
                event_lists.innerHTML += `
                <div id="event-${e[0]}" class="academy-calendar-card">
                    <div class="academy-calendar-card__title">
                        <div class="academy-calendar-card__day">${e[0]}</div>
                        <div class="academy-calendar-card__month">${calender_title.innerText.replace(/\d+/, '')}</div>
                    </div>
                    <div class="academy-calendar-card__content">${content}</div>
                </div>
                `;
            })


            calendar_ins.dataset.ids = Object.keys(event_container).join(',');
        },
        push_item = function (obj) {

            let date = obj.start_date;


            date = new Date(date);

            date = date.getDate();

            if (!(date in event_container)) {
                event_container[date] = []
            }
            event_container[date].push(obj);
        },
        get_events_data = function (year, month) {
            calender.style.removeProperty('display');
            jQuery.post(AcademyGlobal.ajaxurl, {
                action: 'academy_pro_calendar/get_events_data',
                security: AcademyGlobal.academy_nonce,
                year: year,
                month: month + 1
            }, function (res) {
                event_lists.innerHTML = ``;
                event_container = {};
                let data = res.data;
                if (
                    'booking' in data &&
                    'data' in data.booking &&
                    data.booking.data instanceof Array
                ) {
                    data.booking.data.forEach(function (obj) {
                        push_item(obj);
                    })
                }
                if (
                    'meet' in data &&
                    'data' in data.meet &&
                    data.meet.data instanceof Array
                ) {
                    data.meet.data.forEach(function (obj) {
                        push_item(obj);
                    })
                }
                if (
                    'zoom' in data &&
                    'data' in data.zoom &&
                    data.zoom.data instanceof Array
                ) {

                    data.zoom.data.forEach(function (obj) {
                        push_item(obj);
                    })
                }
                insert_html(event_container)

                // console.log(event_container)
                if (Object.keys(event_container).length == 0) {
                    document.getElementById("academy-calendar-event-lists").innerHTML = `
                        <div class="calendar-data-loading">
                            <div class="calendar-data-loading-msg">${calendar_ins.dataset.transEmpty}</div>
                        </div>
                    `;
                }

                let ids = String(document.getElementById("academy-calendar-body").dataset.ids).split(',');
                if (ids instanceof Array) {
                    ids.forEach(function (id) {
                        let cell = document.getElementById(`event-day-${id}`);
                        if (cell != null) {
                            cell.style.setProperty('background-color', 'var(--academy-primary-color)', 'important');
                            cell.style.setProperty('color', 'white', 'important');
                            cell.style.setProperty('font-weight', '800'), 'important';
                            cell.onclick = function (e) {
                                e.preventDefault();
                                let s = document.querySelector(`#event-${id}`);
                                // console.log(s)
                                if (s != null) {
                                    s.scrollIntoView({
                                        behavior: 'smooth',
                                        block: 'start'
                                    });
                                }
                            }
                        }
                    })
                }
            });
        },
        init_calendar = function () {
            let cell_count = 0,
                row = document.createElement("tr"),
                year = date_object.getFullYear(),
                month = date_object.getMonth(),
                first_day = new Date(year, month, 1),
                last_day = new Date(year, month + 1, 0),
                total_days = last_day.getDate(),
                first_day_weekday = first_day.getDay();



            document.getElementById("academy-calendar-event-lists").innerHTML = `
                <div class="calendar-data-loading">
                    <div class="calendar-data-loading-msg">${calendar_ins.dataset.transLoading}</div>
                </div>
            `;
            document.getElementById("academy-calendar-body").dataset.ids = '';
            calendar_body.innerHTML = "";
            calender_title.innerText = `${date_object.toLocaleString('default', { month: 'long' })} ${year}`;

            for (let i = 0; i < first_day_weekday; i++) {
                row.appendChild(document.createElement("td"));
                cell_count++;
            }

            for (let day = 1; day <= total_days; day++) {
                const cell = document.createElement("td");
                cell.id = `event-day-${day}`;
                cell.innerText = day;
                // cell.onclick = function(e){
                //     window.location.hash = `#event-${day}`
                //     e.preventDefault();
                // };




                row.appendChild(cell);
                cell_count++;

                if (cell_count % 7 === 0) {
                    calendar_body.appendChild(row);
                    row = document.createElement("tr");
                }
            }

            if (cell_count % 7 !== 0) {
                calendar_body.appendChild(row);
            }
            get_events_data(year, month);
        }

    prev_month_btn.onclick = () => {
        date_object.setMonth(date_object.getMonth() - 1);
        init_calendar();
    };

    next_month_btn.onclick = () => {
        date_object.setMonth(date_object.getMonth() + 1);
        init_calendar();
    };

    init_calendar();
}
jQuery(document).ready(function(){
    academy_event_calendar_init();
})