<?php
if (!defined('ABSPATH')) {
    exit;
}

$ui_labels = isset($ui_labels) && is_array($ui_labels) ? $ui_labels : [];
$archive_title = sanitize_text_field((string) ($ui_labels['archive_title'] ?? __('View Events', 'nexdirectory')));
$archive_description = sanitize_text_field((string) ($ui_labels['archive_description'] ?? __('Discover official and community events around the world.', 'nexdirectory')));
$archive_kicker = sanitize_text_field((string) get_option('eep_event_hero_kicker_text', (string) ($ui_labels['hero_kicker_default'] ?? $this->get_white_label_brand_name())));

if ($archive_kicker === '') {
    $archive_kicker = $this->get_white_label_brand_name();
}

$plural_label = sanitize_text_field((string) ($ui_labels['plural'] ?? __('Events', 'nexdirectory')));
$type_label = sanitize_text_field((string) ($ui_labels['taxonomy_type_singular'] ?? __('Event Type', 'nexdirectory')));
$mode_label = sanitize_text_field((string) ($ui_labels['taxonomy_mode_singular'] ?? __('Event Mode', 'nexdirectory')));
$tag_label = sanitize_text_field((string) ($ui_labels['taxonomy_tag_singular'] ?? __('Tag', 'nexdirectory')));
$type_plural = sanitize_text_field((string) ($ui_labels['taxonomy_type_plural'] ?? __('Types', 'nexdirectory')));
$mode_plural = sanitize_text_field((string) ($ui_labels['taxonomy_mode_plural'] ?? __('Modes', 'nexdirectory')));
$tag_plural = sanitize_text_field((string) ($ui_labels['taxonomy_tag_plural'] ?? __('Tags', 'nexdirectory')));
$filter_search_label = sanitize_text_field((string) ($ui_labels['filter_search_label'] ?? __('Search', 'nexdirectory')));
$filter_price_label = sanitize_text_field((string) ($ui_labels['filter_price_label'] ?? __('Price Range', 'nexdirectory')));
$filter_price_any_label = sanitize_text_field((string) ($ui_labels['filter_price_any_label'] ?? __('Any Price', 'nexdirectory')));
$filter_city_label = sanitize_text_field((string) ($ui_labels['filter_city_label'] ?? __('City', 'nexdirectory')));
$filter_from_date_label = sanitize_text_field((string) ($ui_labels['filter_from_date_label'] ?? __('From Date', 'nexdirectory')));

$classification_labels = method_exists($this, 'get_classification_labels') ? (array) $this->get_classification_labels() : [];
$official_filter_label = sanitize_text_field((string) ($ui_labels['classification_label'] ?? __('Classification', 'nexdirectory')));
$official_option_label = sanitize_text_field((string) ($classification_labels['official'] ?? __('Official', 'nexdirectory')));
$unofficial_option_label = sanitize_text_field((string) ($classification_labels['unofficial'] ?? __('Unofficial', 'nexdirectory')));

$show_search_filter = isset($show_search_filter) ? (bool) $show_search_filter : true;
$show_type_filter = isset($show_type_filter) ? (bool) $show_type_filter : true;
$show_mode_filter = isset($show_mode_filter) ? (bool) $show_mode_filter : true;
$show_tag_filter = isset($show_tag_filter) ? (bool) $show_tag_filter : false;
$show_date_filter = isset($show_date_filter) ? (bool) $show_date_filter : true;
$show_price_filter = isset($show_price_filter) ? (bool) $show_price_filter : true;
$show_official_filter = isset($show_official_filter) ? (bool) $show_official_filter : true;

$resolve_filter_option_name = static function (array $options, $slug) {
    $slug = sanitize_key((string) $slug);
    if ($slug === '') {
        return '';
    }
    foreach ($options as $option) {
        if (!is_array($option)) {
            continue;
        }
        $option_slug = sanitize_key((string) ($option['slug'] ?? ''));
        if ($option_slug !== '' && $option_slug === $slug) {
            $name = sanitize_text_field((string) ($option['name'] ?? ''));
            if ($name !== '') {
                return $name;
            }
            break;
        }
    }
    return sanitize_text_field(ucwords(str_replace(['-', '_'], ' ', $slug)));
};

$active_hero_taxonomy_name = '';
$active_hero_filter_kind = '';
if (!empty($tag)) {
    $active_hero_taxonomy_name = $resolve_filter_option_name((array) ($filter_options['event_tag'] ?? []), $tag);
    $active_hero_filter_kind = 'tag';
} elseif (!empty($type)) {
    $active_hero_taxonomy_name = $resolve_filter_option_name((array) ($filter_options['event_type'] ?? []), $type);
    $active_hero_filter_kind = 'type';
} elseif (!empty($mode)) {
    $active_hero_taxonomy_name = $resolve_filter_option_name((array) ($filter_options['event_mode'] ?? []), $mode);
    $active_hero_filter_kind = 'mode';
} elseif (!empty($price_range)) {
    $active_hero_taxonomy_name = $resolve_filter_option_name((array) ($filter_options['event_price'] ?? []), $price_range);
    $active_hero_filter_kind = 'price';
}

if ($active_hero_taxonomy_name !== '') {
    $archive_title = trim($active_hero_taxonomy_name . ' ' . $plural_label);
    if ($active_hero_filter_kind === 'tag') {
        $archive_description = sprintf(
            __('Showing %1$s tagged as %2$s.', 'nexdirectory'),
            strtolower($plural_label),
            $active_hero_taxonomy_name
        );
    } elseif ($active_hero_filter_kind === 'type') {
        $archive_description = sprintf(
            __('Showing %1$s in the %2$s category.', 'nexdirectory'),
            strtolower($plural_label),
            $active_hero_taxonomy_name
        );
    } elseif ($active_hero_filter_kind === 'mode') {
        $archive_description = sprintf(
            __('Showing %1$s in %2$s mode.', 'nexdirectory'),
            strtolower($plural_label),
            $active_hero_taxonomy_name
        );
    } elseif ($active_hero_filter_kind === 'price') {
        $archive_description = sprintf(
            __('Showing %1$s for the %2$s price range.', 'nexdirectory'),
            strtolower($plural_label),
            $active_hero_taxonomy_name
        );
    }
}

$archive_cols = isset($_GET['eep_cols']) ? absint((int) wp_unslash($_GET['eep_cols'])) : 3;
if (!in_array($archive_cols, [2, 3, 4], true)) {
    $archive_cols = 3;
}

$archive_page_id = absint((int) get_queried_object_id());
$archive_featured_hero = '';
if ($archive_page_id > 0 && has_post_thumbnail($archive_page_id)) {
    $archive_featured_candidate = get_the_post_thumbnail_url($archive_page_id, 'full');
    if (is_string($archive_featured_candidate) && $archive_featured_candidate !== '') {
        $archive_featured_hero = esc_url($archive_featured_candidate);
    }
}
$archive_fallback_hero = esc_url((string) get_option('eep_style_fallback_hero_url', ''));
$archive_banner_hero = $archive_featured_hero !== '' ? $archive_featured_hero : $archive_fallback_hero;
$archive_banner_has_image = $archive_banner_hero !== '';
$archive_hero_img_src = $archive_banner_has_image
    ? $archive_banner_hero
    : 'https://images.unsplash.com/photo-1480714378408-67cf0d13bc1b?q=80&w=2070&auto=format&fit=crop';
?>

<style>
    @keyframes eepFadeIn {
        from { opacity: 0; transform: translateY(15px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .eep-animate-fade {
        animation: eepFadeIn 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards;
    }
    #eep-archive-results[data-eep-cols] .eep-grid {
        display: grid !important;
        grid-template-columns: minmax(0, 1fr) !important;
        gap: 1.25rem !important;
        align-items: stretch;
    }
    #eep-archive-results[data-eep-cols] .eep-grid > * {
        min-width: 0;
    }
    #eep-archive-results .eep-empty-state {
        grid-column: 1 / -1;
    }
    @media (min-width: 768px) {
        #eep-archive-results[data-eep-cols="2"] .eep-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
        }
        #eep-archive-results[data-eep-cols="3"] .eep-grid {
            grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
        }
        #eep-archive-results[data-eep-cols="4"] .eep-grid {
            grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
        }
    }
    .eep-archive-page .eep-archive-filter-form label.block {
        font-size: 11px !important;
        font-weight: 600 !important;
        line-height: 1.2 !important;
    }
    .eep-archive-page .eep-archive-filter-form :is(input[type="text"], input[type="date"], select, button) {
        font-size: 13px !important;
    }
    .eep-archive-page .eep-archive-filter-form :is(button[type="submit"], .eep-archive-clear-btn) {
        font-size: 13px !important;
        font-weight: 600 !important;
        letter-spacing: 0 !important;
    }
    .eep-archive-page .eep-archive-filters-toggle {
        font-size: 13px !important;
        font-weight: 600 !important;
    }
</style>

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 eep-animate-fade">
    <?php echo $this->render_notice(); ?>
</div>
<?php echo $this->render_platform_breadcrumbs($archive_title); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

<div class="eep-archive-page bg-gray-50 text-gray-800 font-sans antialiased selection:bg-brand-100 selection:text-brand-700 pb-20 md:pb-8 min-h-screen">
    
    <main class="max-w-7xl mx-auto px-0 sm:px-6 lg:px-8">
        
        <div class="eep-animate-fade relative sm:rounded-2xl overflow-hidden mb-6 sm:mb-8 shadow-sm group bg-gray-900 flex flex-col justify-end min-h-[40vh] sm:min-h-[350px]">
            
            <img src="<?php echo esc_url($archive_hero_img_src); ?>" alt="<?php echo esc_attr($archive_title); ?>" class="absolute inset-0 w-full h-full object-cover transition-transform duration-1000 sm:group-hover:scale-105 opacity-80 sm:opacity-100" data-eep-hero-parallax="1">
            
            <div class="absolute inset-0 bg-gradient-to-t from-gray-950 via-gray-900/70 to-transparent"></div>
            
            <div class="relative z-10 p-6 sm:p-8 lg:p-12 w-full mt-auto">
                <div class="flex flex-wrap items-center gap-2 mb-3">
                    <span class="inline-flex items-center px-3 py-1 rounded-full bg-brand-500/20 text-white text-[10px] sm:text-xs font-semibold uppercase tracking-wider backdrop-blur-sm border border-brand-500/30" style="color:#ffffff!important;">
                        <?php echo esc_html($archive_kicker); ?>
                    </span>
                    <span class="inline-flex items-center px-2.5 py-1 rounded-full bg-white/10 text-white text-[10px] sm:text-xs font-semibold uppercase tracking-wider backdrop-blur-sm border border-white/20 flex items-center gap-1.5">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                        <?php echo esc_html($plural_label); ?>
                    </span>
                </div>
                
                <h1 class="text-3xl sm:text-4xl md:text-5xl font-bold text-white mb-3 sm:mb-4 leading-tight tracking-tight drop-shadow-md">
                    <?php echo esc_html($archive_title); ?>
                </h1>
                
                <?php if ($archive_description !== '') : ?>
                    <p class="text-gray-300 text-base sm:text-lg max-w-2xl leading-relaxed">
                        <?php echo esc_html($archive_description); ?>
                    </p>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($show_type_filter) : ?>
            <div class="lg:hidden w-full overflow-x-auto no-scrollbar bg-gray-50 border-b border-gray-200 sticky top-16 z-30 eep-animate-fade" style="animation-delay: 0.1s;">
                <div class="flex gap-2 px-4 py-3 min-w-max">
                    <a href="<?php echo esc_url(get_permalink()); ?>" class="<?php echo empty($type) ? 'bg-brand-500 !text-white border border-brand-500 [&,*]:!text-white' : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'; ?> px-4 py-1.5 rounded-full text-sm font-medium shadow-sm" <?php echo empty($type) ? 'style="color:#fff!important;-webkit-text-fill-color:#fff!important;background:var(--eep-primary)!important;border-color:var(--eep-primary)!important;"' : ''; ?>>
                        <?php esc_html_e('All', 'nexdirectory'); ?>
                    </a>
                    <?php foreach ((array) ($filter_options['event_type'] ?? []) as $option) : ?>
                        <a href="<?php echo esc_url(eep_add_query_arg('event_type', $option['slug'], get_permalink())); ?>" class="<?php echo ($type === $option['slug']) ? 'bg-brand-500 !text-white border border-brand-500 [&,*]:!text-white' : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'; ?> px-4 py-1.5 rounded-full text-sm font-medium" <?php echo ($type === $option['slug']) ? 'style="color:#fff!important;-webkit-text-fill-color:#fff!important;background:var(--eep-primary)!important;border-color:var(--eep-primary)!important;"' : ''; ?>>
                            <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="eep-animate-fade py-6 flex flex-col lg:flex-row gap-8 items-start" style="animation-delay: 0.15s;" x-data="{ filtersSheetOpen: false }">
            
            <aside class="hidden lg:block w-72 flex-shrink-0 sticky top-24 bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                <div class="flex items-center gap-3 mb-6 pb-4 border-b border-gray-100">
                    <div class="w-10 h-10 bg-brand-50 rounded-xl flex items-center justify-center text-brand-500">
                        <i class="fa-solid fa-filter"></i>
                    </div>
                    <h2 class="font-bold text-lg text-gray-900"><?php echo esc_html(sprintf(__('Filter %s', 'nexdirectory'), $plural_label)); ?></h2>
                </div>
                
                <form method="get" class="space-y-5 eep-archive-filter-form">
                    <input type="hidden" name="paged" value="1">
                    <input type="hidden" name="organizer" value="<?php echo esc_attr((string) $organizer_id); ?>">
                    <input type="hidden" name="posts_per_page" value="<?php echo esc_attr((string) $posts_per_page); ?>">
                    <input type="hidden" name="eep_cols" class="eep-archive-cols-input" value="<?php echo esc_attr((string) $archive_cols); ?>">

                    <?php if ($show_search_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($filter_search_label); ?></label>
                            <input type="text" name="s" value="<?php echo esc_attr($search); ?>" placeholder="<?php esc_attr_e('Keywords...', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 outline-none">
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($show_type_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($type_label); ?></label>
                            <select name="event_type" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                                <option value=""><?php echo esc_html(sprintf(__('All %s', 'nexdirectory'), $type_plural)); ?></option>
                                <?php foreach ((array) ($filter_options['event_type'] ?? []) as $option) : ?>
                                    <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($type, (string) ($option['slug'] ?? '')); ?>>
                                        <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <?php if ($show_mode_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($mode_label); ?></label>
                            <select name="event_mode" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                                <option value=""><?php echo esc_html(sprintf(__('All %s', 'nexdirectory'), $mode_plural)); ?></option>
                                <?php foreach ((array) ($filter_options['event_mode'] ?? []) as $option) : ?>
                                    <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($mode, (string) ($option['slug'] ?? '')); ?>>
                                        <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <?php if ($show_tag_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($tag_label); ?></label>
                            <select name="event_tag" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                                <option value=""><?php echo esc_html(sprintf(__('All %s', 'nexdirectory'), $tag_plural)); ?></option>
                                <?php foreach ((array) ($filter_options['event_tag'] ?? []) as $option) : ?>
                                    <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($tag, (string) ($option['slug'] ?? '')); ?>>
                                        <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <?php if ($show_price_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($filter_price_label); ?></label>
                            <select name="event_price" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                                <option value=""><?php echo esc_html($filter_price_any_label); ?></option>
                                <?php foreach ((array) ($filter_options['event_price'] ?? []) as $option) : ?>
                                    <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($price_range, (string) ($option['slug'] ?? '')); ?>>
                                        <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>

                    <?php if ($show_date_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($filter_from_date_label); ?></label>
                            <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                        </div>
                    <?php endif; ?>

                    <?php if ($show_official_filter) : ?>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-2"><?php echo esc_html($official_filter_label); ?></label>
                            <select name="official" class="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm outline-none">
                                <option value=""><?php esc_html_e('All', 'nexdirectory'); ?></option>
                                <option value="1" <?php selected((string) $official, '1'); ?>><?php echo esc_html($official_option_label); ?></option>
                                <option value="0" <?php selected((string) $official, '0'); ?>><?php echo esc_html($unofficial_option_label); ?></option>
                            </select>
                        </div>
                    <?php endif; ?>

                    <button type="submit" class="w-full py-3 rounded-xl bg-brand-500 text-white font-medium hover:bg-brand-600 shadow-sm transition-all text-sm">
                        <?php esc_html_e('Apply Filters', 'nexdirectory'); ?>
                    </button>
                    
                    <?php if (!empty($has_active_filters)) : ?>
                        <a href="<?php echo esc_url(get_permalink()); ?>" class="eep-archive-clear-btn block w-full py-3 mt-2 rounded-xl border border-gray-200 bg-white text-gray-600 font-medium hover:bg-gray-50 text-center text-sm">
                            <?php esc_html_e('Clear all', 'nexdirectory'); ?>
                        </a>
                    <?php endif; ?>
                </form>
            </aside>

            <section class="flex-1 w-full min-w-0 bg-white sm:rounded-2xl shadow-sm border-y sm:border border-gray-100 overflow-hidden relative">
                
                <div class="h-1.5 w-full bg-gradient-to-r from-brand-400 to-brand-600"></div>
                
                <div class="p-4 sm:p-6 lg:p-8">
                    <div class="flex items-center justify-between mb-4 lg:mb-6 pb-4 border-b border-gray-100">
                        <p class="text-sm font-medium text-gray-500">
                            <span class="text-gray-900 font-bold"><?php echo isset($query->found_posts) ? esc_html($query->found_posts) : '0'; ?></span> <?php echo esc_html(strtolower($plural_label)); ?> found
                        </p>
                        <div class="hidden lg:flex items-center gap-4 text-sm">
                            <div class="flex items-center gap-2">
                                <span class="text-gray-500">Sort:</span>
                                <select class="bg-transparent font-bold text-gray-900 outline-none cursor-pointer" onchange="window.location.href=this.value;">
                                    <option value="<?php echo esc_url(eep_add_query_arg('orderby', 'meta_value', get_permalink())); ?>" <?php selected(isset($_GET['orderby']) ? $_GET['orderby'] : 'meta_value', 'meta_value'); ?>>Upcoming</option>
                                    <option value="<?php echo esc_url(eep_add_query_arg('orderby', 'date', get_permalink())); ?>" <?php selected(isset($_GET['orderby']) ? $_GET['orderby'] : '', 'date'); ?>>Newest Added</option>
                                </select>
                            </div>
                            <div class="flex items-center gap-2">
                                <label for="eep-archive-cols-desktop" class="text-gray-500"><?php esc_html_e('Columns:', 'nexdirectory'); ?></label>
                                <select id="eep-archive-cols-desktop" class="eep-archive-columns-select bg-transparent font-bold text-gray-900 outline-none cursor-pointer">
                                    <option value="2" <?php selected($archive_cols, 2); ?>>2</option>
                                    <option value="3" <?php selected($archive_cols, 3); ?>>3</option>
                                    <option value="4" <?php selected($archive_cols, 4); ?>>4</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <button @click="filtersSheetOpen = true" class="eep-archive-filters-toggle lg:hidden w-full mb-6 flex items-center justify-center gap-2 bg-brand-500 border border-brand-500 rounded-xl px-4 py-3 text-sm font-semibold !text-white shadow-sm transition-all active:scale-[0.98]" style="color:#fff!important;-webkit-text-fill-color:#fff!important;background:var(--eep-primary)!important;border-color:var(--eep-primary)!important;">
                        <i class="fa-solid fa-sliders text-white"></i> Toggle Filters
                    </button>

                    <div id="eep-archive-results" 
                         class="w-full [&_.pagination]:hidden [&_nav.navigation]:hidden [&_.page-numbers]:hidden"
                         data-eep-cols="<?php echo esc_attr((string) $archive_cols); ?>"
                         data-posts-per-page="<?php echo esc_attr((string) $posts_per_page); ?>" 
                         data-organizer="<?php echo esc_attr((string) $organizer_id); ?>">
                        
                        <?php 
                            // This outputs the legacy cards & pagination
                            echo $this->render_archive_results_markup($query, $paged, $filters, $organizer_id); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
                        ?>
                    </div>

                    <div class="w-full py-12 flex flex-col items-center justify-center text-gray-400" 
                         x-data="{ loading: false }" 
                         x-intersect="loading = true; /* The AJAX fetch logic binds here */ setTimeout(() => loading = false, 2000)">
                         
                        <i class="fa-solid fa-circle-notch fa-spin text-3xl text-brand-500 mb-3" x-show="loading" x-transition></i>
                        <span class="text-sm font-medium" x-show="loading">Loading more events...</span>
                        <span class="text-sm font-medium" x-show="!loading">Scroll down for more</span>
                    </div>
                </div>
            </section>

            <button @click="filtersSheetOpen = true" class="eep-archive-filters-toggle lg:hidden fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-brand-500 border border-brand-500 !text-white px-5 py-2.5 rounded-full shadow-lg text-sm font-medium flex items-center gap-2 z-40 active:scale-95 transition-transform" style="color:#fff!important;-webkit-text-fill-color:#fff!important;background:var(--eep-primary)!important;border-color:var(--eep-primary)!important;">
                <i class="fa-solid fa-sliders text-white"></i> Filter & Sort
            </button>

            <div x-cloak x-show="filtersSheetOpen" class="lg:hidden relative z-50" aria-labelledby="modal-title" role="dialog" aria-modal="true">
                <div x-show="filtersSheetOpen" x-transition.opacity class="fixed inset-0 bg-gray-900/60 backdrop-blur-sm transition-opacity"></div>

                <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
                    <div class="flex min-h-full items-end justify-center text-center">
                        <form method="get" x-show="filtersSheetOpen" 
                             x-transition:enter="transform transition ease-out duration-300" 
                             x-transition:enter-start="translate-y-full" 
                             x-transition:enter-end="translate-y-0" 
                             x-transition:leave="transform transition ease-in duration-200" 
                             x-transition:leave-start="translate-y-0" 
                             x-transition:leave-end="translate-y-full" 
                             @click.away="filtersSheetOpen = false"
                             class="eep-archive-filter-form relative w-full max-h-[90vh] bg-white rounded-t-3xl text-left shadow-xl overflow-hidden flex flex-col">
                            
                            <input type="hidden" name="paged" value="1">
                            <input type="hidden" name="organizer" value="<?php echo esc_attr((string) $organizer_id); ?>">
                            <input type="hidden" name="posts_per_page" value="<?php echo esc_attr((string) $posts_per_page); ?>">
                            <input type="hidden" name="eep_cols" class="eep-archive-cols-input" value="<?php echo esc_attr((string) $archive_cols); ?>">

                            <div class="bg-white px-4 py-4 border-b border-gray-100 sticky top-0 z-10 flex items-center justify-between">
                                <a href="<?php echo esc_url(get_permalink()); ?>" class="eep-archive-clear-btn text-sm font-semibold text-gray-500 hover:text-gray-900">Clear all</a>
                                <h3 class="text-lg font-bold text-gray-900">Filters</h3>
                                <button type="button" @click="filtersSheetOpen = false" class="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center text-gray-600 hover:bg-gray-200 transition-colors">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                                        <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                                    </svg>
                                </button>
                            </div>

                            <div class="overflow-y-auto p-5 space-y-6 pb-24">
                                
                                <div>
                                    <label class="block text-base font-bold text-gray-900 mb-3">Sort By</label>
                                    <div class="grid grid-cols-2 gap-3">
                                        <label class="cursor-pointer">
                                            <input type="radio" name="orderby" value="meta_value" class="peer hidden" <?php checked(isset($_GET['orderby']) ? $_GET['orderby'] : 'meta_value', 'meta_value'); ?>>
                                            <div class="py-3 border-2 border-gray-200 bg-white text-gray-600 rounded-xl font-semibold text-sm text-center peer-checked:border-brand-500 peer-checked:bg-brand-50 peer-checked:text-brand-600">Upcoming</div>
                                        </label>
                                        <label class="cursor-pointer">
                                            <input type="radio" name="orderby" value="date" class="peer hidden" <?php checked(isset($_GET['orderby']) ? $_GET['orderby'] : '', 'date'); ?>>
                                            <div class="py-3 border-2 border-gray-200 bg-white text-gray-600 rounded-xl font-semibold text-sm text-center peer-checked:border-brand-500 peer-checked:bg-brand-50 peer-checked:text-brand-600">Newest Added</div>
                                        </label>
                                    </div>
                                </div>

                                <?php if ($show_search_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3">Search Keywords</label>
                                        <div class="relative">
                                            <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"></i>
                                            <input type="text" name="s" value="<?php echo esc_attr($search); ?>" placeholder="Design, Tech, etc." class="w-full pl-11 pr-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none focus:border-brand-500">
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_type_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3">Event Type</label>
                                        <select name="event_type" class="w-full px-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none appearance-none cursor-pointer">
                                            <option value="">All Types</option>
                                            <?php foreach ((array) ($filter_options['event_type'] ?? []) as $option) : ?>
                                                <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($type, (string) ($option['slug'] ?? '')); ?>>
                                                    <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_mode_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3">Mode</label>
                                        <div class="flex flex-wrap gap-2">
                                            <label class="px-4 py-2 bg-gray-50 border border-gray-200 rounded-full text-sm font-medium flex items-center gap-2 cursor-pointer has-[:checked]:bg-brand-50 has-[:checked]:border-brand-500 has-[:checked]:text-brand-600">
                                                <input type="radio" name="event_mode" value="" class="hidden" <?php checked($mode, ''); ?>> All
                                            </label>
                                            <?php foreach ((array) ($filter_options['event_mode'] ?? []) as $option) : ?>
                                                <label class="px-4 py-2 bg-gray-50 border border-gray-200 rounded-full text-sm font-medium flex items-center gap-2 cursor-pointer has-[:checked]:bg-brand-50 has-[:checked]:border-brand-500 has-[:checked]:text-brand-600">
                                                    <input type="radio" name="event_mode" value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" class="hidden" <?php checked($mode, (string) ($option['slug'] ?? '')); ?>> <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                                </label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_tag_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3"><?php echo esc_html($tag_label); ?></label>
                                        <select name="event_tag" class="w-full px-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none appearance-none cursor-pointer">
                                            <option value=""><?php echo esc_html(sprintf(__('All %s', 'nexdirectory'), $tag_plural)); ?></option>
                                            <?php foreach ((array) ($filter_options['event_tag'] ?? []) as $option) : ?>
                                                <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($tag, (string) ($option['slug'] ?? '')); ?>>
                                                    <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_price_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3"><?php echo esc_html($filter_price_label); ?></label>
                                        <select name="event_price" class="w-full px-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none appearance-none cursor-pointer">
                                            <option value=""><?php echo esc_html($filter_price_any_label); ?></option>
                                            <?php foreach ((array) ($filter_options['event_price'] ?? []) as $option) : ?>
                                                <option value="<?php echo esc_attr((string) ($option['slug'] ?? '')); ?>" <?php selected($price_range, (string) ($option['slug'] ?? '')); ?>>
                                                    <?php echo esc_html((string) ($option['name'] ?? '')); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_date_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3"><?php echo esc_html($filter_from_date_label); ?></label>
                                        <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>" class="w-full px-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none focus:border-brand-500">
                                    </div>
                                <?php endif; ?>

                                <?php if ($show_official_filter) : ?>
                                    <div>
                                        <label class="block text-base font-bold text-gray-900 mb-3"><?php echo esc_html($official_filter_label); ?></label>
                                        <select name="official" class="w-full px-4 py-3.5 bg-gray-50 border border-gray-200 rounded-xl text-base outline-none appearance-none cursor-pointer">
                                            <option value=""><?php esc_html_e('All', 'nexdirectory'); ?></option>
                                            <option value="1" <?php selected((string) $official, '1'); ?>><?php echo esc_html($official_option_label); ?></option>
                                            <option value="0" <?php selected((string) $official, '0'); ?>><?php echo esc_html($unofficial_option_label); ?></option>
                                        </select>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="bg-white border-t border-gray-100 p-4 sticky bottom-0 z-10">
                                <button type="submit" class="w-full py-4 rounded-xl bg-brand-500 text-white font-bold text-base shadow-[0_4px_14px_0_rgba(var(--eep-primary-rgb),0.39)] hover:bg-brand-600 transition-colors">
                                    Show Results
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    (function () {
        var results = document.getElementById('eep-archive-results');
        if (!results) {
            return;
        }
        var allowed = ['2', '3', '4'];
        var storageKey = 'eep_archive_columns';
        var selects = Array.prototype.slice.call(document.querySelectorAll('.eep-archive-columns-select'));
        var colInputs = Array.prototype.slice.call(document.querySelectorAll('.eep-archive-cols-input'));
        var readStored = function () {
            try {
                return String(window.localStorage.getItem(storageKey) || '');
            } catch (err) {
                return '';
            }
        };
        var persist = function (value) {
            try {
                window.localStorage.setItem(storageKey, value);
            } catch (err) {}
        };
        var applyColumns = function (value) {
            var normalized = String(value || '').trim();
            if (allowed.indexOf(normalized) === -1) {
                normalized = '3';
            }
            results.setAttribute('data-eep-cols', normalized);
            selects.forEach(function (select) {
                if (select && select.value !== normalized) {
                    select.value = normalized;
                }
            });
            colInputs.forEach(function (input) {
                if (input && input.value !== normalized) {
                    input.value = normalized;
                }
            });
            persist(normalized);
        };

        var initial = String(results.getAttribute('data-eep-cols') || '').trim();
        if (allowed.indexOf(initial) === -1) {
            var stored = readStored();
            initial = allowed.indexOf(stored) >= 0 ? stored : '3';
        }
        applyColumns(initial);

        selects.forEach(function (select) {
            if (!select) {
                return;
            }
            select.addEventListener('change', function (event) {
                applyColumns(event && event.target ? event.target.value : '3');
            });
        });

        document.addEventListener('eep:archiveResultsUpdated', function () {
            var stored = readStored();
            if (allowed.indexOf(stored) >= 0) {
                applyColumns(stored);
            }
        });
    })();
</script>
