window.$ = window.$ || jQuery;

const ZmeetFrontend = {
    init() {
        this.bindEvents();
        this.changetime();
    },
    bindEvents() {
        $(document).on('click', '.zmeet-meeting-status', this.handleMeetingStatusButtonClick);
    },

    changetime() {
        // Get user's timezone using Intl
        const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

        // Handle the special case
        const user_timezone = timezone === "Asia/Katmandu" ? "Asia/Kathmandu" : timezone;
    
        const $meetingWrapper = $(".zmeet-wrapper");
    
        if ($meetingWrapper.length) {
            // Extract data attributes
            const originalTime = $meetingWrapper.data("zmeet-starttime");
            const originalTimezone = $meetingWrapper.data("zmeet-timezone");
            const meetingTitle = $meetingWrapper.data("zmeet-title");
            const meetingPermalink = $meetingWrapper.data("zmeet-permalilk");
            const enableUserZone = $meetingWrapper.data("zmeet-enable-user-zone");

            if (enableUserZone) {
                if (!originalTime || !originalTimezone) {
                    console.error("Error: Missing required data attributes.");
                    return;
                }
    
                // Parse original time
                const originalDate = new Date(originalTime);
                if (isNaN(originalDate)) {
                    console.error("Error: Invalid date format! Check the input.");
                    return;
                }
    
                // Format the date in user's timezone
                const dateFormatter = new Intl.DateTimeFormat('en-US', {
                    timeZone: user_timezone,
                    weekday: 'long',
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                    timeZoneName: 'short'
                });

                const timeFormatter = new Intl.DateTimeFormat('en-US', {
                    timeZone: user_timezone,
                    hour: 'numeric',
                    minute: 'numeric',
                    hour12: true,
                    timeZoneName: 'short'
                });
    
                const dayFormatter = new Intl.DateTimeFormat('en-US', {
                    timeZone: user_timezone,
                    weekday: 'long'
                });
    
                const convertedTime = dateFormatter.format(originalDate);
                const onlyTime = timeFormatter.format(originalDate);
                const dayName = dayFormatter.format(originalDate);
    
                // Update Recurring time
                const timeRecurring = $(".zmeet_retime");
                if (timeRecurring.length) {
                    timeRecurring.text(onlyTime);
                }
    
                // Update recurring day
                const dayRecurring = $(".zmeet_reday");
                if (dayRecurring.length) {
                    dayRecurring.each(function () {
                        const currentText = $(this).text();
                        const updatedText = currentText.replace(/\b(on\s+\w+)\b/, "on " + dayName);
                        $(this).text(updatedText);
                    });
                }
    
                // Update time & timezone elements — show meeting time + user local time
                const $timeElement = $(".mhbu-tm");
                if ($timeElement.length) {
                    $timeElement.each(function () {
                        const $el = $(this);
                        const meetingTZ = $el.data("meeting-timezone") || originalTimezone;
                        const meetingTimeFormatter = new Intl.DateTimeFormat("en-US", {
                            timeZone: meetingTZ,
                            weekday: "long",
                            year: "numeric",
                            month: "long",
                            day: "numeric",
                            hour: "numeric",
                            minute: "numeric",
                            hour12: true,
                            timeZoneName: "short",
                        });
                        const meetingTime = meetingTimeFormatter.format(originalDate);
                        $el.text(meetingTime);
                        if (meetingTZ !== user_timezone && !$el.next(".zmeet-user-time-label").length) {
                            const $userTimeLabel = $("<dt>", { class: "zmeet-user-time-label", text: "Your time:" });
                            const $userTimeValue = $("<dd>", { class: "zmeet-user-time", text: convertedTime });
                            $el.after($userTimeValue).after($userTimeLabel);
                        }
                    });
                }

                const $timezoneElement = $(".zmeet-tz");
                if ($timezoneElement.length) {
                    $timezoneElement.each(function () {
                        const $el = $(this);
                        const originalTZ = $el.data("original-tz") || originalTimezone;
                        if (originalTZ !== user_timezone && !$el.next(".zmeet-user-tz-label").length) {
                            const $userTzLabel = $("<dt>", { class: "zmeet-user-tz-label", text: "Your timezone:" });
                            const $userTzValue = $("<dd>", { class: "zmeet-user-tz", text: user_timezone });
                            $el.after($userTzValue).after($userTzLabel);
                        }
                    });
                }
    
                // Handle duration and end time
                const $durationElement = $(".zmeet-duration");
                const endDate = new Date(originalDate);
    
                let hours = 2; // Default to 2 hours
                let minutes = 0;
    
                if ($durationElement.length) {
                    const durationText = $durationElement.text().trim();
                    const hoursMatch = durationText.match(/(\d+)\s*hour/);
                    const minutesMatch = durationText.match(/(\d+)\s*minute/);
    
                    hours = hoursMatch ? parseInt(hoursMatch[1]) : 0;
                    minutes = minutesMatch ? parseInt(minutesMatch[1]) : 0;
                }
    
                endDate.setHours(endDate.getHours() + hours);
                endDate.setMinutes(endDate.getMinutes() + minutes);
    
                // Format times for Google Calendar URL
                const formatForCalendar = (date) => {
                    return date.toISOString().replace(/-|:|\.\d+/g, "");
                };
    
                const start_time_utc = formatForCalendar(originalDate);
                const end_time_utc = formatForCalendar(endDate);
    
                // Update Google Calendar button
                const $calendarButton = $(".zmeet-add-to-calendar-btn");
                if ($calendarButton.length) {
                    const calendar_url = `https://www.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(meetingTitle)}&dates=${start_time_utc}/${end_time_utc}&details=${encodeURIComponent('Join the meeting: ' + meetingPermalink)}&ctz=${encodeURIComponent(user_timezone)}`;
                    $calendarButton.attr("href", calendar_url);
                }
            }
        }
    },
    handleMeetingStatusButtonClick() {
        const meetingId = $(this).data('meeting-id');
        const postId = $(this).data('post-id');
        const meetingStatus = $(this).data('meeting-status');
        ZmeetFrontend.sendMeetingStatusData(meetingId, postId, meetingStatus);
    },
    sendMeetingStatusData(meetingId, postId, meetingStatus) {
        if (meetingStatus === 'end') {
            // Display a confirmation alert
            if (confirm( zmeetMeetingsData.strings.are_you_sure_you_want_to_end )) {
                // If user confirms, proceed with AJAX request
                sendAjaxRequest();
            }
        } else {
            // If meeting status is not 'end', proceed with AJAX request directly
            sendAjaxRequest();
        }

        if (meetingStatus === 'start') {
            // Display a confirmation alert
            if (confirm( zmeetMeetingsData.strings.are_you_sure_you_want_to_start )) {
                // If user confirms, proceed with AJAX request
                sendAjaxRequest();
            }
        } else {
            // If meeting status is not 'end', proceed with AJAX request directly
            sendAjaxRequest();
        }

        function sendAjaxRequest() {
            $.ajax({
                url: zmeet_frontend_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'zmeet_meeting_action',
                    nonce: zmeet_frontend_params.nonce,
                    meeting_id: meetingId,
                    post_id: postId,
                    meeting_status: meetingStatus
                },
                success: function (response) {
                    // Reload the page upon successful response
                    if (response.success) {
                        location.reload();
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                }
            });
        }
    },
   
};

$(document).ready(function () {
    ZmeetFrontend.init();
});
