(function($) {
    // Event Calendar Function
    function initEventCalendar(selector, options) {
        var $calendar = $(selector);
        if (!$calendar.length) {
            console.warn('Calendar element not found:', selector);
            return;
        }

        var defaults = {
            events: {},
            startDay: 0
        };

        var settings = $.extend({}, defaults, options);
        var currentDate = new Date();
        var currentMonth = currentDate.getMonth();
        var currentYear = currentDate.getFullYear();

        var weekdays = settings.startDay === 1 
            ? ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

        var monthNames = [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ];

        // Initialize calendar
        function init() {
            console.log('Initializing calendar with events:', settings.events);
            renderWeekdays();
            renderCalendar();
            updateEventList();
            bindEvents();
        }

        // Render weekday headers
        function renderWeekdays() {
            var $weekdays = $calendar.find('.unlockafe-calendar-weekdays');
            $weekdays.empty();
            
            weekdays.forEach(function(day) {
                $weekdays.append('<div class="weekday">' + day + '</div>');
            });
        }

        // Render calendar
        function renderCalendar() {
            var $days = $calendar.find('.unlockafe-calendar-days');
            $days.empty();

            // Update header
            $calendar.find('.unlockafe-calendar-month').text(monthNames[currentMonth]);
            $calendar.find('.unlockafe-calendar-year').text(currentYear);

            // Get first day of month and number of days
            var firstDay = new Date(currentYear, currentMonth, 1);
            var lastDay = new Date(currentYear, currentMonth + 1, 0);
            var daysInMonth = lastDay.getDate();
            
            // Adjust first day based on start day setting
            var startingDay = firstDay.getDay();
            if (settings.startDay === 1) {
                startingDay = (startingDay === 0) ? 6 : startingDay - 1;
            }

            // Previous month days
            var prevMonth = new Date(currentYear, currentMonth, 0);
            var prevMonthDays = prevMonth.getDate();
            
            for (var i = startingDay - 1; i >= 0; i--) {
                var day = prevMonthDays - i;
                var dateStr = formatDate(currentYear, currentMonth - 1, day);
                $days.append(createDayElement(day, dateStr, true));
            }

            // Current month days
            var today = new Date();
            var isCurrentMonth = currentMonth === today.getMonth() && currentYear === today.getFullYear();
            
            for (var day = 1; day <= daysInMonth; day++) {
                var dateStr = formatDate(currentYear, currentMonth, day);
                var isToday = isCurrentMonth && day === today.getDate();
                $days.append(createDayElement(day, dateStr, false, isToday));
            }

            // Next month days to fill grid
            var totalCells = $days.children().length;
            var remainingCells = 42 - totalCells;
            
            for (var day = 1; day <= remainingCells; day++) {
                var dateStr = formatDate(currentYear, currentMonth + 1, day);
                $days.append(createDayElement(day, dateStr, true));
            }
        }

        // Create day element
        function createDayElement(day, dateStr, isOtherMonth, isToday) {
            var hasEvent = settings.events[dateStr] && settings.events[dateStr].length > 0;
            
            var classes = 'unlockafe-calendar-day';
            if (isOtherMonth) classes += ' other-month';
            if (isToday) classes += ' today';
            if (hasEvent) classes += ' has-event';

            var eventDots = '';
            if (hasEvent) {
                var events = settings.events[dateStr];
                var dotsToShow = Math.min(events.length, 3);
                eventDots = '<div class="unlockafe-calendar-day-events">';
                for (var i = 0; i < dotsToShow; i++) {
                    var color = events[i].color || '#0073aa';
                    eventDots += '<span class="unlockafe-calendar-event-dot" style="background-color: ' + color + '"></span>';
                }
                if (events.length > 3) {
                    eventDots += '<span style="font-size: 10px; color: #666;">+' + (events.length - 3) + '</span>';
                }
                eventDots += '</div>';
            }

            return $('<div class="' + classes + '" data-date="' + dateStr + '"><div class="unlockafe-calendar-day-number">' + day + '</div>' + eventDots + '</div>');
        }

        // Format date as YYYY-MM-DD
        function formatDate(year, month, day) {
            var d = new Date(year, month, day);
            var y = d.getFullYear();
            var m = String(d.getMonth() + 1);
            if (m.length === 1) m = '0' + m;
            var dd = String(d.getDate());
            if (dd.length === 1) dd = '0' + dd;
            return y + '-' + m + '-' + dd;
        }

        // Update event list
        function updateEventList() {
            var $eventList = $calendar.closest('.unlockafe-event-calendar-wrapper').find('.unlockafe-event-list-items');
            if (!$eventList.length) return;

            // Get all events for current month
            var monthEvents = [];
            Object.keys(settings.events).forEach(function(dateStr) {
                var date = new Date(dateStr + 'T00:00:00');
                if (date.getMonth() === currentMonth && date.getFullYear() === currentYear) {
                    settings.events[dateStr].forEach(function(event) {
                        monthEvents.push({
                            date: dateStr,
                            title: event.title,
                            time: event.time,
                            description: event.description,
                            location: event.location,
                            color: event.color
                        });
                    });
                }
            });

            // Sort by date
            monthEvents.sort(function(a, b) {
                return new Date(a.date) - new Date(b.date);
            });

            $eventList.empty();

            if (monthEvents.length === 0) {
                $eventList.html('<div class="unlockafe-event-list-empty"><i class="fa-solid fa-calendar-xmark"></i><p>No events scheduled for this month</p></div>');
                return;
            }

            monthEvents.forEach(function(event) {
                var date = new Date(event.date + 'T00:00:00');
                var dateFormatted = date.toLocaleDateString('en-US', { 
                    month: 'short', 
                    day: 'numeric',
                    year: 'numeric'
                });

                var locationHtml = '';
                if (event.location) {
                    locationHtml = '<span class="unlockafe-event-item-location"><i class="fa-solid fa-location-dot"></i>' + event.location + '</span>';
                }

                var timeHtml = '';
                if (event.time) {
                    timeHtml = '<span class="unlockafe-event-item-time"><i class="fa-solid fa-clock"></i>' + event.time + '</span>';
                }

                var descriptionHtml = event.description 
                    ? '<div class="unlockafe-event-item-description">' + event.description + '</div>' 
                    : '';

                var eventColor = event.color || '#0073aa';

                $eventList.append(
                    '<div class="unlockafe-event-item" style="border-left-color: ' + eventColor + '">' +
                        '<div class="unlockafe-event-item-date">' + dateFormatted + '</div>' +
                        '<h4 class="unlockafe-event-item-title">' + event.title + '</h4>' +
                        '<div class="unlockafe-event-item-meta">' + timeHtml + locationHtml + '</div>' +
                        descriptionHtml +
                    '</div>'
                );
            });
        }

        // Bind events
        function bindEvents() {
            // Navigation buttons
            $calendar.find('.unlockafe-calendar-prev').off('click').on('click', function() {
                currentMonth--;
                if (currentMonth < 0) {
                    currentMonth = 11;
                    currentYear--;
                }
                renderCalendar();
                updateEventList();
            });

            $calendar.find('.unlockafe-calendar-next').off('click').on('click', function() {
                currentMonth++;
                if (currentMonth > 11) {
                    currentMonth = 0;
                    currentYear++;
                }
                renderCalendar();
                updateEventList();
            });

            // Day click
            $calendar.on('click', '.unlockafe-calendar-day', function() {
                var dateStr = $(this).data('date');
                if (dateStr && settings.events[dateStr]) {
                    console.log('Events for', dateStr, settings.events[dateStr]);
                }
            });
        }

        // Initialize
        init();
    }

    // Make function globally available immediately
    if (typeof window !== 'undefined') {
        window.initEventCalendar = initEventCalendar;
        // Also expose without window for compatibility
        if (typeof window.$ !== 'undefined') {
            window.$.fn.initEventCalendar = initEventCalendar;
        }
    }

    // Function to initialize all calendars
    function initializeCalendars() {
        $('.unlockafe-event-calendar').each(function() {
            var $calendar = $(this);
            var calendarId = $calendar.attr('id');
            
            if (!calendarId) {
                console.warn('Calendar element missing ID');
                return;
            }
            
            // Skip if already initialized
            if ($calendar.data('initialized')) {
                return;
            }
            
            var startDay = parseInt($calendar.data('start-day')) || 0;
            
            // Get events from data attribute
            var events = {};
            var eventsData = $calendar.attr('data-events');
            if (eventsData && eventsData !== 'null' && eventsData !== '' && eventsData !== '[]') {
                try {
                    events = JSON.parse(eventsData);
                    console.log('Parsed events for calendar:', calendarId, events);
                } catch (e) {
                    console.error('Error parsing events data:', e, eventsData);
                    events = {};
                }
            } else {
                console.log('No events data found for calendar:', calendarId);
            }

            if (typeof initEventCalendar !== 'undefined') {
                console.log('Initializing calendar:', calendarId, 'with events:', events);
                initEventCalendar('#' + calendarId, {
                    events: events,
                    startDay: startDay
                });
                $calendar.data('initialized', true);
            } else {
                console.error('initEventCalendar function not found');
            }
        });
    }

    // Auto-initialize on document ready
    $(document).ready(function() {
        initializeCalendars();
    });

    // Re-initialize after a short delay
    setTimeout(function() {
        initializeCalendars();
    }, 100);

    // Re-initialize on Elementor frontend
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-event-calendar.default', function($scope) {
            setTimeout(function() {
                var $calendar = $scope.find('.unlockafe-event-calendar');
                if ($calendar.length && !$calendar.data('initialized')) {
                    var startDay = parseInt($calendar.data('start-day')) || 0;
                    
                    var events = {};
                    var eventsData = $calendar.attr('data-events');
                    if (eventsData && eventsData !== 'null' && eventsData !== '' && eventsData !== '[]') {
                        try {
                            events = JSON.parse(eventsData);
                        } catch (e) {
                            console.error('Error parsing events data:', e);
                            events = {};
                        }
                    }
                    
                    var calendarId = $calendar.attr('id');
                    if (calendarId && typeof initEventCalendar !== 'undefined') {
                        initEventCalendar('#' + calendarId, {
                            events: events,
                            startDay: startDay
                        });
                        $calendar.data('initialized', true);
                    }
                }
            }, 100);
        });
    }

    // Also initialize on Elementor preview loaded
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            setTimeout(function() {
                initializeCalendars();
            }, 200);
        });
    }

})(jQuery);
