<?php

class agile_tix_ShortCodes
{



    static function ats_registerShortCodes()
    {
        //add_shortcode('ats_event_grid', 'agile_tix_ShortCodes::ats_shortcode_event_gridCB');
        add_shortcode('ats_event_list', 'agile_tix_ShortCodes::ats_shortcode_event_listCB');
        add_shortcode('ats_coming_soon_banner', 'agile_tix_ShortCodes::ats_shortcode_coming_soon_bannerCB');
        add_shortcode('ats_now_showing_banner', 'agile_tix_ShortCodes::ats_shortcode_now_showing_bannerCB');
    }


    static function ats_shortcode_event_listCB($atts)
    {
        $postConfigType = get_option('agile_field_config_integration_type');
        $postTypeSet = '';

        switch ($postConfigType) {
            case 'none':
                $postTypeSet = 'agile_post';
                break;
            case 'event_champ':
                $postTypeSet = 'event';
                break;
            case 'custom':
                $postTypeSet = get_option('agile_field_theme_custom_map_post_type');
                break;
            case 'amy_movie':
                $postTypeSet = 'amy_movie';
                break;
            default:
                $postTypeSet = 'agile_post'; // fallback for unexpected values
        }

        $atts = shortcode_atts([
            'posttype' => $postTypeSet, 
        ], $atts, 'ats_event_list');

        $postType = sanitize_key($atts['posttype']);

        $args = ['numberposts' => 99, 'post_type' => $postType, 'fields' => 'ids'];
        $posts = get_posts($args);


        $eventsData = [];
        $allGenres = [];
        $eventDates = [];

        foreach ($posts as $post_id) {
            $eventID = get_post_meta($post_id, "ATS_EventID", true);
            if ($eventID) {
                $title = get_the_title($post_id);
                $genres = wp_get_object_terms($post_id, 'genre');
                $genreNames = [];

                if (!is_wp_error($genres) && !empty($genres)) {
                    foreach ($genres as $genre) {
                        $genreNames[] = $genre->name;
                        $allGenres[] = $genre->name;
                    }
                }

                // Collect event dates for calendar
                $showtimes = get_post_meta($post_id, "ATS_ShowTimes", true);
                if ($showtimes && is_array($showtimes)) {
                    foreach ($showtimes as $showtimeData) {
                        if (is_array($showtimeData)) {
                            foreach ($showtimeData as $showtime => $purchaseLink) {
                                $date = new DateTime($showtime);
                                $eventDates[] = $date->format('Y-m-d');
                            }
                        }
                    }
                }

                $eventsData[] = [
                    'id' => $post_id,
                    'title' => $title,
                    'first_letter' => strtoupper(substr($title, 0, 1)),
                    'genres' => $genreNames
                ];
            }
        }

        // Get all unique starting letters, genres, and dates
        $availableLetters = array_unique(array_column($eventsData, 'first_letter'));
        $availableGenres = array_unique($allGenres);
        $availableDates = array_unique($eventDates);
        sort($availableGenres);
        sort($availableDates);

        $listContent = '<div class="ats_event_list_events_container">';



        $listContent .= '<h2 class="ats_event_list_events_header">EVENTS <span class="events-icons"></span></h2>';
        $listContent .= "<span><span id='viewByAZbtn'><b>View A-Z</b></span>    |   <span id='viewByDatebtn'>View by Date</span></span><br/>";

        //A-Z filter
        $listContent .= '<div class="ats_event_list_filter_toggle_container">';
        $listContent .= '<button class="ats_filter_toggle_btn" style="margin-bottom:12px; margin-right:8px;" onclick="toggleFilter(\'alphabet\')">';
        $listContent .= '<svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
        $listContent .= '<path d="M3 4.6C3 4.03995 3 3.75992 3.10899 3.54601C3.20487 3.35785 3.35785 3.20487 3.54601 3.10899C3.75992 3 4.03995 3 4.6 3H19.4C19.9601 3 20.2401 3 20.454 3.10899C20.6422 3.20487 20.7951 3.35785 20.891 3.54601C21 3.75992 21 4.03995 21 4.6V6.33726C21 6.58185 21 6.70414 20.9724 6.81923C20.9479 6.92127 20.9075 7.01881 20.8526 7.10828C20.7908 7.2092 20.7043 7.29568 20.5314 7.46863L14.4686 13.5314C14.2957 13.7043 14.2092 13.7908 14.1474 13.8917C14.0925 13.9812 14.0521 14.0787 14.0276 14.1808C14 14.2959 14 14.4182 14 14.6627V17L10 21V14.6627C10 14.4182 10 14.2959 9.97237 14.1808C9.94787 14.0787 9.90747 13.9812 9.85264 13.8917C9.7908 13.7908 9.70432 13.7043 9.53137 13.5314L3.46863 7.46863C3.29568 7.29568 3.2092 7.2092 3.14736 7.10828C3.09253 7.01881 3.05213 6.92127 3.02763 6.81923C3 6.70414 3 6.58185 3 6.33726V4.6Z" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '</svg>';
        $listContent .= ' A-Z';
        $listContent .= '</button>';

        //if we don't have any genres to list, don't bother showing the button
        $genreBtnStyle = '';
        if (count($availableGenres) < 1){
            $genreBtnStyle = 'display:none;';
        }

        //Genre Filter
        $listContent .= `<button class="ats_filter_toggle_btn" style="margin-bottom:12px; margin-right:8px; ${$genreBtnStyle}" onclick="toggleFilter(\'genre\')">`;
        $listContent .= `<svg style="${$genreBtnStyle}" width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">`;
        $listContent .= '<path opacity="0.34" d="M5 10H7C9 10 10 9 10 7V5C10 3 9 2 7 2H5C3 2 2 3 2 5V7C2 9 3 10 5 10Z" stroke="#292D32" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M17 10H19C21 10 22 9 22 7V5C22 3 21 2 19 2H17C15 2 14 3 14 5V7C14 9 15 10 17 10Z" stroke="#292D32" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path opacity="0.34" d="M17 22H19C21 22 22 21 22 19V17C22 15 21 14 19 14H17C15 14 14 15 14 17V19C14 21 15 22 17 22Z" stroke="#292D32" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M5 22H7C9 22 10 21 10 19V17C10 15 9 14 7 14H5C3 14 2 15 2 17V19C2 21 3 22 5 22Z" stroke="#292D32" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '</svg>';
        $listContent .= `<span style="${$genreBtnStyle}">Genre</span>`;
        $listContent .= '</button>';


        //Calendar Filter
        $listContent .= '<div class="ats-calendar-container">';
        $listContent .= '<button class="ats_filter_toggle_btn" style="margin-bottom:12px;" onclick="toggleCalendar()">';
        $listContent .= '<svg width="24px" height="24px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">';
        $listContent .= '<path d="M8 2V5" stroke="#000000" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M16 2V5" stroke="#000000" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M3.5 9.09H20.5" stroke="#000000" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M21 8.5V17C21 20 19.5 22 16 22H8C4.5 22 3 20 3 17V8.5C3 5.5 4.5 3.5 8 3.5H16C19.5 3.5 21 5.5 21 8.5Z" stroke="#000000" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M15.6947 13.7H15.7037" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M15.6947 16.7H15.7037" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M11.9955 13.7H12.0045" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M11.9955 16.7H12.0045" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M8.29431 13.7H8.30329" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '<path d="M8.29431 16.7H8.30329" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>';
        $listContent .= '</svg>';
        $listContent .= ' Date';
        $listContent .= '</button>';

        // Add calendar overlay and calendar
        $listContent .= '<div class="ats-calendar-overlay" onclick="hideCalendar()"></div>';
        $listContent .= '<div class="ats-calendar" id="ats-eventCalendar">';
        $listContent .= '<div class="ats-calendar__opts">';
        $listContent .= '<select name="ats-calendar__month" id="ats-calendar__month" onchange="updateCalendar()">';
        for ($i = 0; $i < 12; $i++) {
            $monthName = date('M', mktime(0, 0, 0, $i + 1, 1));
            $selected = ($i == (date('n') - 1)) ? ' selected' : '';
            $listContent .= '<option value="' . $i . '"' . $selected . '>' . $monthName . '</option>';
        }
        $listContent .= '</select>';
        $listContent .= '<select name="ats-calendar__year" id="ats-calendar__year" onchange="updateCalendar()">';
        $currentYear = date('Y');
        for ($year = $currentYear; $year <= $currentYear + 1; $year++) { 
            $selected = ($year == $currentYear) ? ' selected' : '';
            $listContent .= '<option value="' . $year . '"' . $selected . '>' . $year . '</option>';
        }

        $listContent .= '</select>';
        $listContent .= '</div>';
        $listContent .= '<div class="ats-calendar__body">';
        $listContent .= '<div class="ats-calendar__days">';
        $listContent .= '<div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div>';
        $listContent .= '</div>';
        $listContent .= '<div class="ats-calendar__dates" id="ats-calendarDates"></div>';
        $listContent .= '</div>';
        $listContent .= '<div class="ats-calendar__buttons">';
        $listContent .= '<button class="ats-calendar__button ats-calendar__button--red" onclick="clearDateFilter()">Clear</button>';
        $listContent .= '<button class="ats-calendar__button ats-calendar__button--primary" onclick="hideCalendar()">Close</button>';
        $listContent .= '</div>';
        $listContent .= '</div>';
        $listContent .= '</div>';
        $listContent .= '</div>';

        // Add the alphabetical filter
        $listContent .= '<div class="ats_event_list_filter_container ats_alphabet_filter" style="display: none;">';
        $listContent .= '<div class="ats_event_list_filter_label"></div>';
        $listContent .= '<div class="ats_event_list_filter_buttons" style="display:inline;">';
        $listContent .= '<button class="ats_filter_btn ats_filter_btn_active" style="margin-right: 8px;" data-filter="all" data-filter-type="alphabet">All</button>';

        //create A-Z buttons, disable those without events
        for ($i = 65; $i <= 90; $i++) {
            $letter = chr($i);
            $hasEvents = in_array($letter, $availableLetters);
            $disabledClass = $hasEvents ? '' : ' ats_filter_btn_disabled';
            $disabled = $hasEvents ? '' : ' disabled';
            $listContent .= '<button class="ats_filter_btn' . $disabledClass . '" data-filter="' . $letter . '" data-filter-type="alphabet"' . $disabled . '>' . $letter . '</button>';
        }

        $listContent .= '</div>';
        $listContent .= '</div>';

        //add genre filter
        $listContent .= '<div class="ats_event_list_filter_container ats_genre_filter" style="display: none;">';
        $listContent .= '<div class="ats_event_list_filter_label"></div>';
        $listContent .= '<div class="ats_event_list_filter_buttons" style="display:inline;">';
        $listContent .= '<button class="ats_filter_btn ats_filter_btn_active" style="margin-right: 8px;" data-filter="all" data-filter-type="genre">All</button>';

        // Create genre buttons
        foreach ($availableGenres as $genre) {
            $listContent .= '<button class="ats_filter_btn" data-filter="' . esc_attr($genre) . '" data-filter-type="genre">' . esc_html($genre) . '</button>';
        }

        $listContent .= '</div>';
        $listContent .= '</div>';

        // Generate events HTML
        $listContent .= "<div id='ats_event_list_AZView'>";
        $showtimeList = [];
        foreach ($posts as $post_id) {
            $eventID = get_post_meta($post_id, "ATS_EventID", true);
            if ($eventID) {
                $title = get_the_title($post_id);
                $firstLetter = strtoupper(substr($title, 0, 1));
                $permalink = get_permalink($post_id);
                $thumb_id = get_post_thumbnail_id($post_id);
                $thumbnail = $thumb_id ? wp_get_attachment_image($thumb_id, 'medium', false, ['class' => 'event-thumbnail']) : '';
                $excerpt = get_the_excerpt($post_id);
                $content = get_post_field('post_content', $post_id);
                $description = !empty($excerpt) ? $excerpt : wp_trim_words($content, 30, '...');

                // Get genres for this event
                $genres = wp_get_object_terms($post_id, 'genre');
                $genreNames = [];
                if (!is_wp_error($genres) && !empty($genres)) {
                    foreach ($genres as $genre) {
                        $genreNames[] = $genre->name;
                    }
                }
                $genreData = !empty($genreNames) ? implode(',', $genreNames) : '';

                // Get event dates and times - collect all dates for this event
                $eventDatesList = [];
                $showtimes = get_post_meta($post_id, "ATS_ShowTimes", true);
                if ($showtimes && is_array($showtimes)) {
                    foreach ($showtimes as $showtimeData) {
                        if (is_array($showtimeData)) {
                            foreach ($showtimeData as $showtime => $purchaseLink) {
                                $date = new DateTime($showtime);
                                $eventDatesList[] = $date->format('Y-m-d');
                            }
                        }
                    }
                }
                $eventDatesData = !empty($eventDatesList) ? implode(',', array_unique($eventDatesList)) : '';

                $showtimeList[] = $showtimes;
                $listContent .= '<div class="ats_event_list_event_item" data-letter="' . $firstLetter . '" data-genres="' . esc_attr($genreData) . '" data-dates="' . esc_attr($eventDatesData) . '">';

                $listContent .= '<div class="ats_event_list_event_content">';

                // Thumbnail
                if ($thumbnail) {
                    $listContent .= '<div class="ats_event_list_event_image">';
                    $listContent .= '<a href="' . esc_url($permalink) . '">' . $thumbnail . '</a>';
                    $listContent .= '</div>';
                }

                $listContent .= '<div class="ats_event_list_event_details">';
                $listContent .= '<h3 class="ats_event_list_event_title"><a href="' . esc_url($permalink) . '">' . esc_html($title) . '</a></h3>';
                $listContent .= '<p class="ats_event_list_event_description">' . esc_html($description) . '</p>';

                if ($showtimes && is_array($showtimes)) {
                    $groupedShowtimes = [];
                    foreach ($showtimes as $showtimeData) {
                        if (is_array($showtimeData)) {
                            foreach ($showtimeData as $showtimeString => $purchaseLink) {
                                $date = new DateTime($showtimeString);
                                $dateKey = $date->format('Y-m-d');
                                $time = $date->format('H:i');
                                if (!isset($groupedShowtimes[$dateKey])) {
                                    $groupedShowtimes[$dateKey] = [
                                        'date' => $date,
                                        'times' => []
                                    ];
                                }
                                $groupedShowtimes[$dateKey]['times'][] = [
                                    'time' => $time,
                                    'purchaseLink' => $purchaseLink
                                ];
                            }
                        }
                    }
                    ksort($groupedShowtimes);

                    //generate unique identifier for this showtimes list
                    $uniqueId = uniqid('showtimes_');
                    $listContent .= '<div class="ats_event_list_event_showtimes">';
                    $index = 0;
                    $totalDays = count($groupedShowtimes);
                    $hasMoreThanFive = $totalDays > 5;

                    foreach ($groupedShowtimes as $dateData) {
                        $isHidden = false;
                        if ($hasMoreThanFive && $index >= 5) {
                            $isHidden = true;
                        }
                        $date = $dateData['date'];
                        $month = $date->format('M');
                        $day = $date->format('j');
                        $hiddenClass = $isHidden ? ' ats_showtime_hidden_' . $uniqueId : '';
                        $listContent .= '<div class="ats_event_list_showtime_row' . $hiddenClass . '">';
                        $dateString = $month . ' ' . $day;
                        $paddedDate = str_pad($dateString, 6, ' ', STR_PAD_RIGHT);
                        $listContent .= '<span class="ats_event_list_showtime_date">' . $paddedDate . ' - </span>';

                        //sort times while preserving purchase link association
                        usort($dateData['times'], function ($a, $b) {
                            return strcmp($a['time'], $b['time']);
                        });

                        foreach ($dateData['times'] as $timeData) {
                            $time = $timeData['time'];
                            $purchaseLink = $timeData['purchaseLink'];
                            $timeObj = DateTime::createFromFormat('H:i', $time);
                            $formattedTime = $timeObj ? $timeObj->format('g:i A') : $time;
                            $paddedTime = str_pad($formattedTime, 8, ' ', STR_PAD_RIGHT);

                            $listContent .= '<a href="' . esc_attr($purchaseLink) . '" class="ats_event_list_showtime_time">' . $paddedTime . '</a>';
                        }
                        $listContent .= '</div>';
                        $index += 1;
                    }

                    //add "Show More" button at the bottom if there are more than 5 days
                    if ($hasMoreThanFive) {
                        $moreDaysCount = $totalDays - 5;
                        $listContent .= '<div class="ats_showtime_toggle_container">';
                        $listContent .= '<button class="ats_showtime_toggle_btn" onclick="toggleShowtimes(this, \'' . $uniqueId . '\', ' . $moreDaysCount . ')">Show More (' . $moreDaysCount . ' more days)</button>';
                        $listContent .= '</div>';
                    }
                    $listContent .= '</div>';

                    //add js for toggle functionality
                    if ($hasMoreThanFive) {
                        $listContent .= '<script>
                    function toggleShowtimes(button, uniqueId, moreDaysCount) {
                        const hiddenRows = document.querySelectorAll(".ats_showtime_hidden_" + uniqueId);
                        const isShowing = button.textContent.includes("Show More");
                        hiddenRows.forEach(row => {
                            if (isShowing) {
                                // Expand: restore normal margins and set max-height to scrollHeight
                                row.style.marginBottom = "5px";
                                row.style.paddingTop = "";
                                row.style.paddingBottom = "";
                                row.style.maxHeight = (row.scrollHeight + 20) + "px";
                                row.style.overflow = "hidden";
                            } else {
                                // Collapse: remove margins and set max-height to 0
                                row.style.marginBottom = "0";
                                row.style.paddingTop = "0";
                                row.style.paddingBottom = "0";
                                row.style.maxHeight = "0";
                                row.style.overflow = "hidden";
                            }
                        });
                        if (isShowing) {
                            button.textContent = "Show Less";
                            button.classList.add("ats_showtime_toggle_btn_active");
                        } else {
                            button.textContent = "Show More (" + moreDaysCount + " more days)";
                            button.classList.remove("ats_showtime_toggle_btn_active");
                        }
                    }
                    </script>';
                    }
                } else {
                    // Fallback to single date if showtimes not available
                    $firstEndDate = get_post_meta($post_id, "ATS_firstEndDate", true);
                    if ($firstEndDate) {
                        $date = new DateTime($firstEndDate);
                        $readableDate = $date->format('D, M j \a\t g:i A');
                        $listContent .= '<div class="ats_event_list_event_single_date">' . $readableDate . '</div>';
                    }
                }

                // More Details button
                $listContent .= '<a href="' . esc_url($permalink) . '" class="ats_event_list_more_details_btn">More Details</a>';

                $listContent .= '</div>'; // .event-details
                $listContent .= '</div>'; // .event-content
                $listContent .= '</div>'; // .event-item
            }
        }
        $listContent .= "</div>"; // #ats_event_list_AZView

        $listContent .= "<div id='ats_event_list_dateView' style='display:none;'>";

        //build the event list by date - collect events with their showtimes
        $groupedShowDays = [];
        foreach ($posts as $post_id) {
            $eventID = get_post_meta($post_id, "ATS_EventID", true);
            if ($eventID) {
                $title = get_the_title($post_id);
                $firstLetter = strtoupper(substr($title, 0, 1)); //add first letter for filtering
                $permalink = get_permalink($post_id);
                $thumb_id = get_post_thumbnail_id($post_id);
                $thumbnail = $thumb_id ? wp_get_attachment_image($thumb_id, 'thumbnail', false, ['class' => 'event-thumbnail-small']) : '';
                $excerpt = get_the_excerpt($post_id);
                $content = get_post_field('post_content', $post_id);
                $description = !empty($excerpt) ? $excerpt : wp_trim_words($content, 15, '...');

                //get genres for this event
                $genres = wp_get_object_terms($post_id, 'genre');
                $genreNames = [];
                if (!is_wp_error($genres) && !empty($genres)) {
                    foreach ($genres as $genre) {
                        $genreNames[] = $genre->name;
                    }
                }
                $genreData = !empty($genreNames) ? implode(',', $genreNames) : '';
                $showtimes = get_post_meta($post_id, "ATS_ShowTimes", true);
                if ($showtimes && is_array($showtimes)) {
                    foreach ($showtimes as $showtimeData) {
                        if (is_array($showtimeData)) {
                            foreach ($showtimeData as $showtime => $purchaseLink) {
                                $date = new DateTime($showtime);
                                $dateKey = $date->format('Y-m-d');
                                $time = $date->format('H:i');
                                if (!isset($groupedShowDays[$dateKey])) {
                                    $groupedShowDays[$dateKey] = [
                                        'date' => $date,
                                        'events' => []
                                    ];
                                }
                                //check if this event is already added for this date
                                $eventExists = false;
                                foreach ($groupedShowDays[$dateKey]['events'] as &$existingEvent) {
                                    if ($existingEvent['id'] == $post_id) {
                                        //$existingEvent['times'][] = $time;
                                         $existingEvent['times'][] = [
                                                'time' => $time,
                                                'purchaseLink' => $purchaseLink
                                            ];
                                        $eventExists = true;
                                        break;
                                    }
                                }
                                //if event doesn't exist for this date, add it
                                if (!$eventExists) {
                                    $groupedShowDays[$dateKey]['events'][] = [
                                        'id' => $post_id,
                                        'title' => $title,
                                        'first_letter' => $firstLetter, //add first letter for filtering
                                        'permalink' => $permalink,
                                        'thumbnail' => $thumbnail,
                                        'description' => $description,
                                        'genres' => $genreData,
                                        //'times' => [$time]
                                        'times' => [[
                                            'time' => $time,
                                            'purchaseLink' => $purchaseLink
                                        ]]
                                    ];
                                }
                            }
                        }
                    }
                }
            }
        }

        ksort($groupedShowDays);

        //generate the timeline HTML
        if (!empty($groupedShowDays)) {
            $listContent .= '<div class="ats_event_timeline_container">';

            foreach ($groupedShowDays as $dateKey => $dayData) {
                $date = $dayData['date'];
                $dayName = $date->format('D'); //short day name
                $monthDay = $date->format('M j'); //short month and day

                $listContent .= '<div class="ats_timeline_day" data-date="' . $dateKey . '">';
                $listContent .= '<div class="ats_timeline_date_header">';
                $listContent .= '<div class="ats_timeline_day_name">' . $dayName . ' ' . $monthDay . '</div>';
                $listContent .= '</div>';

                $listContent .= '<div class="ats_timeline_events">';

                //sort events by their earliest showtime for this day
                usort($dayData['events'], function ($a, $b) {
                    $aEarliest = min(array_column($a['times'], 'time'));
                    $bEarliest = min(array_column($b['times'], 'time'));
                    return strcmp($aEarliest, $bEarliest);
                });

                foreach ($dayData['events'] as $event) {
                    usort($event['times'], function ($a, $b) {
                        return strcmp($a['time'], $b['time']);
                    });

                    //add data attributes for filtering
                    $listContent .= '<div class="ats_timeline_event" data-letter="' . $event['first_letter'] . '" data-genres="' . esc_attr($event['genres']) . '" data-date="' . $dateKey . '">';

                    if ($event['thumbnail']) {
                        $listContent .= '<div class="ats_event_list_event_image">';
                        $listContent .= '<a href="' . esc_url($event['permalink']) . '">' . $event['thumbnail'] . '</a>';
                        $listContent .= '</div>';
                    }

                    $listContent .= '<div class="ats_timeline_event_times">';
                    foreach ($event['times'] as $timeData) {
                        $time = $timeData['time'];
                        $purchaseLink = $timeData['purchaseLink'];
                        $timeObj = DateTime::createFromFormat('H:i', $time);
                        $formattedTime = $timeObj ? $timeObj->format('g:i A') : $time;
                        $listContent .= '<a href="' . esc_attr($purchaseLink) . '" class="ats_event_list_showtime_time ats_timeline_event_times" style="margin-bottom:3px;">' . $formattedTime . '</a>'; //
                    }
                    $listContent .= '</div>';

                    $listContent .= '<div class="ats_timeline_event_content">';

                    

                    $listContent .= '<div class="ats_timeline_event_details">';
                    $listContent .= '<h4 class="ats_timeline_event_title">';
                    $listContent .= '<a href="' . esc_url($event['permalink']) . '">' . esc_html($event['title']) . '</a>';
                    $listContent .= '</h4>';
                    $listContent .= '<p class="ats_timeline_event_description">' . esc_html($event['description']) . '</p>';
                    $listContent .= '</div>';

                    $listContent .= '</div>'; // .ats_timeline_event_content
                    $listContent .= '</div>'; // .ats_timeline_event
                }

                $listContent .= '</div>'; // .ats_timeline_events
                $listContent .= '</div>'; // .ats_timeline_day
            }

            $listContent .= '</div>'; // .ats_event_timeline_container
        } else {
            $listContent .= '<div class="ats_no_events_message">No events found.</div>';
        }

        $listContent .= "</div>"; // #ats_event_list_dateView

        $availableDatesJson = json_encode($availableDates);

        //dump the JS in along side the code directly

        $listContent .= '<script>
            let currentVisibleFilter = null;
            let selectedDate = null;
            let availableEventDates = ' . $availableDatesJson . ';

            function toggleCalendar() {
                const calendar = document.getElementById("ats-eventCalendar");
                const overlay = document.querySelector(".ats-calendar-overlay");
                const calendarBtn = document.querySelector(".ats-calendar-container .ats_filter_toggle_btn");

                if (calendar.style.display === "none" || calendar.style.display === "") {
                    // Position calendar below the button
                    const rect = calendarBtn.getBoundingClientRect();
                    calendar.style.display = "block";
                    calendar.style.position = "fixed";
                    calendar.style.top = "50%";
                    calendar.style.left = "50%";
                    calendar.style.transform = "translate(-50%, -50%)";
                    overlay.style.display = "block";

                    // Update calendar with current month
                    updateCalendar();
                } else {
                    hideCalendar();
                }
            }

            function hideCalendar() {
                document.getElementById("ats-eventCalendar").style.display = "none";
                document.querySelector(".ats-calendar-overlay").style.display = "none";
            }

            function updateCalendar() {
                const monthSelect = document.getElementById("ats-calendar__month");
                const yearSelect = document.getElementById("ats-calendar__year");
                const datesContainer = document.getElementById("ats-calendarDates");

                const month = parseInt(monthSelect.value);
                const year = parseInt(yearSelect.value);

                // Clear existing dates
                datesContainer.innerHTML = "";

                //get first day of month and number of days
                const firstDay = new Date(year, month, 1);
                const lastDay = new Date(year, month + 1, 0);
                const startDate = new Date(firstDay);
                startDate.setDate(startDate.getDate() - firstDay.getDay()); // Start from Sunday

                //generate calendar dates
                for (let i = 0; i < 42; i++) { // 6 weeks * 7 days
                    const currentDate = new Date(startDate);
                    currentDate.setDate(startDate.getDate() + i);

                    const isCurrentMonth = currentDate.getMonth() === month;
                    const dateStr = currentDate.toISOString().split("T")[0]; // YYYY-MM-DD format
                    const hasEvents = availableEventDates.includes(dateStr);

                    let classes = "ats-calendar__date";
                    if (!isCurrentMonth) {
                        classes += " ats-calendar__date--grey";
                    }
                    if (hasEvents) {
                        classes += " ats-calendar__date--has-events";
                    }
                    if (selectedDate === dateStr) {
                        classes += " ats-calendar__date--selected";
                    }

                    const dateDiv = document.createElement("div");
                    dateDiv.className = classes;
                    dateDiv.innerHTML = "<span>" + currentDate.getDate() + "</span>";

                    if (isCurrentMonth && hasEvents) {
                        dateDiv.style.cursor = "pointer";
                        dateDiv.onclick = function() {
                            selectDate(dateStr);
                        };
                    }

                    datesContainer.appendChild(dateDiv);
                }
            }

            function selectDate(dateStr) {
                selectedDate = dateStr;
                updateCalendar(); //refresh calendar to show selection
                filterEventsByDate(dateStr);
                hideCalendar();

                //update button appearance to show active date filter
                const calendarBtn = document.querySelector(".ats-calendar-container .ats_filter_toggle_btn");
                calendarBtn.classList.add("ats_filter_toggle_btn_active");

                //clear other filter selections
                document.querySelectorAll(".ats_filter_btn_active").forEach(btn => {
                    btn.classList.remove("ats_filter_btn_active");
                });

                //reset other filters to "All"
                document.querySelectorAll(".ats_filter_btn[data-filter=\'all\']").forEach(btn => {
                    btn.classList.add("ats_filter_btn_active");
                });
            }

            function clearDateFilter() {
                selectedDate = null;
                updateCalendar();

                //remove active state from calendar button
                const calendarBtn = document.querySelector(".ats-calendar-container .ats_filter_toggle_btn");
                calendarBtn.classList.remove("ats_filter_toggle_btn_active");

                //show all events
                filterEvents("all", "alphabet");
                hideCalendar();
            }

            function filterEventsByDate(dateStr) {
                const azView = document.getElementById("ats_event_list_AZView");
                const dateView = document.getElementById("ats_event_list_dateView");
                const isAZView = azView.style.display !== "none";

                if (isAZView) {
                    //filter A-Z view events by date
                    const eventItems = document.querySelectorAll(".ats_event_list_event_item");
                    eventItems.forEach(item => {
                        const itemDates = item.getAttribute("data-dates");
                        const shouldShow = itemDates && itemDates.split(",").includes(dateStr);
                        item.style.display = shouldShow ? "block" : "none";
                    });
                } else {
                    //filter timeline view - show only the selected date
                    const timelineDays = document.querySelectorAll(".ats_timeline_day");
                    timelineDays.forEach(day => {
                        const dayDate = day.getAttribute("data-date");
                        day.style.display = (dayDate === dateStr) ? "block" : "none";
                    });
                }
            }

            function toggleFilter(filterType) {
                const alphabetContainer = document.querySelector(".ats_alphabet_filter");
                const genreContainer = document.querySelector(".ats_genre_filter");
                const toggleBtns = document.querySelectorAll(".ats_filter_toggle_btn");

                const isSameFilter = currentVisibleFilter === filterType;

                // If clicking the same filter thats already visible, hide all and reset
                if (isSameFilter) {
                    alphabetContainer.style.display = "none";
                    genreContainer.style.display = "none";
                    toggleBtns.forEach(btn => btn.classList.remove("ats_filter_toggle_btn_active"));
                    currentVisibleFilter = null;
                    return;
                }

                //else, show the selected filter and update active button
                alphabetContainer.style.display = "none";
                genreContainer.style.display = "none";
                toggleBtns.forEach(btn => btn.classList.remove("ats_filter_toggle_btn_active"));

                if (filterType === "alphabet") {
                    alphabetContainer.style.display = "block";
                    toggleBtns[0].classList.add("ats_filter_toggle_btn_active");
                } else if (filterType === "genre") {
                    genreContainer.style.display = "block";
                    toggleBtns[1].classList.add("ats_filter_toggle_btn_active");
                }

                currentVisibleFilter = filterType;
            }

            function filterEvents(filter, filterType) {
                // Clear date filter when using other filters
                if (filterType !== "date") {
                    selectedDate = null;
                    document.querySelector(".ats-calendar-container .ats_filter_toggle_btn").classList.remove("ats_filter_toggle_btn_active");
                }

                const azView = document.getElementById("ats_event_list_AZView");
                const dateView = document.getElementById("ats_event_list_dateView");
                const isAZView = azView.style.display !== "none";

                if (isAZView) {
                    const eventItems = document.querySelectorAll(".ats_event_list_event_item");
                    eventItems.forEach(item => {
                        let shouldShow = false;

                        if (filter === "all") {
                            shouldShow = true;
                        } else if (filterType === "alphabet") {
                            const itemLetter = item.getAttribute("data-letter");
                            shouldShow = itemLetter === filter;
                        } else if (filterType === "genre") {
                            const itemGenres = item.getAttribute("data-genres");
                            shouldShow = itemGenres && itemGenres.split(",").includes(filter);
                        }

                        item.style.display = shouldShow ? "block" : "none";
                    });
                } else {
                    //filter timeline view events and hide empty days
                    const timelineEvents = document.querySelectorAll(".ats_timeline_event");
                    const timelineDays = document.querySelectorAll(".ats_timeline_day");

                    timelineEvents.forEach(event => {
                        let shouldShow = false;

                        if (filter === "all") {
                            shouldShow = true;
                        } else if (filterType === "alphabet") {
                            const eventLetter = event.getAttribute("data-letter");
                            shouldShow = eventLetter === filter;
                        } else if (filterType === "genre") {
                            const eventGenres = event.getAttribute("data-genres");
                            shouldShow = eventGenres && eventGenres.split(",").includes(filter);
                        }

                        event.style.display = shouldShow ? "flex" : "none";
                    });

                    // Hide/show days based on whether they have visible events
                    timelineDays.forEach(day => {
                        const visibleEvents = day.querySelectorAll(".ats_timeline_event[style*=\\"flex\\"], .ats_timeline_event:not([style*=\\"none\\"])");
                        const hasVisibleEvents = Array.from(visibleEvents).some(event =>
                            event.style.display !== "none"
                        );
                        day.style.display = hasVisibleEvents ? "block" : "none";
                    });
                }
            }

            document.addEventListener("DOMContentLoaded", function() {
                const filterButtons = document.querySelectorAll(".ats_filter_btn:not(.ats_filter_btn_disabled)");

                filterButtons.forEach(button => {
                    button.addEventListener("click", function() {
                        const filter = this.getAttribute("data-filter");
                        const filterType = this.getAttribute("data-filter-type");

                        // Update active button within the same filter type
                        const sameTypeButtons = document.querySelectorAll(\'.ats_filter_btn[data-filter-type="\' + filterType + \'"]:not(.ats_filter_btn_disabled)\');
                        sameTypeButtons.forEach(btn => btn.classList.remove("ats_filter_btn_active"));
                        this.classList.add("ats_filter_btn_active");

                        filterEvents(filter, filterType);
                    });
                });

                document.getElementById("viewByAZbtn").addEventListener("click", function(){
                    document.getElementById("ats_event_list_AZView").style.display = "block";
                    document.getElementById("ats_event_list_dateView").style.display = "none";

                    let filterContainer = document.getElementsByClassName("ats_event_list_filter_toggle_container");
                    filterContainer[0].style.display = "block";

                    // Wrap clicked button in <b> tags and remove from other button
                    this.innerHTML = "<b>" + this.innerHTML.replace(/<\\/?b>/g, "") + "</b>";
                    document.getElementById("viewByDatebtn").innerHTML = document.getElementById("viewByDatebtn").innerHTML.replace(/<\\/?b>/g, "");

                    // Re-apply current filter to A-Z view
                    if (selectedDate) {
                        filterEventsByDate(selectedDate);
                    } else {
                        const activeFilterBtn = document.querySelector(".ats_filter_btn_active");
                        if (activeFilterBtn) {
                            const filter = activeFilterBtn.getAttribute("data-filter");
                            const filterType = activeFilterBtn.getAttribute("data-filter-type");
                            filterEvents(filter, filterType);
                        }
                    }
                });

                document.getElementById("viewByDatebtn").addEventListener("click", function(){
                    document.getElementById("ats_event_list_AZView").style.display = "none";
                    document.getElementById("ats_event_list_dateView").style.display = "block";

                    let filterContainer = document.getElementsByClassName("ats_event_list_filter_toggle_container");
                    filterContainer[0].style.display = "block"; // Keep filters visible for date view too

                    this.innerHTML = "<b>" + this.innerHTML.replace(/<\\/?b>/g, "") + "</b>";
                    document.getElementById("viewByAZbtn").innerHTML = document.getElementById("viewByAZbtn").innerHTML.replace(/<\\/?b>/g, "");

                    // Re-apply current filter to timeline view
                    if (selectedDate) {
                        filterEventsByDate(selectedDate);
                    } else {
                        const activeFilterBtn = document.querySelector(".ats_filter_btn_active");
                        if (activeFilterBtn) {
                            const filter = activeFilterBtn.getAttribute("data-filter");
                            const filterType = activeFilterBtn.getAttribute("data-filter-type");
                            filterEvents(filter, filterType);
                        }
                    }
                });
            });
            </script>';
        $listContent .= "</div>";
        return $listContent;
    }


    /*
    static function ats_shortcode_event_gridCB($atts)
    {
        // Set default shortcode attributes and merge with provided ones
        $atts = shortcode_atts([
            'posttype' => 'agile_post', // default to standard post type
            'itemsWide' => 3,
        ], $atts, 'ats_event_list');
        $postType = sanitize_key($atts['posttype']);
        $objPerRow = sanitize_key($atts['itemsWide']);

        $args = ['numberposts' => 99, 'post_type' => $postType, 'fields' => 'ids'];
        $posts = get_posts($args);
        $listContent = "<div class='ats-event-list' style='display: grid; grid-template-columns: repeat({$objPerRow}, 1fr); gap: 20px;'>";

        foreach ($posts as $post_id) {
            $title = get_the_title($post_id);
            $permalink = get_permalink($post_id);

            $thumb_id = get_post_thumbnail_id($post_id);
            $thumbnail = $thumb_id ? wp_get_attachment_image($thumb_id, 'thumbnail') : '';

            $firstEndDate = get_post_meta($post_id, "ATS_firstEndDate", true);
            $date = new DateTime($firstEndDate);
            $readableDate = $date->format('F j, Y \a\t g:i A');

            $listContent .= "
                            <div class='ats-event-item' style='border: 1px solid #ccc; padding: 10px; text-align: center;'>
                                <a href='{$permalink}'>
                                    {$thumbnail}
                                    <h3 style='margin-top: 10px;'>{$title}</h3>
                                </a>
                            <hr style='border: none; border-top: 2px solid #ccc; margin: 20px 0;'>
                            <span>
                                <svg width='12px' height='12px' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'>
                                <path d='M12 7V12L14.5 10.5M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z' stroke='#000000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/>
                                </svg>
                                {$readableDate}
                            </span>
                            </div>
                            ";
        }

        $listContent .= "</div>";
        return $listContent;
    }*/

    /**
     * Coming Soon Banner Shortcode
     * Displays an auto-scrolling banner of coming soon events
     */
    static function ats_shortcode_coming_soon_bannerCB($atts)
    {
        $postType = agile_tix_post_type::get_configured_post_type();
        
        $atts = shortcode_atts([
            'interval' => 8000, // Auto-scroll interval in milliseconds (default 8 seconds)
            'height' => 'auto', 
        ], $atts, 'ats_coming_soon_banner');
        
        $interval = absint($atts['interval']);
        $height = esc_attr($atts['height']);
        
        $args = [
            'post_type' => $postType,
            'posts_per_page' => -1,
            'meta_query' => [
                [
                    'key' => 'ATS_ComingSoonDate',
                    'compare' => 'EXISTS',
                ],
            ],
            'orderby' => 'meta_value',
            'meta_key' => 'ATS_ComingSoonDate',
            'order' => 'ASC',
        ];
        
        $posts = get_posts($args);
        
        if (empty($posts)) {
            return '<div class="ats-coming-soon-banner-empty">No coming soon events at this time.</div>';
        }
        
        // Generate unique ID for this banner instance
        $banner_id = 'ats-coming-soon-banner-' . uniqid();
        
        // Start building the banner HTML
        $height_style = $height === 'auto' ? 'height: auto;' : 'height: ' . $height . ';';
        $banner_html = '<div class="ats-coming-soon-banner-container" id="' . esc_attr($banner_id) . '" style="' . $height_style . ' position: relative; overflow: hidden;">';
        $slider_height_style = $height === 'auto' ? 'height: auto;' : 'height: 100%;';
        $banner_html .= '<div class="ats-coming-soon-banner-slider" style="display: flex; transition: transform 0.5s ease-in-out; ' . $slider_height_style . '">';
        
        foreach ($posts as $index => $post) {
            $post_id = $post->ID;
            $title = get_the_title($post_id);
            $permalink = get_permalink($post_id);
            $coming_soon_date = get_post_meta($post_id, 'ATS_ComingSoonDate', true);
            $thumb_id = get_post_thumbnail_id($post_id);
            $thumbnail = $thumb_id ? wp_get_attachment_image($thumb_id, 'large', false, ['class' => 'ats-coming-soon-banner-image']) : '';
            $excerpt = get_the_excerpt($post_id);
            $content = get_post_field('post_content', $post_id);
            $description = !empty($excerpt) ? $excerpt : wp_trim_words($content, 30, '...');
            
            // Format the coming soon date
            $formatted_date = '';
            if (!empty($coming_soon_date)) {
                try {
                    $date_obj = new DateTime($coming_soon_date);
                    $formatted_date = $date_obj->format('F j, Y');
                } catch (Exception $e) {
                    $formatted_date = $coming_soon_date;
                }
            }
            
            $slide_height_style = $height === 'auto' ? 'min-height: 300px;' : 'height: 100%;';
            $banner_html .= '<a href="' . esc_url($permalink) . '" class="ats-coming-soon-banner-slide" style="min-width: 100%; ' . $slide_height_style . ' display: block; position: relative; text-decoration: none; cursor: pointer;">';
            
            // Background image (full opacity) - takes full height
            if ($thumb_id) {
                $bg_image = wp_get_attachment_image_url($thumb_id, 'full');
                $bg_height_style = $height === 'auto' ? 'padding-bottom: 56.25%;' : 'height: 100%;';
                $banner_html .= '<div class="ats-coming-soon-banner-bg" style="position: absolute; top: 0; left: 0; width: 100%; ' . $bg_height_style . ' background-image: url(' . esc_url($bg_image) . '); background-size: contain; background-position: center; background-repeat: no-repeat; z-index: 1;"></div>';
            }
            
            // Text banner overlaid on top of image
            $banner_html .= '<div class="ats-coming-soon-banner-text-banner" style="position: absolute; top: 0; left: 0; width: 100%; padding: 8px 20px; text-align: center; z-index: 2; background-color: rgba(0, 0, 0, 0.4);">';
            
            $banner_html .= '<h2 class="ats-coming-soon-banner-title" style="font-size: 1.8em; margin: 0 0 4px 0; font-weight: bold; color: #fff;">';
            $banner_html .= esc_html($title);
            $banner_html .= '</h2>';
            
            if ($formatted_date) {
                $banner_html .= '<div class="ats-coming-soon-banner-date" style="font-size: 1em; margin: 0; color: #fff;">' . esc_html($formatted_date) . '</div>';
            }
            
            $banner_html .= '</div>'; // .ats-coming-soon-banner-text-banner
            
            $banner_html .= '</a>'; // .ats-coming-soon-banner-slide
        }
        
        $banner_html .= '</div>'; // .ats-coming-soon-banner-slider
        
        // Navigation dots wrapped in a bubble
        $banner_html .= '<div class="ats-coming-soon-banner-dots-container" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 0.3); padding: 8px 12px; border-radius: 20px; z-index: 3; pointer-events: auto;">';
        $banner_html .= '<div class="ats-coming-soon-banner-dots" style="display: flex; gap: 10px; align-items: center;">';
        foreach ($posts as $index => $post) {
            $active_class = $index === 0 ? ' active' : '';
            $banner_html .= '<button class="ats-coming-soon-banner-dot' . $active_class . '" data-slide="' . $index . '" style="width: 8px; height: 8px; padding: 0; border-radius: 50%; border: 1px solid rgba(255, 255, 255, 0.9); background-color: ' . ($index === 0 ? 'rgba(255, 255, 255, 0.9)' : 'transparent') . '; cursor: pointer; transition: background-color 0.3s; opacity: 0.9;"></button>';
        }
        $banner_html .= '</div>'; // .ats-coming-soon-banner-dots
        $banner_html .= '</div>'; // .ats-coming-soon-banner-dots-container
        
        $banner_html .= '</div>'; // .ats-coming-soon-banner-container
        
        $banner_html .= '<script>
        (function() {
            const banner = document.getElementById("' . esc_js($banner_id) . '");
            if (!banner) return;
            
            const slider = banner.querySelector(".ats-coming-soon-banner-slider");
            const slides = banner.querySelectorAll(".ats-coming-soon-banner-slide");
            const dots = banner.querySelectorAll(".ats-coming-soon-banner-dot");
            const totalSlides = slides.length;
            
            if (totalSlides === 0) return;
            
            let currentSlide = 0;
            let autoScrollInterval;
            
            function goToSlide(index) {
                if (index < 0) index = totalSlides - 1;
                if (index >= totalSlides) index = 0;
                
                currentSlide = index;
                slider.style.transform = "translateX(-" + (currentSlide * 100) + "%)";
                
                // Update dots
                dots.forEach((dot, i) => {
                    if (i === currentSlide) {
                        dot.classList.add("active");
                        dot.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
                    } else {
                        dot.classList.remove("active");
                        dot.style.backgroundColor = "transparent";
                    }
                });
            }
            
            function nextSlide() {
                goToSlide(currentSlide + 1);
            }
            
            function stopAutoScroll() {
                if (autoScrollInterval) {
                    clearInterval(autoScrollInterval);
                    autoScrollInterval = null;
                }
            }
            
            function startAutoScroll() {
                stopAutoScroll(); // Clear any existing interval first
                autoScrollInterval = setInterval(nextSlide, ' . $interval . ');
            }
            
            // Dot navigation
            dots.forEach((dot, index) => {
                dot.addEventListener("click", function() {
                    stopAutoScroll();
                    goToSlide(index);
                    startAutoScroll();
                });
            });
            
            // Pause on hover
            banner.addEventListener("mouseenter", stopAutoScroll);
            banner.addEventListener("mouseleave", startAutoScroll);
            
            // Start auto-scrolling
            startAutoScroll();
        })();
        </script>';
        
        // Add CSS
        $banner_html .= '<style>
        .ats-coming-soon-banner-container {
            width: 100%;
        }
        .ats-coming-soon-banner-slide {
            color: inherit;
            display: block;
        }
        .ats-coming-soon-banner-slide:hover {
            opacity: 0.95;
        }
        .ats-coming-soon-banner-dot {
            opacity: 0.9;
        }
        .ats-coming-soon-banner-dot:hover {
            background-color: rgba(255, 255, 255, 0.7) !important;
            opacity: 1;
        }
        </style>';
        
        return $banner_html;
    }

    /**
     * Now Showing Banner Shortcode
     * Displays an auto-scrolling banner of now showing events
     * Reuses the same structure as coming soon banner
     */
    static function ats_shortcode_now_showing_bannerCB($atts)
    {
        // Get configured post type
        $postType = agile_tix_post_type::get_configured_post_type();
        
        // Parse shortcode attributes
        $atts = shortcode_atts([
            'interval' => 8000, // Auto-scroll interval in milliseconds (default 8 seconds)
            'height' => '500px', 
        ], $atts, 'ats_now_showing_banner');
        
        $interval = absint($atts['interval']);
        $height = esc_attr($atts['height']);
        
        $args = [
            'post_type' => $postType,
            'posts_per_page' => -1,
            'meta_query' => [
                [
                    'key' => 'ATS_ComingSoonDate',
                    'compare' => 'NOT EXISTS',
                ],
            ],
            'orderby' => 'date',
            'order' => 'DESC',
        ];
        
        $posts = get_posts($args);
        
        if (empty($posts)) {
            return '<div class="ats-now-showing-banner-empty">No now showing events at this time.</div>';
        }
        
        
        $banner_id = 'ats-now-showing-banner-' . uniqid();
        
        $height_style = $height === 'auto' ? 'height: auto;' : 'height: ' . $height . ';';
        $banner_html = '<div class="ats-now-showing-banner-container" id="' . esc_attr($banner_id) . '" style="' . $height_style . ' position: relative; overflow: hidden;">';
        $slider_height_style = $height === 'auto' ? 'height: auto;' : 'height: 100%;';
        $banner_html .= '<div class="ats-now-showing-banner-slider" style="display: flex; transition: transform 0.5s ease-in-out; ' . $slider_height_style . '">';
        
        foreach ($posts as $index => $post) {
            $post_id = $post->ID;
            $title = get_the_title($post_id);
            $permalink = get_permalink($post_id);
            $thumb_id = get_post_thumbnail_id($post_id);
            $excerpt = get_the_excerpt($post_id);
            $content = get_post_field('post_content', $post_id);
            $description = !empty($excerpt) ? $excerpt : wp_trim_words($content, 30, '...');
            
            $first_end_date = get_post_meta($post_id, 'ATS_firstEndDate', true);
            $formatted_date = '';
            if (!empty($first_end_date)) {
                try {
                    $date_obj = new DateTime($first_end_date);
                    $formatted_date = $date_obj->format('F j, Y');
                } catch (Exception $e) {
                    $formatted_date = $first_end_date;
                }
            }
            
            $slide_height_style = $height === 'auto' ? 'min-height: 300px;' : 'height: 100%;';
            $banner_html .= '<a href="' . esc_url($permalink) . '" class="ats-now-showing-banner-slide" style="min-width: 100%; ' . $slide_height_style . ' display: block; position: relative; text-decoration: none; cursor: pointer;">';
            
            if ($thumb_id) {
                $bg_image = wp_get_attachment_image_url($thumb_id, 'full');
                $bg_height_style = $height === 'auto' ? 'padding-bottom: 56.25%;' : 'height: 100%;';
                $banner_html .= '<div class="ats-now-showing-banner-bg" style="position: absolute; top: 0; left: 0; width: 100%; ' . $bg_height_style . ' background-image: url(' . esc_url($bg_image) . '); background-size: contain; background-position: center; background-repeat: no-repeat; z-index: 1;"></div>';
            }
            

            $banner_html .= '<div class="ats-now-showing-banner-text-banner" style="position: absolute; top: 0; left: 0; width: 100%; padding: 8px 20px; text-align: center; z-index: 2; background-color: rgba(0, 0, 0, 0.4);">';
            
            $banner_html .= '<h2 class="ats-now-showing-banner-title" style="font-size: 1.8em; margin: 0 0 4px 0; font-weight: bold; color: #fff;">';
            $banner_html .= esc_html($title);
            $banner_html .= '</h2>';
            
            if ($formatted_date) {
                $banner_html .= '<div class="ats-now-showing-banner-date" style="font-size: 1em; margin: 0; color: #fff;">' . esc_html($formatted_date) . '</div>';
            }
            
            $banner_html .= '</div>'; // .ats-now-showing-banner-text-banner
            
            $banner_html .= '</a>'; // .ats-now-showing-banner-slide
        }
        
        $banner_html .= '</div>'; // .ats-now-showing-banner-slider
        
        // Navigation dots wrapped in a bubble
        $banner_html .= '<div class="ats-now-showing-banner-dots-container" style="position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); background-color: rgba(0, 0, 0, 0.3); padding: 8px 12px; border-radius: 20px; z-index: 3; pointer-events: auto;">';
        $banner_html .= '<div class="ats-now-showing-banner-dots" style="display: flex; gap: 10px; align-items: center;">';
        foreach ($posts as $index => $post) {
            $active_class = $index === 0 ? ' active' : '';
            $banner_html .= '<button class="ats-now-showing-banner-dot' . $active_class . '" data-slide="' . $index . '" style="width: 8px; height: 8px; padding: 0; border-radius: 50%; border: 1px solid rgba(255, 255, 255, 0.9); background-color: ' . ($index === 0 ? 'rgba(255, 255, 255, 0.9)' : 'transparent') . '; cursor: pointer; transition: background-color 0.3s; opacity: 0.9;"></button>';
        }
        $banner_html .= '</div>'; // .ats-now-showing-banner-dots
        $banner_html .= '</div>'; // .ats-now-showing-banner-dots-container
        
        $banner_html .= '</div>'; // .ats-now-showing-banner-container
        
        // Add JavaScript for auto-scrolling 
        $banner_html .= '<script>
        (function() {
            const banner = document.getElementById("' . esc_js($banner_id) . '");
            if (!banner) return;
            
            const slider = banner.querySelector(".ats-now-showing-banner-slider");
            const slides = banner.querySelectorAll(".ats-now-showing-banner-slide");
            const dots = banner.querySelectorAll(".ats-now-showing-banner-dot");
            const totalSlides = slides.length;
            
            if (totalSlides === 0) return;
            
            let currentSlide = 0;
            let autoScrollInterval;
            
            function goToSlide(index) {
                if (index < 0) index = totalSlides - 1;
                if (index >= totalSlides) index = 0;
                
                currentSlide = index;
                slider.style.transform = "translateX(-" + (currentSlide * 100) + "%)";
                
                // Update dots
                dots.forEach((dot, i) => {
                    if (i === currentSlide) {
                        dot.classList.add("active");
                        dot.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
                    } else {
                        dot.classList.remove("active");
                        dot.style.backgroundColor = "transparent";
                    }
                });
            }
            
            function nextSlide() {
                goToSlide(currentSlide + 1);
            }
            
            function stopAutoScroll() {
                if (autoScrollInterval) {
                    clearInterval(autoScrollInterval);
                    autoScrollInterval = null;
                }
            }
            
            function startAutoScroll() {
                stopAutoScroll(); // Clear any existing interval first
                autoScrollInterval = setInterval(nextSlide, ' . $interval . ');
            }
            
            // Dot navigation
            dots.forEach((dot, index) => {
                dot.addEventListener("click", function() {
                    stopAutoScroll();
                    goToSlide(index);
                    startAutoScroll();
                });
            });
            
            // Pause on hover
            banner.addEventListener("mouseenter", stopAutoScroll);
            banner.addEventListener("mouseleave", startAutoScroll);
            
            // Start auto-scrolling
            startAutoScroll();
        })();
        </script>';
        
        // Add CSS styles
        $banner_html .= '<style>
        .ats-now-showing-banner-container {
            width: 100%;
        }
        .ats-now-showing-banner-slide {
            color: inherit;
            display: block;
        }
        .ats-now-showing-banner-slide:hover {
            opacity: 0.95;
        }
        .ats-now-showing-banner-dot {
            opacity: 0.9;
        }
        .ats-now-showing-banner-dot:hover {
            background-color: rgba(255, 255, 255, 0.7) !important;
            opacity: 1;
        }
        </style>';
        
        return $banner_html;
    }

}

