<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

/**
 * Event Calendar Widget
 *
 * @since 1.0.0
 */
class Event_Calendar extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-event-calendar';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('Event Calendar', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-calendar ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['calendar', 'event', 'schedule', 'date', 'appointment', 'agenda'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return ['unlockafe-event-calendar-scripts'];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-event-calendar-style', 'font-awesome'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // Events Section
        $this->start_controls_section(
            'events_section',
            [
                'label' => __('Events', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'event_date',
            [
                'label' => __('Event Date', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DATE_TIME,
                'default' => date('Y-m-d H:i'),
                'picker_options' => [
                    'enableTime' => false,
                    'dateFormat' => 'Y-m-d',
                ],
            ]
        );

        $repeater->add_control(
            'event_time',
            [
                'label' => __('Event Time', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '10:00 AM',
                'placeholder' => __('e.g., 10:00 AM', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'event_title',
            [
                'label' => __('Event Title', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Event Title', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter event title', 'unlock-addons-for-elementor'),
                'label_block' => true,
            ]
        );

        $repeater->add_control(
            'event_description',
            [
                'label' => __('Event Description', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXTAREA,
                'default' => __('Event description goes here.', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter event description', 'unlock-addons-for-elementor'),
                'rows' => 3,
            ]
        );

        $repeater->add_control(
            'event_location',
            [
                'label' => __('Event Location', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'placeholder' => __('e.g., Conference Hall A', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'event_color',
            [
                'label' => __('Event Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#0073aa',
            ]
        );

        $this->add_control(
            'events_list',
            [
                'label' => __('Events', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'event_date' => date('Y-m-d'),
                        'event_time' => '10:00 AM',
                        'event_title' => __('Sample Event 1', 'unlock-addons-for-elementor'),
                        'event_description' => __('This is a sample event description.', 'unlock-addons-for-elementor'),
                    ],
                ],
                'title_field' => '{{{ event_title }}}',
            ]
        );

        $this->end_controls_section();

        // Settings Section
        $this->start_controls_section(
            'settings_section',
            [
                'label' => __('Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'start_day',
            [
                'label' => __('Week Starts On', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    '0' => __('Sunday', 'unlock-addons-for-elementor'),
                    '1' => __('Monday', 'unlock-addons-for-elementor'),
                ],
                'default' => '0',
            ]
        );

        $this->add_control(
            'show_event_list',
            [
                'label' => __('Show Event List', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Calendar Container
        $this->start_controls_section(
            'calendar_container_style_section',
            [
                'label' => __('Calendar Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'calendar_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-event-calendar',
            ]
        );

        $this->add_responsive_control(
            'calendar_padding',
            [
                'label' => __('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-event-calendar' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'calendar_border',
                'selector' => '{{WRAPPER}} .unlockafe-event-calendar',
            ]
        );

        $this->add_control(
            'calendar_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-event-calendar' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'calendar_box_shadow',
                'selector' => '{{WRAPPER}} .unlockafe-event-calendar',
            ]
        );

        $this->end_controls_section();

        // Header Style
        $this->start_controls_section(
            'header_style_section',
            [
                'label' => __('Calendar Header', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'header_background',
            [
                'label' => __('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#0073aa',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-header' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'header_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-header' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'header_typography',
                'selector' => '{{WRAPPER}} .unlockafe-calendar-header',
            ]
        );

        $this->end_controls_section();

        // Weekday Style
        $this->start_controls_section(
            'weekday_style_section',
            [
                'label' => __('Weekday Headers', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'weekday_background',
            [
                'label' => __('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#f5f5f5',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-weekdays' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'weekday_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-weekdays' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'weekday_typography',
                'selector' => '{{WRAPPER}} .unlockafe-calendar-weekdays',
            ]
        );

        $this->end_controls_section();

        // Day Cell Style
        $this->start_controls_section(
            'day_cell_style_section',
            [
                'label' => __('Day Cells', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'day_cell_background',
            [
                'label' => __('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'day_cell_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'day_cell_hover_background',
            [
                'label' => __('Hover Background', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day:hover' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'today_background',
            [
                'label' => __('Today Background', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#0073aa',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day.today' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'today_text_color',
            [
                'label' => __('Today Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day.today' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'event_day_background',
            [
                'label' => __('Event Day Background', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#e8f4f8',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-calendar-day.has-event' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Event List Style
        $this->start_controls_section(
            'event_list_style_section',
            [
                'label' => __('Event List', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'show_event_list' => 'yes',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'event_list_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-event-list',
            ]
        );

        $this->add_responsive_control(
            'event_list_padding',
            [
                'label' => __('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-event-list' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'event_title_typography',
                'label' => __('Event Title Typography', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlockafe-event-item-title',
            ]
        );

        $this->add_control(
            'event_title_color',
            [
                'label' => __('Event Title Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-event-item-title' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $widget_id = $this->get_id();
        $start_day = !empty($settings['start_day']) ? intval($settings['start_day']) : 0;
        $show_event_list = $settings['show_event_list'] === 'yes';

        // Prepare events data
        $events_data = [];
        if (!empty($settings['events_list'])) {
            foreach ($settings['events_list'] as $event) {
                $event_date = !empty($event['event_date']) ? $event['event_date'] : '';
                
                // Handle if date is an array (from Elementor DATE_TIME control)
                if (is_array($event_date)) {
                    $event_date = !empty($event_date['date']) ? $event_date['date'] : '';
                }
                
                if ($event_date) {
                    // Try multiple date formats
                    $date_obj = false;
                    $formats = ['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d', 'Y/m/d H:i:s', 'Y/m/d H:i', 'Y/m/d', 'd/m/Y H:i:s', 'd/m/Y H:i', 'd/m/Y', 'm/d/Y H:i:s', 'm/d/Y H:i', 'm/d/Y'];
                    
                    foreach ($formats as $format) {
                        $date_obj = \DateTime::createFromFormat($format, $event_date);
                        if ($date_obj !== false) {
                            break;
                        }
                    }
                    
                    // If still not parsed, try strtotime
                    if (!$date_obj) {
                        $timestamp = strtotime($event_date);
                        if ($timestamp !== false) {
                            $date_obj = new \DateTime();
                            $date_obj->setTimestamp($timestamp);
                        }
                    }
                    
                    if ($date_obj) {
                        $date_key = $date_obj->format('Y-m-d');
                        if (!isset($events_data[$date_key])) {
                            $events_data[$date_key] = [];
                        }
                        $events_data[$date_key][] = [
                            'title' => !empty($event['event_title']) ? esc_html($event['event_title']) : '',
                            'time' => !empty($event['event_time']) ? esc_html($event['event_time']) : '',
                            'description' => !empty($event['event_description']) ? wp_kses_post($event['event_description']) : '',
                            'location' => !empty($event['event_location']) ? esc_html($event['event_location']) : '',
                            'color' => !empty($event['event_color']) ? esc_attr($event['event_color']) : '#0073aa',
                        ];
                    }
                }
            }
        }

        // Pass events data to JavaScript via data attribute
        $events_json = wp_json_encode($events_data);
        $events_json_escaped = htmlspecialchars($events_json, ENT_QUOTES, 'UTF-8');

        ?>
        <div class="unlockafe-event-calendar-wrapper">
            <div id="unlockafe-event-calendar-<?php echo esc_attr($widget_id); ?>" class="unlockafe-event-calendar" data-start-day="<?php echo esc_attr($start_day); ?>" data-events='<?php echo $events_json_escaped; ?>'>
                <div class="unlockafe-calendar-header">
                    <button class="unlockafe-calendar-nav unlockafe-calendar-prev" type="button">
                        <i class="fa-solid fa-chevron-left"></i>
                    </button>
                    <div class="unlockafe-calendar-month-year">
                        <span class="unlockafe-calendar-month"></span>
                        <span class="unlockafe-calendar-year"></span>
                    </div>
                    <button class="unlockafe-calendar-nav unlockafe-calendar-next" type="button">
                        <i class="fa-solid fa-chevron-right"></i>
                    </button>
                </div>
                <div class="unlockafe-calendar-weekdays"></div>
                <div class="unlockafe-calendar-days"></div>
            </div>
            <?php if ($show_event_list): ?>
                <div class="unlockafe-event-list">
                    <h3 class="unlockafe-event-list-title"><?php echo __('Upcoming Events', 'unlock-addons-for-elementor'); ?></h3>
                    <div class="unlockafe-event-list-items"></div>
                </div>
            <?php endif; ?>
            
            <!-- Event Popup Modal -->
            <div class="unlockafe-event-popup-overlay" id="unlockafe-event-popup-<?php echo esc_attr($widget_id); ?>">
                <div class="unlockafe-event-popup">
                    <button class="unlockafe-event-popup-close" type="button">
                        <i class="fa-solid fa-times"></i>
                    </button>
                    <div class="unlockafe-event-popup-header">
                        <h3 class="unlockafe-event-popup-date"></h3>
                    </div>
                    <div class="unlockafe-event-popup-content"></div>
                </div>
            </div>
        </div>
        <script>
        (function() {
            var widgetId = '<?php echo esc_js($widget_id); ?>';
            var calendarId = 'unlockafe-event-calendar-<?php echo esc_js($widget_id); ?>';
            var startDay = <?php echo intval($start_day); ?>;
            var eventsData = <?php echo $events_json; ?>;
            var initialized = false;
            
            // Self-contained calendar initialization function
            function initCalendarInline() {
                if (initialized) return;
                
                if (typeof jQuery === 'undefined') {
                    setTimeout(initCalendarInline, 100);
                    return;
                }
                
                var $ = jQuery;
                var $calendar = $('#' + calendarId);
                if ($calendar.length === 0) {
                    setTimeout(initCalendarInline, 100);
                    return;
                }
                
                if ($calendar.data('initialized')) {
                    initialized = true;
                    return;
                }
                
                // Calendar initialization code
                var settings = {
                    events: eventsData || {},
                    startDay: startDay
                };
                
                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'];
                
                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;
                }
                
                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>');
                }
                
                function renderWeekdays() {
                    var $weekdays = $calendar.find('.unlockafe-calendar-weekdays');
                    $weekdays.empty();
                    weekdays.forEach(function(day) {
                        $weekdays.append('<div class="weekday">' + day + '</div>');
                    });
                }
                
                function renderCalendar() {
                    var $days = $calendar.find('.unlockafe-calendar-days');
                    $days.empty();
                    
                    $calendar.find('.unlockafe-calendar-month').text(monthNames[currentMonth]);
                    $calendar.find('.unlockafe-calendar-year').text(currentYear);
                    
                    var firstDay = new Date(currentYear, currentMonth, 1);
                    var lastDay = new Date(currentYear, currentMonth + 1, 0);
                    var daysInMonth = lastDay.getDate();
                    var startingDay = firstDay.getDay();
                    if (settings.startDay === 1) {
                        startingDay = (startingDay === 0) ? 6 : startingDay - 1;
                    }
                    
                    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));
                    }
                    
                    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));
                    }
                    
                    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));
                    }
                }
                
                function updateEventList() {
                    var $eventList = $calendar.closest('.unlockafe-event-calendar-wrapper').find('.unlockafe-event-list-items');
                    if (!$eventList.length) return;
                    
                    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 || '#0073aa'
                                });
                            });
                        }
                    });
                    
                    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 = event.location ? '<span class="unlockafe-event-item-location"><i class="fa-solid fa-location-dot"></i>' + event.location + '</span>' : '';
                        var timeHtml = event.time ? '<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>' : '';
                        
                        $eventList.append(
                            '<div class="unlockafe-event-item" style="border-left-color: ' + event.color + '">' +
                                '<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>'
                        );
                    });
                }
                
                function bindEvents() {
                    $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 - show popup if events exist
                    $calendar.on('click', '.unlockafe-calendar-day', function() {
                        var dateStr = $(this).data('date');
                        if (dateStr && settings.events[dateStr] && settings.events[dateStr].length > 0) {
                            showEventPopup(dateStr, settings.events[dateStr]);
                        }
                    });
                }
                
                function showEventPopup(dateStr, events) {
                    var $popup = $calendar.closest('.unlockafe-event-calendar-wrapper').find('.unlockafe-event-popup-overlay');
                    if (!$popup.length) return;
                    
                    var date = new Date(dateStr + 'T00:00:00');
                    var dateFormatted = date.toLocaleDateString('en-US', { 
                        weekday: 'long',
                        month: 'long', 
                        day: 'numeric',
                        year: 'numeric'
                    });
                    
                    var $popupHeader = $popup.find('.unlockafe-event-popup-date');
                    var $popupContent = $popup.find('.unlockafe-event-popup-content');
                    
                    $popupHeader.text(dateFormatted);
                    $popupContent.empty();
                    
                    events.forEach(function(event) {
                        var locationHtml = event.location ? '<span class="unlockafe-event-item-location"><i class="fa-solid fa-location-dot"></i>' + event.location + '</span>' : '';
                        var timeHtml = event.time ? '<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';
                        
                        $popupContent.append(
                            '<div class="unlockafe-event-popup-item" style="border-left-color: ' + eventColor + '">' +
                                '<h4 class="unlockafe-event-popup-item-title">' + (event.title || 'Event') + '</h4>' +
                                '<div class="unlockafe-event-popup-item-meta">' + timeHtml + locationHtml + '</div>' +
                                descriptionHtml +
                            '</div>'
                        );
                    });
                    
                    $popup.addClass('active');
                    
                    // Close popup handlers
                    $popup.find('.unlockafe-event-popup-close').off('click').on('click', function() {
                        $popup.removeClass('active');
                    });
                    
                    $popup.off('click').on('click', function(e) {
                        if ($(e.target).hasClass('unlockafe-event-popup-overlay')) {
                            $popup.removeClass('active');
                        }
                    });
                    
                    // Close on ESC key
                    $(document).off('keydown.eventCalendar').on('keydown.eventCalendar', function(e) {
                        if (e.keyCode === 27) {
                            $popup.removeClass('active');
                        }
                    });
                }
                
                // Initialize
                renderWeekdays();
                renderCalendar();
                updateEventList();
                bindEvents();
                
                $calendar.data('initialized', true);
                initialized = true;
                console.log('Calendar initialized:', calendarId);
            }
            
            // Initialize
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    setTimeout(initCalendarInline, 100);
                });
            } else {
                setTimeout(initCalendarInline, 100);
            }
            
            setTimeout(initCalendarInline, 300);
            setTimeout(initCalendarInline, 600);
            setTimeout(initCalendarInline, 1000);
            
            if (typeof elementorFrontend !== 'undefined') {
                elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-event-calendar.default', function($scope) {
                    setTimeout(initCalendarInline, 200);
                });
                
                if (elementorFrontend.isEditMode) {
                    setTimeout(initCalendarInline, 1500);
                    setTimeout(initCalendarInline, 3000);
                }
            }
        })();
        </script>
        <?php
    }
}

