<?php

add_action( 'wp_enqueue_scripts', 'cc_scripts' );
function cc_scripts() {
	wp_enqueue_script( 'cc-bootstrap', get_template_directory_uri() . '/dist/js/bootstrap.min.js', array( 'jquery' ), '1.0.0', true );
	wp_enqueue_script( 'main', get_template_directory_uri() . '/main.js', array( 'jquery', 'cc-bootstrap' ), filemtime( get_template_directory() . '/main.js' ), true );
	wp_localize_script( 'main', 'PARAMS', array(
		'ajaxurl' => admin_url( 'admin-ajax.php' ),
	));
}

add_action( 'wp_enqueue_scripts', 'cc_styles' );
function cc_styles() {
	wp_enqueue_style( 'style', get_template_directory_uri() . '/style.css', array(), filemtime( get_template_directory() . '/style.css' ) );
}

// add_filter( 'show_admin_bar', '__return_false' );

add_action( 'after_setup_theme', 'cc_theme_add_supports' );
function cc_theme_add_supports() {
	add_theme_support( 'custom-logo' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'align-full' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'menus' );
}

add_action( 'init', 'cc_theme_setup' );
function cc_theme_setup() {
	register_nav_menu( 'theme_header', 'Header Navigation' );
}

// Prevent 404 on KDN Commons and Learning Exchanges pages with query parameters - AGGRESSIVE FIX
add_action('parse_request', 'kdn_force_page_recognition', 1);
function kdn_force_page_recognition($wp) {
    // Check if we're accessing kdn-commons, contribute-to-commons, or learning-exchanges
    if (strpos($_SERVER['REQUEST_URI'], '/kdn-commons') !== false ||
        strpos($_SERVER['REQUEST_URI'], '/contribute-to-commons') !== false ||
        strpos($_SERVER['REQUEST_URI'], '/learning-exchanges') !== false) {

        // Determine which page we're on
        if (strpos($_SERVER['REQUEST_URI'], '/kdn-commons') !== false) {
            $page = get_page_by_path('kdn-commons');
        } elseif (strpos($_SERVER['REQUEST_URI'], '/learning-exchanges') !== false) {
            $page = get_page_by_path('learning-exchanges');
        } else {
            $page = get_page_by_path('contribute-to-commons');
        }

        if ($page) {
            // Force WordPress to load this page
            $wp->query_vars['page_id'] = $page->ID;
            $wp->query_vars['pagename'] = $page->post_name;
            $wp->query_vars['error'] = '';
            unset($wp->query_vars['post_type']);
        }
    }
}

// Force 200 status on all protected pages
add_filter('status_header', 'kdn_force_200_status', 10, 2);
function kdn_force_200_status($status_header, $code) {
    if ((strpos($_SERVER['REQUEST_URI'], '/kdn-commons') !== false ||
         strpos($_SERVER['REQUEST_URI'], '/contribute-to-commons') !== false ||
         strpos($_SERVER['REQUEST_URI'], '/learning-exchanges') !== false) && $code == 404) {
        return str_replace('404', '200', $status_header);
    }
    return $status_header;
}

// Prevent WordPress from setting 404
add_action('wp', 'kdn_prevent_404_final', 1);
function kdn_prevent_404_final() {
    global $wp_query;
    if (strpos($_SERVER['REQUEST_URI'], '/kdn-commons') !== false ||
        strpos($_SERVER['REQUEST_URI'], '/contribute-to-commons') !== false ||
        strpos($_SERVER['REQUEST_URI'], '/learning-exchanges') !== false) {
        $wp_query->is_404 = false;
        $wp_query->is_page = true;
    }
}

// Include Ultimate Member AJAX Login Handler
if ( file_exists( get_template_directory() . '/um-ajax-login-handler.php' ) ) {
	require_once get_template_directory() . '/um-ajax-login-handler.php';
}


add_action('template_redirect', function () {

    // Allow Ultimate Member password endpoint
    if ( function_exists('UM') ) {
        // If this is the edit profile page AND password tab is active
        if ( um_is_core_page('edit') && UM()->query()->get_mode() === 'password' ) {
            return; // allow UM to show the password tab
        }
    }

    // Normal redirect for subscribers on edit profile page
    if (is_page('edit-profile') && is_user_logged_in()) {

        $user = wp_get_current_user();

        if (in_array('subscriber', (array) $user->roles, true)) {

            if (!isset($_GET['um_action']) || $_GET['um_action'] !== 'edit') {
                wp_redirect(add_query_arg('um_action', 'edit', get_permalink(get_page_by_path('edit-profile'))));
                exit;
            }

        }
    }

});



/**
 * Control redirect after Ultimate Member profile update
 * Using the official UM filter: um_update_profile_redirect_after
 */
add_filter('um_update_profile_redirect_after', function($url, $user_id, $args) {

    $current_user_id = get_current_user_id();

    // Admin editing another user - redirect to that user's profile
    if ($current_user_id !== $user_id) {
        return um_user_profile_url($user_id);
    }

    // Subscriber editing their own profile - redirect to edit-profile page
    $user = get_userdata($user_id);
    if ($user && in_array('subscriber', (array) $user->roles, true)) {
        return add_query_arg(
            'um_action',
            'edit',
            get_permalink(get_page_by_path('edit-profile'))
        );
    }

    // Default behavior for other roles
    return $url;

}, 10, 3);

// Create a custom shortcode for password change
// -------------------------------
// Custom Ultimate Member Password Change Form
// -------------------------------
add_shortcode('um_custom_password_form', function () {

    if (!is_user_logged_in()) {
        return '<p>You must be logged in to change your password.</p>';
    }

    $output = '';

    // Handle form submission
    if (isset($_POST['um_custom_pass_submit']) && isset($_POST['um_password_nonce'])) {

        // Verify nonce
        if (!wp_verify_nonce($_POST['um_password_nonce'], 'um_change_password')) {
            $output .= '<p style="color:red;">Security check failed. Please try again.</p>';
        } else {
            $user_id = get_current_user_id();
            $current_pass = $_POST['current_pass'] ?? '';
            $new_pass = $_POST['new_pass'] ?? '';
            $confirm_pass = $_POST['confirm_pass'] ?? '';

            $user = get_userdata($user_id);

            // Validate current password
            if (!wp_check_password($current_pass, $user->user_pass, $user_id)) {
                $output .= '<p style="color:red;">Current password is incorrect.</p>';
            }
            // Validate new passwords
            elseif ($new_pass !== $confirm_pass) {
                $output .= '<p style="color:red;">New passwords do not match.</p>';
            }
            elseif (strlen($new_pass) < 6) {
                $output .= '<p style="color:red;">Password must be at least 6 characters.</p>';
            }
            else {
                // Update password using WordPress native function
                wp_set_password($new_pass, $user_id);

                // Re-authenticate user after password change
                wp_set_auth_cookie($user_id);

                // Redirect to same page with success message
                wp_redirect(add_query_arg('password_changed', '1', remove_query_arg('password_changed')));
                exit;
            }
        }
    }

    // Success message
    if (isset($_GET['password_changed'])) {
        $output .= '<p style="color:green;">Password updated successfully!</p>';
    }

    // Form HTML
    $nonce_field = wp_nonce_field('um_change_password', 'um_password_nonce', true, false);

    $output .= '
        <form method="post" class="um um-edit um-password-form">

			' . $nonce_field . '


			<div class="um-field um-field-password">
				<div class="um-field-label">
					<label>Current Password<span style="color: #F27E70 !important; font-size: 10px !important; margin-left: 4px !important;">*</span></label>
				</div>
				<div class="um-field-area">
					<input type="password" name="current_pass" class="um-form-field" required>
				</div>
			</div>

			<div class="um-field um-field-password">
				<div class="um-field-label">
					<label>New Password<span style="color: #F27E70 !important; font-size: 10px !important; margin-left: 4px !important;">*</span></label>
				</div>
				<div class="um-field-area">
					<input type="password" name="new_pass" class="um-form-field" required>
				</div>
			</div>

			<div class="um-field um-field-password">
				<div class="um-field-label">
					<label>Confirm New Password<span style="color: #F27E70 !important; font-size: 10px !important; margin-left: 4px !important;">*</span></label>
				</div>
				<div class="um-field-area">
					<input type="password" name="confirm_pass" class="um-form-field" required>
				</div>
			</div>

			<div class="um-field um-field-submit">
				<button type="submit" name="um_custom_pass_submit" class="um-button">Update Password</button>
			</div>

		</form>

    ';

    return $output;
});

/**
 * Process KDN Commons form submission (separate function to handle redirects properly)
 */
function kdn_process_commons_submission() {

    // Verify nonce
    if (!wp_verify_nonce($_POST['kdn_commons_nonce'], 'kdn_commons_submission')) {
        return; // Security check failed - will show form again
    }

    // Get form data
    $resource_title = sanitize_text_field($_POST['resource_title'] ?? '');
    $description = sanitize_textarea_field($_POST['description'] ?? '');
    $author_names = sanitize_text_field($_POST['author_names'] ?? '');
    $year = sanitize_text_field($_POST['year'] ?? '');
    $language = sanitize_text_field($_POST['language'] ?? '');
    $topic = sanitize_text_field($_POST['topic'] ?? '');
    $region = sanitize_text_field($_POST['region'] ?? '');
    $resource_for = sanitize_text_field($_POST['resource_for'] ?? '');
    $status = sanitize_text_field($_POST['status'] ?? '');
    $resource_type = sanitize_text_field($_POST['resource_type'] ?? '');
    $resource_url = sanitize_url($_POST['resource_url'] ?? '');

    // Validate required fields
    if (empty($resource_title)) {
        return; // Will show form again with empty title error
    }

    // Create the post
    $post_data = array(
        'post_type'    => 'kdn_commons',
        'post_title'   => $resource_title,
        'post_status'  => 'publish', // Auto-publish
        'post_author'  => get_current_user_id() ?: 1,
    );

    $post_id = wp_insert_post($post_data);

    if (is_wp_error($post_id)) {
        return; // Post creation failed - will show form again
    }

    // Set ACF Fields
    if (function_exists('update_field')) {
        if (!empty($description)) {
            update_field('description', $description, $post_id);
        }
        if (!empty($author_names)) {
            update_field('author_name', $author_names, $post_id);
        }
        if (!empty($year)) {
            update_field('year', $year, $post_id);
        }
        if (!empty($status)) {
            update_field('status', $status, $post_id);
        }
        if (!empty($resource_for)) {
            update_field('resource_for', $resource_for, $post_id);
        }
        if (!empty($resource_url)) {
            update_field('resource_url', $resource_url, $post_id);
        }
    }

    // Set Taxonomies
    if (!empty($language)) {
        wp_set_object_terms($post_id, $language, 'language');
    }
    if (!empty($topic)) {
        wp_set_object_terms($post_id, $topic, 'topic');
    }
    if (!empty($region)) {
        wp_set_object_terms($post_id, $region, 'region');
    }
    if (!empty($resource_type)) {
        wp_set_object_terms($post_id, $resource_type, 'resource_type');
    }

    // Handle Resource Image (Featured Image)
    if (!empty($_FILES['resource_image']['name'])) {
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');

        $attachment_id = media_handle_upload('resource_image', $post_id);
        if (!is_wp_error($attachment_id)) {
            set_post_thumbnail($post_id, $attachment_id);
        }
    }

    // Handle Resource File Upload
    if (!empty($_FILES['upload_resource_file']['name']) && function_exists('update_field')) {
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');

        $file_id = media_handle_upload('upload_resource_file', $post_id);
        if (!is_wp_error($file_id)) {
            update_field('file', $file_id, $post_id);
        }
    }

    // Redirect to KDN Commons page after successful submission
    wp_redirect(home_url('/kdn-commons/?resource_submitted=1'));
    exit;
}

/**
 * Custom KDN Commons Resource Submission Form
 * Shortcode: [kdn_commons_form]
 */
add_shortcode('kdn_commons_form', 'kdn_commons_resource_form');

function kdn_commons_resource_form() {

    // Handle form submission FIRST (before any output)
    if (isset($_POST['kdn_commons_submit']) && isset($_POST['kdn_commons_nonce'])) {
        kdn_process_commons_submission();
        // If we reach here, submission failed - continue to show form with errors
    }

    // Check if user is logged in (optional - remove if you want public submissions)
    if (!is_user_logged_in()) {
        return '<p>Please <a href="' . esc_url(home_url('/login/')) . '" style="color: #0165A0;">login</a> to submit a resource.</p>';
    }

    $output = '';

    // Show error messages from failed submission
    if (isset($_POST['kdn_commons_submit'])) {
        if (!isset($_POST['kdn_commons_nonce']) || !wp_verify_nonce($_POST['kdn_commons_nonce'], 'kdn_commons_submission')) {
            $output .= '<div class="kdn-error">Security check failed. Please try again.</div>';
        } elseif (empty($_POST['resource_title'])) {
            $output .= '<div class="kdn-error">Resource Title is required.</div>';
        } else {
            $output .= '<div class="kdn-error">Failed to create resource. Please try again.</div>';
        }
    }

    // Get taxonomy terms for dropdowns
    $languages = get_terms(array('taxonomy' => 'language', 'hide_empty' => false));
    $topics = get_terms(array('taxonomy' => 'topic', 'hide_empty' => false));
    $regions = get_terms(array('taxonomy' => 'region', 'hide_empty' => false));
    $resource_types = get_terms(array('taxonomy' => 'resource_type', 'hide_empty' => false));

    // Get ACF field choices for Status and Resource For
    $status_choices = array();
    $resource_for_choices = array();

    if (function_exists('acf_get_field')) {
        // Get field by field name instead of field key
        $status_field = acf_get_field('status');
        if ($status_field && isset($status_field['choices'])) {
            $status_choices = $status_field['choices'];
        }

        $resource_for_field = acf_get_field('resource_for');
        if ($resource_for_field && isset($resource_for_field['choices'])) {
            $resource_for_choices = $resource_for_field['choices'];
        }
    }

    // Debug: Uncomment to see if terms are being fetched
    // error_log('Resource Types: ' . print_r($resource_types, true));

    $nonce_field = wp_nonce_field('kdn_commons_submission', 'kdn_commons_nonce', true, false);

    // Form HTML
    $output .= '
    <style>
        .kdn-commons-form { max-width: 800px; margin: 0 auto; }
        .kdn-form-group { margin-bottom: 20px; }
        .kdn-form-group label {
            display: block;
            margin-bottom: 8px;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-style: normal;
            font-size: 10px;
            line-height: 100%;
            letter-spacing: 0%;
            color: #B1B1B1;
        }
        .kdn-form-group label .required { color: #F27E70; font-size: 10px; margin-left: 4px; }
        .kdn-form-group input[type="text"],
        .kdn-form-group input[type="file"],
        .kdn-form-group textarea,
        .kdn-form-group select {
            width: 409px;
            max-width: 100%;
            height: 40px;
            border-radius: 6px;
            border: 1px solid #ddd;
            padding: 6px 10px;
            font-size: 14px;
            box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15);
        }
        .kdn-form-group textarea { min-height: 170px; height: auto; resize: vertical; }
        .kdn-form-group small {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-style: normal;
            font-size: 12px;
            line-height: 100%;
            color: #B1B1B1;
        }
        .kdn-submit-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            border: none;
            cursor: pointer;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .kdn-submit-btn:hover { background-color: #014d7a; }
        .kdn-form-submit-wrapper { text-align: right; }
        .kdn-error { background: #ffebee; border-left: 4px solid #f44336; color: #c62828; padding: 12px 15px; margin-bottom: 20px; }
        .kdn-success { background: #e8f5e9; border-left: 4px solid #4caf50; color: #2e7d32; padding: 12px 15px; margin-bottom: 20px; }
    </style>

    <form method="post" enctype="multipart/form-data" class="kdn-commons-form">
        ' . $nonce_field . '

        <div class="kdn-form-group">
            <label>Resource Title<span class="required">*</span></label>
            <input type="text" name="resource_title" required>
        </div>

        <div class="kdn-form-group">
            <label>Resource Preview</label>
            <input type="file" name="resource_image" accept="image/*">
            <small style="display: block; margin-top: 8px; color: #B1B1B1;">Max image size allowed 400kB</small>
        </div>

        <div class="kdn-form-group">
            <label>Description</label>
            <textarea name="description"></textarea>
            <small style="display: block; margin-top: 8px; color: #B1B1B1;">Keep the description within 200 words</small>
        </div>

        <div class="kdn-form-group">
            <label>Author Name(s)</label>
            <input type="text" name="author_names">
            <small style="display: block; margin-top: 8px; color: #B1B1B1; word-wrap: break-word;">Where possible, format as \'First Name Last Name(s)\'. For multiple authors, List all separated by commas or write one author and format as \'First Name Last Name, et al.\'</small>
        </div>

        <div class="kdn-form-group">
            <label>Year<span class="required">*</span></label>
            <select name="year" required>
                <option value="">Select Year</option>';

    // Generate years from current year back to 1900
    $current_year = date('Y');
    for ($year = $current_year; $year >= 1900; $year--) {
        $output .= '<option value="' . $year . '">' . $year . '</option>';
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Language</label>
            <select name="language">
                <option value="">Select Language</option>';

    if (!empty($languages) && !is_wp_error($languages)) {
        foreach ($languages as $term) {
            $output .= '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
        }
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Topic<span class="required">*</span></label>
            <select name="topic" required>
                <option value="">Select Topic</option>';

    if (!empty($topics) && !is_wp_error($topics)) {
        foreach ($topics as $term) {
            $output .= '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
        }
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Focus Region<span class="required">*</span></label>
            <select name="region" required>
                <option value="">Select Region</option>';

    if (!empty($regions) && !is_wp_error($regions)) {
        foreach ($regions as $term) {
            $output .= '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
        }
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Resource For<span class="required">*</span></label>
            <select name="resource_for" required>
                <option value="">Select</option>';

    if (!empty($resource_for_choices)) {
        foreach ($resource_for_choices as $value => $label) {
            $output .= '<option value="' . esc_attr($value) . '">' . esc_html($label) . '</option>';
        }
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Status<span class="required">*</span></label>
            <select name="status" required>
                <option value="">Select Status</option>';

    if (!empty($status_choices)) {
        foreach ($status_choices as $value => $label) {
            $output .= '<option value="' . esc_attr($value) . '">' . esc_html($label) . '</option>';
        }
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Resource Type<span class="required">*</span></label>
            <select name="resource_type" required>
                <option value="">Select Resource Type</option>';

    if (!empty($resource_types) && !is_wp_error($resource_types)) {
        foreach ($resource_types as $term) {
            $output .= '<option value="' . esc_attr($term->slug) . '">' . esc_html($term->name) . '</option>';
        }
    } else {
        // No terms found - show message
        $output .= '<option value="" disabled>No resource types available</option>';
    }

    $output .= '
            </select>
        </div>

        <div class="kdn-form-group">
            <label>Resource<span class="required">*</span></label>
            <input type="text" name="resource_url" placeholder="Resource URL">
            <p style="margin: 10px 0;">OR</p>
            <input type="file" name="upload_resource_file" accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.zip">
            <small style="display: block; margin-top: 8px; color: #B1B1B1;">Max file size allowed 1GB</small>
        </div>

        <div class="kdn-form-group kdn-form-submit-wrapper">
            <button type="submit" name="kdn_commons_submit" class="kdn-submit-btn">Publish Resource</button>
        </div>

    </form>
    ';

    return $output;
}

/**
 * KDN Commons Archive Display with Filters
 * Shortcode: [kdn_commons_archive]
 */
add_shortcode('kdn_commons_archive', 'kdn_commons_archive_display');

function kdn_commons_archive_display() {
    ob_start();

    // Get all taxonomy terms for filters
    $resource_types = get_terms(array('taxonomy' => 'resource_type', 'hide_empty' => false));
    $topics = get_terms(array('taxonomy' => 'topic', 'hide_empty' => false));
    $languages = get_terms(array('taxonomy' => 'language', 'hide_empty' => false));
    $regions = get_terms(array('taxonomy' => 'region', 'hide_empty' => false));

    // Get ACF field choices for Resource For filter
    $resource_for_choices = array();
    if (function_exists('acf_get_field')) {
        $resource_for_field = acf_get_field('resource_for');
        if ($resource_for_field && isset($resource_for_field['choices'])) {
            $resource_for_choices = $resource_for_field['choices'];
        }
    }

    // Get filter values from URL
    $keyword = isset($_GET['keyword']) ? sanitize_text_field($_GET['keyword']) : '';
    $selected_resource_type = isset($_GET['resource_type']) ? sanitize_text_field($_GET['resource_type']) : '';
    $selected_resource_for = isset($_GET['resource_for']) ? sanitize_text_field($_GET['resource_for']) : '';
    $selected_topic = isset($_GET['topic']) ? sanitize_text_field($_GET['topic']) : '';
    $selected_language = isset($_GET['language']) ? sanitize_text_field($_GET['language']) : '';
    $selected_year = isset($_GET['year']) ? sanitize_text_field($_GET['year']) : '';
    $selected_region = isset($_GET['region']) ? sanitize_text_field($_GET['region']) : '';

    // Pagination
    $posts_per_page = 6;
    $paged = isset($_GET['paged']) ? intval($_GET['paged']) : 1;

    // Build query args
    $args = array(
        'post_type' => 'kdn_commons',
        'post_status' => 'publish',
        'posts_per_page' => $posts_per_page,
        'paged' => $paged,
        'orderby' => 'date',
        'order' => 'DESC',
    );

    // Add keyword search
    if (!empty($keyword)) {
        $args['s'] = $keyword;
    }

    // Add taxonomy filters
    $tax_query = array('relation' => 'AND');

    if (!empty($selected_resource_type)) {
        $tax_query[] = array(
            'taxonomy' => 'resource_type',
            'field' => 'slug',
            'terms' => $selected_resource_type,
        );
    }

    if (!empty($selected_topic)) {
        $tax_query[] = array(
            'taxonomy' => 'topic',
            'field' => 'slug',
            'terms' => $selected_topic,
        );
    }

    if (!empty($selected_language)) {
        $tax_query[] = array(
            'taxonomy' => 'language',
            'field' => 'slug',
            'terms' => $selected_language,
        );
    }

    if (!empty($selected_region)) {
        $tax_query[] = array(
            'taxonomy' => 'region',
            'field' => 'slug',
            'terms' => $selected_region,
        );
    }

    if (count($tax_query) > 1) {
        $args['tax_query'] = $tax_query;
    }

    // Add ACF meta query for Resource For and Year
    $meta_query = array('relation' => 'AND');

    if (!empty($selected_resource_for)) {
        $meta_query[] = array(
            'key' => 'resource_for',
            'value' => $selected_resource_for,
            'compare' => '=',
        );
    }

    if (!empty($selected_year)) {
        $meta_query[] = array(
            'key' => 'year',
            'value' => $selected_year,
            'compare' => '=',
        );
    }

    if (count($meta_query) > 1) {
        $args['meta_query'] = $meta_query;
    }

    $query = new WP_Query($args);
    $total_pages = $query->max_num_pages;

    ?>
    <style>
        .kdn-commons-archive {
            max-width: 1030px;
            margin: 0 auto;
        }
        .kdn-archive-filters {
            margin-bottom: 40px;
        }
        .kdn-filter-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 20px;
        }
        .kdn-filter-group {
            display: flex;
            flex-direction: column;
        }
        .kdn-filter-group label {
            display: block;
            margin-bottom: 8px;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-style: normal;
            font-size: 10px;
            line-height: 100%;
            letter-spacing: 0%;
            color: #B1B1B1;
        }
        .kdn-filter-group select,
        .kdn-filter-group input[type="text"] {
            height: 40px;
            border-radius: 6px;
            border: 1px solid #ddd;
            padding: 6px 10px;
            font-size: 14px;
            background: white;
            box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15);
        }
        .kdn-filter-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .kdn-reset-btn {
            color: #B1B1B1;
            text-decoration: none;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-style: normal;
            font-size: 16px;
            line-height: 100%;
            letter-spacing: 0%;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .kdn-reset-btn:hover {
            color: #999;
        }
        .kdn-search-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            border: none;
            cursor: pointer;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .kdn-search-btn:hover {
            background-color: #014d7a;
        }
        .kdn-resources-grid {
            display: grid;
            grid-template-columns: repeat(3, 340px);
            gap: 30px;
            margin-bottom: 40px;
            justify-content: space-between;
        }
        .kdn-resource-card {
            background: transparent;
            border-radius: 10px;
            transition: background-color 0.3s ease;
            width: 340px;
            cursor: pointer;
            text-decoration: none;
            display: block;
            color: inherit;
            padding: 12px;
        }
        .kdn-resource-card:hover {
            background-color: #0165A029;
        }
        .kdn-resource-card-inner {
            width: 316px;
            margin: 0 auto;
        }
        .kdn-resource-image {
            width: 316px;
            height: 210px;
            object-fit: cover;
            background: #f0f0f0;
            border-radius: 10px !important;
        }
        .kdn-resource-content {
            padding-top: 16px;
            width: 316px;
        }
        .kdn-resource-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .kdn-resource-tag {
            border-radius: 20px;
            padding: 3px 7px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .kdn-tag-resource-type {
            background: #D97A66;
            color: #FFFFFF;
        }
        .kdn-tag-topic {
            background: transparent;
            border: 1px solid #2C2C2C;
            color: #2C2C2C;
        }
        .kdn-tag-language {
            background: #2C2C2C;
            color: #FFFFFF;
        }
        .kdn-resource-title {
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 16px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #333;
            margin: 0 0 10px 0;
        }
        .kdn-buttons-section {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 20px 0 40px;
        }
        .kdn-load-more-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            border: none;
            cursor: pointer;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .kdn-load-more-btn:hover {
            background-color: #014d7a;
        }
        .kdn-load-more-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .kdn-contribute-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            border: none;
            text-decoration: none;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
            display: inline-flex;
            align-items: center;
            cursor: pointer;
        }
        .kdn-contribute-btn:hover {
            background-color: #014d7a;
        }
        .kdn-no-results {
            text-align: center;
            padding: 60px 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .kdn-no-results h3,
        .kdn-no-results p {
            margin: 0;
        }
        .kdn-no-results svg {
            margin-bottom: 28px;
        }
        .kdn-no-results h3 {
            margin-bottom: 10px;
        }
        @media (max-width: 1030px) {
            .kdn-commons-archive {
                max-width: 100%;
                padding: 0 20px;
            }
            .kdn-resources-grid {
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                justify-content: center;
            }
            .kdn-resource-card {
                width: 100%;
            }
        }
        @media (max-width: 768px) {
            .kdn-filter-row {
                grid-template-columns: 1fr;
            }
            .kdn-resources-grid {
                grid-template-columns: 1fr;
            }
            .kdn-filter-accordion {
                display: block;
            }
            .kdn-filter-accordion-header {
                background: transparent;
                border-top: 1px solid #EBEBE6;
                border-bottom: 1px solid #EBEBE6;
                border-left: none;
                border-right: none;
                padding: 15px 0;
                cursor: pointer;
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                font-family: "Work Sans", sans-serif;
                font-weight: 500;
                font-size: 20px;
                line-height: 100%;
                letter-spacing: 0%;
                color: #2C2C2C;
            }
            .kdn-filter-accordion-icon {
                transition: transform 0.3s ease;
            }
            .kdn-filter-accordion-icon.active {
                transform: rotate(180deg);
            }
            .kdn-filter-accordion-content {
                max-height: 0;
                overflow: hidden;
                transition: max-height 0.3s ease;
            }
            .kdn-filter-accordion-content.active {
                max-height: 2000px;
            }
            .kdn-archive-filters {
                display: none;
            }
        }
        @media (min-width: 769px) {
            .kdn-filter-accordion {
                display: none;
            }
        }
    </style>

    <div class="kdn-commons-archive">
        <?php if (isset($_GET['resource_submitted'])) : ?>
            <div style="background: #e8f5e9; border-left: 4px solid #4caf50; color: #2e7d32; padding: 15px 20px; margin-bottom: 30px; border-radius: 4px;">
                <strong>Success!</strong> Your resource has been submitted and published successfully.
            </div>
        <?php endif; ?>

        <!-- Mobile Accordion Filter -->
        <div class="kdn-filter-accordion">
            <div class="kdn-filter-accordion-header" onclick="toggleKdnFilters()">
                <span>Search & Filters</span>
                <svg class="kdn-filter-accordion-icon" width="23" height="16" viewBox="0 0 23 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 1.04348C0 0.766731 0.110146 0.501318 0.306206 0.305628C0.502267 0.109937 0.768183 0 1.04545 0H21.9545C22.2318 0 22.4977 0.109937 22.6938 0.305628C22.8899 0.501318 23 0.766731 23 1.04348C23 1.32023 22.8899 1.58564 22.6938 1.78133C22.4977 1.97702 22.2318 2.08696 21.9545 2.08696H1.04545C0.768183 2.08696 0.502267 1.97702 0.306206 1.78133C0.110146 1.58564 0 1.32023 0 1.04348ZM3.48485 8C3.48485 7.72325 3.59499 7.45784 3.79105 7.26215C3.98712 7.06646 4.25303 6.95652 4.5303 6.95652H18.4697C18.747 6.95652 19.0129 7.06646 19.2089 7.26215C19.405 7.45784 19.5152 7.72325 19.5152 8C19.5152 8.27675 19.405 8.54216 19.2089 8.73785C19.0129 8.93354 18.747 9.04348 18.4697 9.04348H4.5303C4.25303 9.04348 3.98712 8.93354 3.79105 8.73785C3.59499 8.54216 3.48485 8.27675 3.48485 8ZM7.66667 14.9565C7.66667 14.6798 7.77681 14.4144 7.97287 14.2187C8.16893 14.023 8.43485 13.913 8.71212 13.913H14.2879C14.5652 13.913 14.8311 14.023 15.0271 14.2187C15.2232 14.4144 15.3333 14.6798 15.3333 14.9565C15.3333 15.2333 15.2232 15.4987 15.0271 15.6944C14.8311 15.8901 14.5652 16 14.2879 16H8.71212C8.43485 16 8.16893 15.8901 7.97287 15.6944C7.77681 15.4987 7.66667 15.2333 7.66667 14.9565Z" fill="#2C2C2C"/>
                </svg>
            </div>
            <div class="kdn-filter-accordion-content">
                <form method="get" action="<?php echo esc_url(home_url('/kdn-commons/')); ?>" class="kdn-archive-filters" style="display: block;">
                    <div class="kdn-filter-row">
                        <div class="kdn-filter-group">
                            <label>Keyword</label>
                            <input type="text" name="keyword" value="<?php echo esc_attr($keyword); ?>" placeholder="Search...">
                        </div>

                        <div class="kdn-filter-group">
                            <label>Resource Type</label>
                            <select name="resource_type">
                                <option value="">All Resource Types</option>
                                <?php if (!empty($resource_types)) : foreach ($resource_types as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_resource_type, $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <label>Resource For</label>
                            <select name="resource_for">
                                <option value="">All</option>
                                <?php if (!empty($resource_for_choices)) : ?>
                                    <?php foreach ($resource_for_choices as $value => $label) : ?>
                                        <option value="<?php echo esc_attr($value); ?>" <?php selected($selected_resource_for, $value); ?>>
                                            <?php echo esc_html($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <label>Topic</label>
                            <select name="topic">
                                <option value="">All Topics</option>
                                <?php if (!empty($topics)) : foreach ($topics as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_topic, $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <label>Language</label>
                            <select name="language">
                                <option value="">All Languages</option>
                                <?php if (!empty($languages)) : foreach ($languages as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_language, $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <label>Year</label>
                            <select name="year">
                                <option value="">All Years</option>
                                <?php
                                $current_year = date('Y');
                                for ($y = $current_year; $y >= 1900; $y--) :
                                ?>
                                    <option value="<?php echo $y; ?>" <?php selected($selected_year, $y); ?>><?php echo $y; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <label>Region</label>
                            <select name="region">
                                <option value="">All Regions</option>
                                <?php if (!empty($regions)) : foreach ($regions as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_region, $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>

                        <div class="kdn-filter-group">
                            <button type="submit" class="kdn-search-btn">Search</button>
                        </div>
                    </div>

                    <div class="kdn-filter-actions">
                        <a href="<?php echo esc_url(home_url('/kdn-commons/')); ?>" class="kdn-reset-btn">
                            <svg width="19" height="17" viewBox="0 0 19 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.05029 0.771484C9.43992 0.153309 10.9698 -0.00869072 12.4458 0.306641C13.9218 0.621984 15.2765 1.40051 16.3384 2.54102C17.3999 3.68135 18.1212 5.13316 18.4136 6.71191C18.7059 8.29071 18.5566 9.92724 17.9829 11.415C17.4091 12.9029 16.4365 14.1765 15.187 15.0732C13.9373 15.9701 12.4667 16.4502 10.9614 16.4502H10.811V14.8164H10.9614C12.1569 14.8164 13.3269 14.4354 14.3228 13.7207C15.3185 13.0059 16.0965 11.9887 16.5562 10.7969C17.0158 9.60485 17.1363 8.29242 16.9019 7.02637C16.6674 5.76028 16.0887 4.59825 15.2407 3.6875C14.3929 2.77698 13.3138 2.15879 12.1411 1.9082C10.9684 1.65766 9.75241 1.78555 8.64697 2.27734C7.54153 2.76915 6.59505 3.60309 5.92822 4.6748C5.26132 5.74682 4.90479 7.00864 4.90479 8.2998V12.0518L6.87939 9.93066L6.98877 9.81348L7.09912 9.93066L7.96729 10.8643L8.06299 10.9668L7.96729 11.0684L4.24365 15.0684L4.13428 15.1865L4.02393 15.0684L0.300293 11.0684L0.20459 10.9668L0.300293 10.8643L1.16846 9.93066L1.27881 9.81348L1.38818 9.93066L3.36279 12.0518V8.2998C3.36279 6.69026 3.80765 5.11622 4.64111 3.77637C5.47472 2.43638 6.66074 1.38969 8.05029 0.771484Z" fill="#B1B1B1" stroke="#B1B1B1" stroke-width="0.3"/>
                            </svg>
                            Reset Search
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Desktop Filter (original) -->
        <form method="get" action="<?php echo esc_url(home_url('/kdn-commons/')); ?>" class="kdn-archive-filters">
            <div class="kdn-filter-row">
                <div class="kdn-filter-group">
                    <label>Keyword</label>
                    <input type="text" name="keyword" value="<?php echo esc_attr($keyword); ?>" placeholder="Search...">
                </div>

                <div class="kdn-filter-group">
                    <label>Resource Type</label>
                    <select name="resource_type">
                        <option value="">All Resource Types</option>
                        <?php if (!empty($resource_types)) : foreach ($resource_types as $term) : ?>
                            <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_resource_type, $term->slug); ?>>
                                <?php echo esc_html($term->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>

                <div class="kdn-filter-group">
                    <label>Resource For</label>
                    <select name="resource_for">
                        <option value="">All</option>
                        <?php if (!empty($resource_for_choices)) : ?>
                            <?php foreach ($resource_for_choices as $value => $label) : ?>
                                <option value="<?php echo esc_attr($value); ?>" <?php selected($selected_resource_for, $value); ?>>
                                    <?php echo esc_html($label); ?>
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>

                <div class="kdn-filter-group">
                    <label>Topic</label>
                    <select name="topic">
                        <option value="">All Topics</option>
                        <?php if (!empty($topics)) : foreach ($topics as $term) : ?>
                            <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_topic, $term->slug); ?>>
                                <?php echo esc_html($term->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>
            </div>

            <div class="kdn-filter-row">
                <div class="kdn-filter-group">
                    <label>Language</label>
                    <select name="language">
                        <option value="">All Languages</option>
                        <?php if (!empty($languages)) : foreach ($languages as $term) : ?>
                            <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_language, $term->slug); ?>>
                                <?php echo esc_html($term->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>

                <div class="kdn-filter-group">
                    <label>Year</label>
                    <select name="year">
                        <option value="">All Years</option>
                        <?php
                        $current_year = date('Y');
                        for ($y = $current_year; $y >= 1900; $y--) :
                        ?>
                            <option value="<?php echo $y; ?>" <?php selected($selected_year, $y); ?>><?php echo $y; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>

                <div class="kdn-filter-group">
                    <label>Region</label>
                    <select name="region">
                        <option value="">All Regions</option>
                        <?php if (!empty($regions)) : foreach ($regions as $term) : ?>
                            <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_region, $term->slug); ?>>
                                <?php echo esc_html($term->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>

                <div class="kdn-filter-group" style="justify-content: flex-end;">
                    <button type="submit" class="kdn-search-btn">Search</button>
                </div>
            </div>

            <div class="kdn-filter-actions">
                <a href="<?php echo esc_url(home_url('/kdn-commons/')); ?>" class="kdn-reset-btn">
                    <svg width="19" height="17" viewBox="0 0 19 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8.05029 0.771484C9.43992 0.153309 10.9698 -0.00869072 12.4458 0.306641C13.9218 0.621984 15.2765 1.40051 16.3384 2.54102C17.3999 3.68135 18.1212 5.13316 18.4136 6.71191C18.7059 8.29071 18.5566 9.92724 17.9829 11.415C17.4091 12.9029 16.4365 14.1765 15.187 15.0732C13.9373 15.9701 12.4667 16.4502 10.9614 16.4502H10.811V14.8164H10.9614C12.1569 14.8164 13.3269 14.4354 14.3228 13.7207C15.3185 13.0059 16.0965 11.9887 16.5562 10.7969C17.0158 9.60485 17.1363 8.29242 16.9019 7.02637C16.6674 5.76028 16.0887 4.59825 15.2407 3.6875C14.3929 2.77698 13.3138 2.15879 12.1411 1.9082C10.9684 1.65766 9.75241 1.78555 8.64697 2.27734C7.54153 2.76915 6.59505 3.60309 5.92822 4.6748C5.26132 5.74682 4.90479 7.00864 4.90479 8.2998V12.0518L6.87939 9.93066L6.98877 9.81348L7.09912 9.93066L7.96729 10.8643L8.06299 10.9668L7.96729 11.0684L4.24365 15.0684L4.13428 15.1865L4.02393 15.0684L0.300293 11.0684L0.20459 10.9668L0.300293 10.8643L1.16846 9.93066L1.27881 9.81348L1.38818 9.93066L3.36279 12.0518V8.2998C3.36279 6.69026 3.80765 5.11622 4.64111 3.77637C5.47472 2.43638 6.66074 1.38969 8.05029 0.771484Z" fill="#B1B1B1" stroke="#B1B1B1" stroke-width="0.3"/>
                    </svg>
                    Reset Search
                </a>
            </div>
        </form>

        <?php if ($query->have_posts()) : ?>
            <div class="kdn-resources-grid">
                <?php while ($query->have_posts()) : $query->the_post();
                    $post_id = get_the_ID();
                    $resource_types_terms = get_the_terms($post_id, 'resource_type');
                    $topics_terms = get_the_terms($post_id, 'topic');
                ?>
                    <a href="<?php the_permalink(); ?>" class="kdn-resource-card">
                        <div class="kdn-resource-card-inner">
                            <?php if (has_post_thumbnail()) : ?>
                                <img src="<?php echo get_the_post_thumbnail_url($post_id, 'medium_large'); ?>" alt="<?php the_title(); ?>" class="kdn-resource-image">
                            <?php else : ?>
                                <div class="kdn-resource-image"></div>
                            <?php endif; ?>

                            <div class="kdn-resource-content">
                                <div class="kdn-resource-tags">
                                    <?php if ($resource_types_terms && !is_wp_error($resource_types_terms)) : ?>
                                        <?php foreach ($resource_types_terms as $term) : ?>
                                            <span class="kdn-resource-tag kdn-tag-resource-type"><?php echo esc_html($term->name); ?></span>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php if ($topics_terms && !is_wp_error($topics_terms)) : ?>
                                        <?php foreach ($topics_terms as $term) : ?>
                                            <span class="kdn-resource-tag kdn-tag-topic"><?php echo esc_html($term->name); ?></span>
                                        <?php endforeach; ?>
                                    <?php endif; ?>

                                    <?php
                                    $language_terms = get_the_terms($post_id, 'language');
                                    if ($language_terms && !is_wp_error($language_terms)) :
                                        foreach ($language_terms as $term) :
                                            // Only show language tag if it's not English
                                            if (strtolower($term->name) !== 'english') : ?>
                                                <span class="kdn-resource-tag kdn-tag-language"><?php echo esc_html($term->name); ?></span>
                                            <?php endif;
                                        endforeach;
                                    endif; ?>
                                </div>

                                <h3 class="kdn-resource-title">
                                    <?php the_title(); ?>
                                </h3>
                            </div>
                        </div>
                    </a>
                <?php endwhile; ?>
            </div>
        <?php else : ?>
            <div class="kdn-no-results">
                <svg width="155" height="145" viewBox="0 0 155 145" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M148 62.4316V67.4658C147.997 86.1736 140.568 104.114 127.347 117.342C114.126 130.569 96.1958 138 77.5 138H72.469C63.872 138.001 55.3589 136.308 47.4159 133.017C39.4729 129.726 32.2556 124.902 26.1761 118.819C20.0966 112.737 15.274 105.516 11.9837 97.5683C8.69349 89.6208 7 81.1025 7 72.5V65.3304C7.00293 49.8592 13.147 35.0227 24.0808 24.0839C35.0146 13.1452 49.8428 7 65.304 7C79.2218 7 92.5695 12.5324 102.411 22.38C112.252 32.2277 117.781 45.584 117.781 59.5106V64.3568C117.781 75.8694 113.211 86.9108 105.077 95.0525C96.9424 103.194 85.9093 107.77 74.404 107.773H72.469C63.1219 107.767 54.1594 104.049 47.55 97.435C40.9406 90.8214 37.2249 81.8531 37.219 72.5V67.4658C37.219 59.448 40.4013 51.7584 46.0661 46.0879C51.7308 40.4174 59.4143 37.2303 67.427 37.2274C78.5504 37.2274 87.573 46.2557 87.573 57.3863V60.263C87.573 69.8003 79.833 77.5453 70.3018 77.5453H67.427" stroke="#E5E5D3" stroke-width="14" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <h3 style="font-family: 'Work Sans', sans-serif; font-weight: 400; font-size: 30px; line-height: 100%; letter-spacing: 0%; text-align: center; color: #D9D9C3;">No Result Found</h3>
                <p style="font-family: 'Work Sans', sans-serif; font-weight: 400; font-size: 16px; line-height: 140%; letter-spacing: 0%; text-align: center; color: #D9D9C3;">Try different filters</p>
            </div>
        <?php endif; ?>

        <?php wp_reset_postdata(); ?>

        <div class="kdn-buttons-section">
            <?php if ($paged < $total_pages) : ?>
                <button class="kdn-load-more-btn" data-page="<?php echo $paged; ?>" data-max-pages="<?php echo $total_pages; ?>">
                    Load More
                </button>
            <?php endif; ?>

            <a href="<?php echo esc_url(home_url('/contribute-to-commons')); ?>" class="kdn-contribute-btn">Contribute</a>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('.kdn-load-more-btn').on('click', function() {
            var button = $(this);
            var currentPage = parseInt(button.data('page'));
            var maxPages = parseInt(button.data('max-pages'));
            var nextPage = currentPage + 1;

            // Disable button
            button.prop('disabled', true).text('Loading...');

            // Get all current filter values from URL
            var urlParams = new URLSearchParams(window.location.search);

            // AJAX request to load more posts
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    action: 'kdn_load_more_posts',
                    paged: nextPage,
                    keyword: urlParams.get('keyword') || '',
                    resource_type: urlParams.get('resource_type') || '',
                    resource_for: urlParams.get('resource_for') || '',
                    topic: urlParams.get('topic') || '',
                    language: urlParams.get('language') || '',
                    year: urlParams.get('year') || '',
                    region: urlParams.get('region') || ''
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        // Append new cards to grid
                        $('.kdn-resources-grid').append(response.data.html);

                        // Update button state
                        if (nextPage >= maxPages) {
                            button.remove(); // Remove button if no more pages
                        } else {
                            button.data('page', nextPage);
                            button.prop('disabled', false).text('Load More');
                        }
                    } else {
                        button.prop('disabled', false).text('Load More');
                        alert('No more posts to load.');
                    }
                },
                error: function() {
                    button.prop('disabled', false).text('Load More');
                    alert('Error loading more posts. Please try again.');
                }
            });
        });
    });
    </script>

    <script>
    function toggleKdnFilters() {
        var content = document.querySelector('.kdn-filter-accordion-content');
        var icon = document.querySelector('.kdn-filter-accordion-icon');
        content.classList.toggle('active');
        icon.classList.toggle('active');
    }
    </script>
    <?php

    return ob_get_clean();
}

// AJAX handler for Load More
add_action('wp_ajax_kdn_load_more_posts', 'kdn_load_more_posts_handler');
add_action('wp_ajax_nopriv_kdn_load_more_posts', 'kdn_load_more_posts_handler');

function kdn_load_more_posts_handler() {
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;
    $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : '';
    $selected_resource_type = isset($_POST['resource_type']) ? sanitize_text_field($_POST['resource_type']) : '';
    $selected_resource_for = isset($_POST['resource_for']) ? sanitize_text_field($_POST['resource_for']) : '';
    $selected_topic = isset($_POST['topic']) ? sanitize_text_field($_POST['topic']) : '';
    $selected_language = isset($_POST['language']) ? sanitize_text_field($_POST['language']) : '';
    $selected_year = isset($_POST['year']) ? sanitize_text_field($_POST['year']) : '';
    $selected_region = isset($_POST['region']) ? sanitize_text_field($_POST['region']) : '';

    // Build query args (same as main query)
    $args = array(
        'post_type' => 'kdn_commons',
        'post_status' => 'publish',
        'posts_per_page' => 6,
        'paged' => $paged,
        'orderby' => 'date',
        'order' => 'DESC',
    );

    // Add keyword search
    if (!empty($keyword)) {
        $args['s'] = $keyword;
    }

    // Add taxonomy filters
    $tax_query = array('relation' => 'AND');

    if (!empty($selected_resource_type)) {
        $tax_query[] = array(
            'taxonomy' => 'resource_type',
            'field' => 'slug',
            'terms' => $selected_resource_type,
        );
    }

    if (!empty($selected_topic)) {
        $tax_query[] = array(
            'taxonomy' => 'topic',
            'field' => 'slug',
            'terms' => $selected_topic,
        );
    }

    if (!empty($selected_language)) {
        $tax_query[] = array(
            'taxonomy' => 'language',
            'field' => 'slug',
            'terms' => $selected_language,
        );
    }

    if (!empty($selected_region)) {
        $tax_query[] = array(
            'taxonomy' => 'region',
            'field' => 'slug',
            'terms' => $selected_region,
        );
    }

    if (count($tax_query) > 1) {
        $args['tax_query'] = $tax_query;
    }

    // Add ACF meta query
    $meta_query = array('relation' => 'AND');

    if (!empty($selected_resource_for)) {
        $meta_query[] = array(
            'key' => 'resource_for',
            'value' => $selected_resource_for,
            'compare' => '=',
        );
    }

    if (!empty($selected_year)) {
        $meta_query[] = array(
            'key' => 'year',
            'value' => $selected_year,
            'compare' => '=',
        );
    }

    if (count($meta_query) > 1) {
        $args['meta_query'] = $meta_query;
    }

    $query = new WP_Query($args);

    ob_start();

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
            $resource_types_terms = get_the_terms($post_id, 'resource_type');
            $topics_terms = get_the_terms($post_id, 'topic');
            ?>
            <a href="<?php the_permalink(); ?>" class="kdn-resource-card">
                <div class="kdn-resource-card-inner">
                    <?php if (has_post_thumbnail()) : ?>
                        <img src="<?php echo get_the_post_thumbnail_url($post_id, 'medium_large'); ?>" alt="<?php the_title(); ?>" class="kdn-resource-image">
                    <?php else : ?>
                        <div class="kdn-resource-image"></div>
                    <?php endif; ?>

                    <div class="kdn-resource-content">
                        <div class="kdn-resource-tags">
                            <?php if ($resource_types_terms && !is_wp_error($resource_types_terms)) : ?>
                                <?php foreach ($resource_types_terms as $term) : ?>
                                    <span class="kdn-resource-tag kdn-tag-resource-type"><?php echo esc_html($term->name); ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>

                            <?php if ($topics_terms && !is_wp_error($topics_terms)) : ?>
                                <?php foreach ($topics_terms as $term) : ?>
                                    <span class="kdn-resource-tag kdn-tag-topic"><?php echo esc_html($term->name); ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>

                            <?php
                            $language_terms = get_the_terms($post_id, 'language');
                            if ($language_terms && !is_wp_error($language_terms)) :
                                foreach ($language_terms as $term) :
                                    // Only show language tag if it's not English
                                    if (strtolower($term->name) !== 'english') : ?>
                                        <span class="kdn-resource-tag kdn-tag-language"><?php echo esc_html($term->name); ?></span>
                                    <?php endif;
                                endforeach;
                            endif; ?>
                        </div>

                        <h3 class="kdn-resource-title">
                            <?php the_title(); ?>
                        </h3>
                    </div>
                </div>
            </a>
            <?php
        }
    }

    wp_reset_postdata();

    $html = ob_get_clean();

    wp_send_json_success(array('html' => $html));
}

/**
 * Elementor Form Handler for KDN Commons Resource Submission
 * Creates posts in kdn_commons post type with taxonomies and ACF fields
 */
add_action('elementor_pro/forms/new_record', 'handle_kdn_commons_form_submission', 10, 2);

function handle_kdn_commons_form_submission($record, $ajax_handler) {
    // Get the form name to identify our specific form
    $form_name = $record->get_form_settings('form_name');

    // Only process forms named "KDN Commons Resource Form" (you can change this)
    if ($form_name !== 'KDN Commons Resource Form') {
        return;
    }

    // Get submitted form data
    $raw_fields = $record->get('fields');
    $fields = [];
    foreach ($raw_fields as $id => $field) {
        $fields[$id] = $field['value'];
    }

    // Prepare post data
    $post_data = array(
        'post_type'    => 'kdn_commons',
        'post_title'   => sanitize_text_field($fields['resource_title'] ?? ''),
        'post_status'  => 'pending', // Set to 'publish' if you want auto-publish
        'post_author'  => get_current_user_id() ?: 1, // Use current user or admin
    );

    // Validate required field
    if (empty($post_data['post_title'])) {
        $ajax_handler->add_error_message('Resource Title is required.');
        return;
    }

    // Insert the post
    $post_id = wp_insert_post($post_data);

    if (is_wp_error($post_id)) {
        $ajax_handler->add_error_message('Failed to create resource: ' . $post_id->get_error_message());
        return;
    }

    // Set ACF Fields
    if (function_exists('update_field')) {
        // Description
        if (!empty($fields['description'])) {
            update_field('description', sanitize_textarea_field($fields['description']), $post_id);
        }

        // Author Name(s) - Fixed: ACF field is 'author_name' (singular)
        if (!empty($fields['author_names'])) {
            update_field('author_name', sanitize_text_field($fields['author_names']), $post_id);
        }

        // Resource For
        if (!empty($fields['resource_for'])) {
            update_field('resource_for', sanitize_text_field($fields['resource_for']), $post_id);
        }

        // Year
        if (!empty($fields['year'])) {
            update_field('year', sanitize_text_field($fields['year']), $post_id);
        }

        // Status
        if (!empty($fields['status'])) {
            update_field('status', sanitize_text_field($fields['status']), $post_id);
        }

        // Resource URL
        if (!empty($fields['resource_url'])) {
            update_field('resource_url', sanitize_url($fields['resource_url']), $post_id);
        }

        // Upload Resource File - Fixed: ACF field is 'file'
        if (!empty($fields['upload_resource_file'])) {
            // Elementor file upload returns file ID
            update_field('file', $fields['upload_resource_file'], $post_id);
        }
    }

    // Set Featured Image (Resource Image)
    if (!empty($fields['resource_image'])) {
        // Elementor file upload returns attachment ID
        set_post_thumbnail($post_id, $fields['resource_image']);
    }

    // Set Taxonomies
    // Language
    if (!empty($fields['language'])) {
        wp_set_object_terms($post_id, $fields['language'], 'language');
    }

    // Topic
    if (!empty($fields['topic'])) {
        wp_set_object_terms($post_id, $fields['topic'], 'topic');
    }

    // Region
    if (!empty($fields['region'])) {
        wp_set_object_terms($post_id, $fields['region'], 'region');
    }

    // Resource Type
    if (!empty($fields['resource_type'])) {
        wp_set_object_terms($post_id, $fields['resource_type'], 'resource_type');
    }

    // Optional: Redirect or show success message
    $ajax_handler->add_response_data('message', 'Resource submitted successfully! Post ID: ' . $post_id);
}

/**
 * KDN Commons Single Resource Display
 * Shortcode: [kdn_commons_single]
 * Displays resource details on single post page
 */
add_shortcode('kdn_commons_single', 'kdn_commons_single_display');

function kdn_commons_single_display() {
    global $post;

    // Check if we're on a single kdn_commons post
    if (!is_singular('kdn_commons') && !$post) {
        return '<p>This shortcode only works on KDN Commons single pages.</p>';
    }

    $post_id = $post->ID;

    // Get ACF fields
    $author_name = get_field('author_name', $post_id);
    $submitted_by = get_the_author_meta('display_name', $post->post_author);

    // Get year - handle different possible formats
    $year_raw = get_post_meta($post_id, 'year', true);
    // If it's a serialized ACF choice value, try to get the display value
    if (function_exists('acf_get_field')) {
        $year_field = acf_get_field('year');
        if ($year_field && isset($year_field['choices']) && isset($year_field['choices'][$year_raw])) {
            $year = $year_field['choices'][$year_raw];
        } else {
            $year = $year_raw;
        }
    } else {
        $year = $year_raw;
    }

    $resource_for = get_field('resource_for', $post_id);

    // Get taxonomy terms
    $language_terms = get_the_terms($post_id, 'language');
    $region_terms = get_the_terms($post_id, 'region');

    $language = ($language_terms && !is_wp_error($language_terms)) ? $language_terms[0]->name : '';
    $region = ($region_terms && !is_wp_error($region_terms)) ? $region_terms[0]->name : '';

    ob_start();
    ?>

    <style>
        .kdn-single-details {
            border-radius: 8px;
            max-width: 600px;
        }
        .kdn-detail-item {
            padding: 12px 12px 12px 0;
            border-bottom: 1px solid #EBEBE6;
        }
        .kdn-detail-item:last-child {
            border-bottom: none;
        }
        .kdn-detail-label {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-size: 12px;
            line-height: 140%;
            letter-spacing: 0.02em;
            text-transform: uppercase;
            color: #999999;
            margin-bottom: 4px;
        }
        .kdn-detail-value {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-size: 16px;
            line-height: 150%;
            color: #2C2C2C;
        }
    </style>

    <div class="kdn-single-details">
        <?php if ($author_name) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Author(s)</div>
                <div class="kdn-detail-value"><?php echo esc_html($author_name); ?></div>
            </div>
        <?php endif; ?>

        <?php if ($submitted_by) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Submitted By</div>
                <div class="kdn-detail-value"><?php echo esc_html($submitted_by); ?></div>
            </div>
        <?php endif; ?>

        <?php if ($year) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Resource Year</div>
                <div class="kdn-detail-value"><?php echo esc_html($year); ?></div>
            </div>
        <?php endif; ?>

        <?php if ($language) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Language</div>
                <div class="kdn-detail-value"><?php echo esc_html($language); ?></div>
            </div>
        <?php endif; ?>

        <?php if ($region) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Focus Region</div>
                <div class="kdn-detail-value"><?php echo esc_html($region); ?></div>
            </div>
        <?php endif; ?>

        <?php if ($resource_for) : ?>
            <div class="kdn-detail-item">
                <div class="kdn-detail-label">Resource For</div>
                <div class="kdn-detail-value"><?php echo esc_html($resource_for); ?></div>
            </div>
        <?php endif; ?>
    </div>

    <?php
    return ob_get_clean();
}

/**
 * KDN Commons Resource Tags Display
 * Shortcode: [kdn_commons_tags]
 */
add_shortcode('kdn_commons_tags', 'kdn_commons_tags_display');

function kdn_commons_tags_display() {
    global $post;

    // Only work on singular kdn_commons posts
    if (!is_singular('kdn_commons') || !$post) {
        return '';
    }

    $post_id = $post->ID;

    ob_start();
    ?>

    <style>
        .kdn-resource-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .kdn-resource-tag {
            border-radius: 20px;
            padding: 3px 7px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .kdn-tag-resource-type {
            background: #D97A66;
            color: #FFFFFF;
        }
        .kdn-tag-topic {
            background: transparent;
            border: 1px solid #2C2C2C;
            color: #2C2C2C;
        }
        .kdn-tag-language {
            background: #2C2C2C;
            color: #FFFFFF;
        }
    </style>

    <div class="kdn-resource-tags">
        <?php
        // Get Resource Type terms
        $resource_types_terms = get_the_terms($post_id, 'resource_type');
        if ($resource_types_terms && !is_wp_error($resource_types_terms)) :
            foreach ($resource_types_terms as $term) : ?>
                <span class="kdn-resource-tag kdn-tag-resource-type"><?php echo esc_html($term->name); ?></span>
            <?php endforeach;
        endif;

        // Get Topic terms
        $topics_terms = get_the_terms($post_id, 'topic');
        if ($topics_terms && !is_wp_error($topics_terms)) :
            foreach ($topics_terms as $term) : ?>
                <span class="kdn-resource-tag kdn-tag-topic"><?php echo esc_html($term->name); ?></span>
            <?php endforeach;
        endif;

        // Get Language terms (only show if not English)
        $language_terms = get_the_terms($post_id, 'language');
        if ($language_terms && !is_wp_error($language_terms)) :
            foreach ($language_terms as $term) :
                if (strtolower($term->name) !== 'english') : ?>
                    <span class="kdn-resource-tag kdn-tag-language"><?php echo esc_html($term->name); ?></span>
                <?php endif;
            endforeach;
        endif;
        ?>
    </div>

    <?php
    return ob_get_clean();
}

/**
 * KDN Commons View Resource Button
 * Shortcode: [kdn_commons_view_button]
 */
add_shortcode('kdn_commons_view_button', 'kdn_commons_view_button_display');

function kdn_commons_view_button_display() {
    global $post;

    // Only work on singular kdn_commons posts
    if (!is_singular('kdn_commons') || !$post) {
        return '';
    }

    $post_id = $post->ID;

    // Get resource URL (priority 1)
    $resource_url = get_field('resource_url', $post_id);

    // If no URL, get file field (priority 2)
    if (empty($resource_url)) {
        $file = get_field('file', $post_id);
        if ($file) {
            $resource_url = is_array($file) ? $file['url'] : $file;
        }
    }

    // If no resource available, don't show button
    if (empty($resource_url)) {
        return '';
    }

    ob_start();
    ?>

    <style>
        .kdn-view-resource-btn {
            display: inline-block;
            background-color: #0165A0;
            color: #FFFFFF;
            padding: 12px 24px;
            border-radius: 30px;
            text-decoration: none;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
            transition: background-color 0.3s ease;
        }
        .kdn-view-resource-btn:hover {
            background-color: #014d7a;
            color: #FFFFFF;
        }
    </style>

    <a href="<?php echo esc_url($resource_url); ?>" target="_blank" rel="noopener noreferrer" class="kdn-view-resource-btn">
        VIEW RESOURCE
    </a>

    <?php
    return ob_get_clean();
}

/**
 * KDN Commons Latest Posts Grid
 * Shortcode: [kdn_commons_latest_grid]
 * Displays latest 4 KDN Commons posts in custom grid layout
 */
add_shortcode('kdn_commons_latest_grid', 'kdn_commons_latest_grid_display');

function kdn_commons_latest_grid_display() {
    // Query latest 4 KDN Commons posts
    $args = array(
        'post_type' => 'kdn_commons',
        'post_status' => 'publish',
        'posts_per_page' => 4,
        'orderby' => 'date',
        'order' => 'DESC',
    );

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '<p>No resources found.</p>';
    }

    ob_start();
    ?>

    <style>
        .kdn-latest-grid {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Desktop Grid Layout */
        .kdn-grid-container {
            display: grid;
            grid-template-columns: 298px 595px;
            grid-template-rows: 459px 383px;
            gap: 17px;
            width: 910px;
            margin: 0 auto;
        }

        /* Position items in grid */
        .kdn-grid-item-1 {
            grid-column: 1 / 3;
            grid-row: 1;
            justify-self: start;
        }

        .kdn-grid-item-2 {
            grid-column: 1 / 3;
            grid-row: 1;
            justify-self: end;
        }

        .kdn-grid-item-3 {
            grid-column: 1;
            grid-row: 2;
        }

        .kdn-grid-item-4 {
            grid-column: 2;
            grid-row: 2;
        }

        /* Card styling */
        .kdn-grid-card {
            position: relative;
            overflow: hidden;
            border-radius: 10px;
            display: block;
            text-decoration: none;
            width: 100%;
            height: 100%;
        }

        .kdn-grid-card img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            display: block;
            transition: transform 0.3s ease;
        }

        .kdn-grid-card:hover img {
            transform: scale(1.05);
        }

        /* Hide mobile content on desktop */
        .kdn-grid-mobile-content {
            display: none;
        }

        /* Specific dimensions for each grid item */
        .kdn-grid-item-1 {
            width: 535px;
            height: 459px;
        }

        .kdn-grid-item-2 {
            width: 358px;
            height: 459px;
        }

        .kdn-grid-item-3 {
            width: 298px;
            height: 383px;
        }

        .kdn-grid-item-4 {
            width: 595px;
            height: 383px;
        }

        /* Hover overlay */
        .kdn-grid-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #0165A0E5;
            opacity: 0;
            transition: opacity 0.3s ease;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 30px;
            text-align: center;
        }

        .kdn-grid-card:hover .kdn-grid-overlay {
            opacity: 1;
        }

        .kdn-grid-overlay-tag {
            color: #FFFFFF;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-size: 14px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
            margin-bottom: 15px;
        }

        .kdn-grid-overlay-title {
            color: white;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 30px;
            line-height: 120%;
            letter-spacing: 0%;
            text-transform: capitalize;
            margin: 0 0 20px 0;
        }

        .kdn-grid-overlay-btn {
            background-color: transparent;
            color: #FFFFFF;
            padding: 12px 24px;
            border: 1px solid #FFFFFF;
            border-radius: 30px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 14px;
            line-height: 100%;
            text-transform: uppercase;
            text-decoration: none;
            display: inline-block;
            cursor: pointer;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        .kdn-grid-overlay-btn:hover {
            background-color: #FFFFFF;
            color: #0165A0;
        }

        /* Mobile Layout */
        @media (max-width: 768px) {
            .kdn-grid-container {
                display: flex;
                flex-direction: column;
                gap: 30px;
                width: 100%;
            }

            .kdn-grid-item-1,
            .kdn-grid-item-2,
            .kdn-grid-item-3,
            .kdn-grid-item-4 {
                width: 315px;
                height: auto;
                margin: 0 auto;
            }

            /* Remove hover effect on mobile */
            .kdn-grid-overlay {
                display: none;
            }

            /* Mobile card adjustments */
            .kdn-grid-card {
                display: flex;
                flex-direction: column;
            }

            .kdn-grid-card img {
                width: 315px;
                height: 271px;
                margin-bottom: 10px;
            }

            /* Show mobile content below image */
            .kdn-grid-mobile-content {
                display: flex;
                flex-direction: column;
                position: relative;
                gap: 10px;
                z-index: 1;
            }

            .kdn-grid-mobile-tag {
                color: #2C2C2C;
                font-family: "Work Sans", sans-serif;
                font-weight: 500;
                font-size: 10px;
                line-height: 140%;
                letter-spacing: 0%;
                text-transform: uppercase;
                margin: 0;
            }

            .kdn-grid-mobile-title {
                color: #2C2C2C;
                font-family: "Work Sans", sans-serif;
                font-weight: 600;
                font-size: 16px;
                line-height: 120%;
                letter-spacing: 0%;
                margin: 0;
            }

            .kdn-grid-overlay-btn {
                display: none;
            }
        }
    </style>

    <div class="kdn-latest-grid">
        <div class="kdn-grid-container">
            <?php
            $counter = 1;
            while ($query->have_posts()) :
                $query->the_post();
                $post_id = get_the_ID();
                $post_title = get_the_title();
                $post_url = get_permalink();
                $thumbnail_url = get_the_post_thumbnail_url($post_id, 'full');

                // Get resource type taxonomy
                $resource_types = get_the_terms($post_id, 'resource_type');
                $resource_type_name = ($resource_types && !is_wp_error($resource_types)) ? $resource_types[0]->name : '';

                // Get resource URL
                $resource_url = get_field('resource_url', $post_id);
                if (empty($resource_url)) {
                    $file = get_field('file', $post_id);
                    if ($file) {
                        $resource_url = is_array($file) ? $file['url'] : $file;
                    }
                }

                // Fallback image if no featured image
                if (!$thumbnail_url) {
                    $thumbnail_url = get_template_directory_uri() . '/assets/images/placeholder.jpg';
                }
            ?>
                <div class="kdn-grid-item-<?php echo $counter; ?>">
                    <a href="<?php echo esc_url($post_url); ?>" class="kdn-grid-card">
                        <img src="<?php echo esc_url($thumbnail_url); ?>" alt="<?php echo esc_attr($post_title); ?>">

                        <!-- Desktop hover overlay -->
                        <div class="kdn-grid-overlay">
                            <?php if ($resource_type_name) : ?>
                                <span class="kdn-grid-overlay-tag"><?php echo esc_html($resource_type_name); ?></span>
                            <?php endif; ?>
                            <h3 class="kdn-grid-overlay-title"><?php echo esc_html($post_title); ?></h3>
                            <span class="kdn-grid-overlay-btn" onclick="event.preventDefault(); event.stopPropagation(); window.location.href='<?php echo esc_url($post_url); ?>';">
                                VIEW RESOURCE
                            </span>
                        </div>

                        <!-- Mobile static content -->
                        <div class="kdn-grid-mobile-content">
                            <?php if ($resource_type_name) : ?>
                                <span class="kdn-grid-mobile-tag"><?php echo esc_html($resource_type_name); ?></span>
                            <?php endif; ?>
                            <h3 class="kdn-grid-mobile-title"><?php echo esc_html($post_title); ?></h3>
                        </div>
                    </a>
                </div>
            <?php
                $counter++;
            endwhile;
            wp_reset_postdata();
            ?>
        </div>
    </div>

    <?php
    return ob_get_clean();
}

/**
 * KDN Commons Explore Resources Button
 * Shortcode: [kdn_explore_resources]
 * Only shows if there are published kdn_commons posts
 */
add_shortcode('kdn_explore_resources', 'kdn_explore_resources_button');

function kdn_explore_resources_button() {
    // Check if there are any published kdn_commons posts
    $args = array(
        'post_type' => 'kdn_commons',
        'post_status' => 'publish',
        'posts_per_page' => 1,
    );

    $query = new WP_Query($args);

    // If no posts found, don't show button
    if (!$query->have_posts()) {
        wp_reset_postdata();
        return '';
    }

    wp_reset_postdata();

    // Get the KDN Commons page URL
    $kdn_commons_url = home_url('/kdn-commons/');

    ob_start();
    ?>

    <style>
        .kdn-explore-btn {
            display: inline-block;
            background-color: transparent;
            color: #0165A0;
            border: 1px solid #0165A0;
            border-radius: 30px;
            padding: 10px 30px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
            text-decoration: none;
            transition: background-color 0.3s ease, color 0.3s ease;
            cursor: pointer;
        }

        .kdn-explore-btn:hover {
            background-color: #0165A0;
            color: #FFFFFF;
        }
    </style>

    <a href="<?php echo esc_url($kdn_commons_url); ?>" class="kdn-explore-btn">
        Explore Resources
    </a>

    <?php
    return ob_get_clean();
}

/**
 * Helper function to convert YouTube URL to embed URL
 */
function learning_exchange_get_youtube_embed_url($url) {
    if (empty($url)) {
        return '';
    }

    // Extract video ID from various YouTube URL formats
    $video_id = '';

    // Handle youtu.be format
    if (preg_match('/youtu\.be\/([^\?&]+)/', $url, $matches)) {
        $video_id = $matches[1];
    }
    // Handle youtube.com/watch?v= format
    elseif (preg_match('/youtube\.com\/watch\?v=([^\?&]+)/', $url, $matches)) {
        $video_id = $matches[1];
    }
    // Handle youtube.com/embed/ format
    elseif (preg_match('/youtube\.com\/embed\/([^\?&]+)/', $url, $matches)) {
        $video_id = $matches[1];
    }
    // Handle v= parameter anywhere in URL
    elseif (preg_match('/[?&]v=([^\?&]+)/', $url, $matches)) {
        $video_id = $matches[1];
    }

    if ($video_id) {
        return 'https://www.youtube.com/embed/' . $video_id;
    }

    return '';
}

/**
 * Learning Exchange Archive Display with Filters
 * Shortcode: [learning_exchange_archive]
 */
add_shortcode('learning_exchange_archive', 'learning_exchange_archive_display');

function learning_exchange_archive_display() {
    ob_start();

    // Get taxonomy terms for filters
    $topics = get_terms(array('taxonomy' => 'topic', 'hide_empty' => false));

    // Get filter values from URL
    $keyword = isset($_GET['keyword']) ? sanitize_text_field($_GET['keyword']) : '';
    $selected_topic = isset($_GET['topic']) ? sanitize_text_field($_GET['topic']) : '';
    $selected_month = isset($_GET['month']) ? sanitize_text_field($_GET['month']) : '';
    $selected_year = isset($_GET['year']) ? sanitize_text_field($_GET['year']) : '';

    // Pagination
    $posts_per_page = 6;
    $paged = isset($_GET['paged']) ? intval($_GET['paged']) : 1;

    // Build query args
    $args = array(
        'post_type' => 'learning_exchanges',
        'post_status' => 'publish',
        'posts_per_page' => $posts_per_page,
        'paged' => $paged,
        'meta_key' => 'schedule_start_time',
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'meta_type' => 'DATETIME',
    );

    // Add keyword search
    if (!empty($keyword)) {
        $args['s'] = $keyword;
    }

    // Add taxonomy filters
    if (!empty($selected_topic)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'topic',
                'field' => 'slug',
                'terms' => $selected_topic,
            ),
        );
    }

    // Add date filters for month and year
    $meta_query = array('relation' => 'AND');

    // Always ensure schedule_start_time exists
    $meta_query[] = array(
        'key' => 'schedule_start_time',
        'compare' => 'EXISTS',
    );

    if (!empty($selected_month) || !empty($selected_year)) {

        if (!empty($selected_month) && !empty($selected_year)) {
            // Filter by specific month and year
            $start_date = $selected_year . '-' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '-01 00:00:00';
            $end_date = date('Y-m-t 23:59:59', strtotime($start_date));

            $meta_query[] = array(
                'key' => 'schedule_start_time',
                'value' => array($start_date, $end_date),
                'compare' => 'BETWEEN',
                'type' => 'DATETIME',
            );
        } elseif (!empty($selected_year)) {
            // Filter by year only
            $start_date = $selected_year . '-01-01 00:00:00';
            $end_date = $selected_year . '-12-31 23:59:59';

            $meta_query[] = array(
                'key' => 'schedule_start_time',
                'value' => array($start_date, $end_date),
                'compare' => 'BETWEEN',
                'type' => 'DATETIME',
            );
        }
    }

    // Always apply the meta_query (includes EXISTS check)
    if (!empty($meta_query)) {
        $args['meta_query'] = $meta_query;
    }

    $query = new WP_Query($args);
    $total_pages = $query->max_num_pages;

    ?>
    <style>
        .learning-exchange-archive {
            max-width: 1030px;
            margin: 0 auto;
        }
        .learning-exchange-filters {
            margin-bottom: 40px;
        }
        .learning-exchange-filter-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        .learning-exchange-filter-group {
            display: flex;
            flex-direction: column;
        }
        .learning-exchange-filter-group label {
            display: block;
            margin-bottom: 8px;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-style: normal;
            font-size: 10px;
            line-height: 100%;
            letter-spacing: 0%;
            color: #B1B1B1;
        }
        .learning-exchange-filter-group select,
        .learning-exchange-filter-group input[type="text"] {
            height: 40px;
            border-radius: 6px;
            border: 1px solid #ddd;
            padding: 6px 10px;
            font-size: 14px;
            background: white;
            box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15);
        }
        .learning-exchange-filter-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .learning-exchange-reset-btn {
            color: #B1B1B1;
            text-decoration: none;
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-style: normal;
            font-size: 16px;
            line-height: 100%;
            letter-spacing: 0%;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .learning-exchange-reset-btn:hover {
            color: #999;
        }
        .learning-exchange-search-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            width: 200px;
            border: none;
            cursor: pointer;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .learning-exchange-search-btn:hover {
            background-color: #014d7a;
        }
        .learning-exchange-grid {
            display: grid;
            grid-template-columns: repeat(3, 340px);
            gap: 30px;
            margin-bottom: 40px;
            justify-content: space-between;
        }
        .learning-exchange-card {
            background: transparent;
            border-radius: 10px;
            width: 340px;
            cursor: pointer;
            text-decoration: none;
            display: block;
            color: inherit;
            padding: 12px;
        }
        .learning-exchange-card-inner {
            width: 316px;
            margin: 0 auto;
        }
        .learning-exchange-video-wrapper {
            position: relative;
            width: 316px;
            height: 177px;
            border-radius: 10px;
            overflow: hidden;
            background: #f0f0f0;
        }
        .learning-exchange-image {
            width: 316px;
            height: 177px;
            object-fit: cover;
            background: #f0f0f0;
            border-radius: 10px !important;
        }
        .learning-exchange-content {
            padding-top: 16px;
            width: 316px;
        }
        .learning-exchange-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .learning-exchange-tag {
            border-radius: 20px;
            padding: 3px 7px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .learning-exchange-tag-upcoming {
            background: #FF6B6B;
            color: #FFFFFF;
        }
        .learning-exchange-tag-topic {
            background: transparent;
            border: 1px solid #2C2C2C;
            color: #2C2C2C;
        }
        .learning-exchange-datetime {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-style: normal;
            font-size: 14px;
            line-height: 140%;
            color: #E86A5A;
            margin: 0 0 10px 0;
        }
        .learning-exchange-title {
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 16px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #333;
            margin: 0 0 10px 0;
        }
        .learning-exchange-buttons-section {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
            padding: 20px 0 40px;
        }
        .learning-exchange-load-more-btn {
            background-color: #0165A0;
            color: white;
            border-radius: 30px;
            padding: 10px 24px;
            height: 40px;
            border: none;
            cursor: pointer;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .learning-exchange-load-more-btn:hover {
            background-color: #014d7a;
        }
        .learning-exchange-load-more-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        .learning-exchange-no-results {
            text-align: center;
            padding: 60px 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .learning-exchange-no-results h3,
        .learning-exchange-no-results p {
            margin: 0;
        }
        .learning-exchange-no-results svg {
            margin-bottom: 28px;
        }
        .learning-exchange-no-results h3 {
            margin-bottom: 10px;
        }
        @media (max-width: 1030px) {
            .learning-exchange-archive {
                max-width: 100%;
                padding: 0 20px;
            }
            .learning-exchange-grid {
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                justify-content: center;
            }
            .learning-exchange-card {
                width: 100%;
            }
        }
        @media (max-width: 768px) {
            .learning-exchange-filter-row {
                grid-template-columns: 1fr;
            }
            .learning-exchange-grid {
                grid-template-columns: 1fr;
            }
            .learning-exchange-filter-accordion {
                display: block;
            }
            .learning-exchange-filter-accordion-header {
                background: transparent;
                border-top: 1px solid #EBEBE6;
                border-bottom: 1px solid #EBEBE6;
                border-left: none;
                border-right: none;
                padding: 15px 0;
                cursor: pointer;
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                font-family: "Work Sans", sans-serif;
                font-weight: 500;
                font-size: 20px;
                line-height: 100%;
                letter-spacing: 0%;
                color: #2C2C2C;
            }
            .learning-exchange-filter-accordion-icon {
                transition: transform 0.3s ease;
            }
            .learning-exchange-filter-accordion-icon.active {
                transform: rotate(180deg);
            }
            .learning-exchange-filter-accordion-content {
                max-height: 0;
                overflow: hidden;
                transition: max-height 0.3s ease;
            }
            .learning-exchange-filter-accordion-content.active {
                max-height: 2000px;
            }
            .learning-exchange-filters {
                display: none;
            }
        }
        @media (min-width: 769px) {
            .learning-exchange-filter-accordion {
                display: none;
            }
        }
    </style>

    <div class="learning-exchange-archive">
        <!-- Mobile Accordion Filter -->
        <div class="learning-exchange-filter-accordion">
            <div class="learning-exchange-filter-accordion-header" onclick="toggleLearningExchangeFilters()">
                <span>Search & Filters</span>
                <svg class="learning-exchange-filter-accordion-icon" width="23" height="16" viewBox="0 0 23 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 1.04348C0 0.766731 0.110146 0.501318 0.306206 0.305628C0.502267 0.109937 0.768183 0 1.04545 0H21.9545C22.2318 0 22.4977 0.109937 22.6938 0.305628C22.8899 0.501318 23 0.766731 23 1.04348C23 1.32023 22.8899 1.58564 22.6938 1.78133C22.4977 1.97702 22.2318 2.08696 21.9545 2.08696H1.04545C0.768183 2.08696 0.502267 1.97702 0.306206 1.78133C0.110146 1.58564 0 1.32023 0 1.04348ZM3.48485 8C3.48485 7.72325 3.59499 7.45784 3.79105 7.26215C3.98712 7.06646 4.25303 6.95652 4.5303 6.95652H18.4697C18.747 6.95652 19.0129 7.06646 19.2089 7.26215C19.405 7.45784 19.5152 7.72325 19.5152 8C19.5152 8.27675 19.405 8.54216 19.2089 8.73785C19.0129 8.93354 18.747 9.04348 18.4697 9.04348H4.5303C4.25303 9.04348 3.98712 8.93354 3.79105 8.73785C3.59499 8.54216 3.48485 8.27675 3.48485 8ZM7.66667 14.9565C7.66667 14.6798 7.77681 14.4144 7.97287 14.2187C8.16893 14.023 8.43485 13.913 8.71212 13.913H14.2879C14.5652 13.913 14.8311 14.023 15.0271 14.2187C15.2232 14.4144 15.3333 14.6798 15.3333 14.9565C15.3333 15.2333 15.2232 15.4987 15.0271 15.6944C14.8311 15.8901 14.5652 16 14.2879 16H8.71212C8.43485 16 8.16893 15.8901 7.97287 15.6944C7.77681 15.4987 7.66667 15.2333 7.66667 14.9565Z" fill="#2C2C2C"/>
                </svg>
            </div>
            <div class="learning-exchange-filter-accordion-content">
                <form method="get" action="<?php echo esc_url(get_permalink()); ?>" class="learning-exchange-filters" style="display: block;">
                    <div class="learning-exchange-filter-row">
                        <div class="learning-exchange-filter-group">
                            <label>Search Keyword</label>
                            <input type="text" name="keyword" value="<?php echo esc_attr($keyword); ?>" placeholder="Search...">
                        </div>

                        <div class="learning-exchange-filter-group">
                            <label>Topic</label>
                            <select name="topic">
                                <option value="">All Topics</option>
                                <?php if (!empty($topics)) : foreach ($topics as $term) : ?>
                                    <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_topic, $term->slug); ?>>
                                        <?php echo esc_html($term->name); ?>
                                    </option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>

                        <div class="learning-exchange-filter-group">
                            <label>Month</label>
                            <select name="month">
                                <option value="">All Months</option>
                                <option value="01" <?php selected($selected_month, '01'); ?>>January</option>
                                <option value="02" <?php selected($selected_month, '02'); ?>>February</option>
                                <option value="03" <?php selected($selected_month, '03'); ?>>March</option>
                                <option value="04" <?php selected($selected_month, '04'); ?>>April</option>
                                <option value="05" <?php selected($selected_month, '05'); ?>>May</option>
                                <option value="06" <?php selected($selected_month, '06'); ?>>June</option>
                                <option value="07" <?php selected($selected_month, '07'); ?>>July</option>
                                <option value="08" <?php selected($selected_month, '08'); ?>>August</option>
                                <option value="09" <?php selected($selected_month, '09'); ?>>September</option>
                                <option value="10" <?php selected($selected_month, '10'); ?>>October</option>
                                <option value="11" <?php selected($selected_month, '11'); ?>>November</option>
                                <option value="12" <?php selected($selected_month, '12'); ?>>December</option>
                            </select>
                        </div>

                        <div class="learning-exchange-filter-group">
                            <label>Year</label>
                            <select name="year">
                                <option value="">All Years</option>
                                <?php
                                $current_year = date('Y');
                                for ($year = $current_year + 2; $year >= $current_year - 5; $year--) {
                                    echo '<option value="' . $year . '" ' . selected($selected_year, $year, false) . '>' . $year . '</option>';
                                }
                                ?>
                            </select>
                        </div>

                        <div class="learning-exchange-filter-group">
                            <button type="submit" class="learning-exchange-search-btn">Search</button>
                        </div>
                    </div>

                    <div class="learning-exchange-filter-actions">
                        <a href="<?php echo esc_url(get_permalink()); ?>" class="learning-exchange-reset-btn">
                            <svg width="19" height="17" viewBox="0 0 19 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M8.05029 0.771484C9.43992 0.153309 10.9698 -0.00869072 12.4458 0.306641C13.9218 0.621984 15.2765 1.40051 16.3384 2.54102C17.3999 3.68135 18.1212 5.13316 18.4136 6.71191C18.7059 8.29071 18.5566 9.92724 17.9829 11.415C17.4091 12.9029 16.4365 14.1765 15.187 15.0732C13.9373 15.9701 12.4667 16.4502 10.9614 16.4502H10.811V14.8164H10.9614C12.1569 14.8164 13.3269 14.4354 14.3228 13.7207C15.3185 13.0059 16.0965 11.9887 16.5562 10.7969C17.0158 9.60485 17.1363 8.29242 16.9019 7.02637C16.6674 5.76028 16.0887 4.59825 15.2407 3.6875C14.3929 2.77698 13.3138 2.15879 12.1411 1.9082C10.9684 1.65766 9.75241 1.78555 8.64697 2.27734C7.54153 2.76915 6.59505 3.60309 5.92822 4.6748C5.26132 5.74682 4.90479 7.00864 4.90479 8.2998V12.0518L6.87939 9.93066L6.98877 9.81348L7.09912 9.93066L7.96729 10.8643L8.06299 10.9668L7.96729 11.0684L4.24365 15.0684L4.13428 15.1865L4.02393 15.0684L0.300293 11.0684L0.20459 10.9668L0.300293 10.8643L1.16846 9.93066L1.27881 9.81348L1.38818 9.93066L3.36279 12.0518V8.2998C3.36279 6.69026 3.80765 5.11622 4.64111 3.77637C5.47472 2.43638 6.66074 1.38969 8.05029 0.771484Z" fill="#B1B1B1" stroke="#B1B1B1" stroke-width="0.3"/>
                            </svg>
                            Reset Search
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Desktop Filter (original) -->
        <form method="get" action="<?php echo esc_url(get_permalink()); ?>" class="learning-exchange-filters">
            <div class="learning-exchange-filter-row">
                <div class="learning-exchange-filter-group">
                    <label>Search Keyword</label>
                    <input type="text" name="keyword" value="<?php echo esc_attr($keyword); ?>" placeholder="Search...">
                </div>

                <div class="learning-exchange-filter-group">
                    <label>Topic</label>
                    <select name="topic">
                        <option value="">All Topics</option>
                        <?php if (!empty($topics)) : foreach ($topics as $term) : ?>
                            <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($selected_topic, $term->slug); ?>>
                                <?php echo esc_html($term->name); ?>
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                </div>

                <div class="learning-exchange-filter-group">
                    <label>Month</label>
                    <select name="month">
                        <option value="">All Months</option>
                        <option value="01" <?php selected($selected_month, '01'); ?>>January</option>
                        <option value="02" <?php selected($selected_month, '02'); ?>>February</option>
                        <option value="03" <?php selected($selected_month, '03'); ?>>March</option>
                        <option value="04" <?php selected($selected_month, '04'); ?>>April</option>
                        <option value="05" <?php selected($selected_month, '05'); ?>>May</option>
                        <option value="06" <?php selected($selected_month, '06'); ?>>June</option>
                        <option value="07" <?php selected($selected_month, '07'); ?>>July</option>
                        <option value="08" <?php selected($selected_month, '08'); ?>>August</option>
                        <option value="09" <?php selected($selected_month, '09'); ?>>September</option>
                        <option value="10" <?php selected($selected_month, '10'); ?>>October</option>
                        <option value="11" <?php selected($selected_month, '11'); ?>>November</option>
                        <option value="12" <?php selected($selected_month, '12'); ?>>December</option>
                    </select>
                </div>

                <div class="learning-exchange-filter-group">
                    <label>Year</label>
                    <select name="year">
                        <option value="">All Years</option>
                        <?php
                        $current_year = date('Y');
                        for ($year = $current_year + 2; $year >= $current_year - 5; $year--) {
                            echo '<option value="' . $year . '" ' . selected($selected_year, $year, false) . '>' . $year . '</option>';
                        }
                        ?>
                    </select>
                </div>
            </div>

            <div class="learning-exchange-filter-row">
                <div class="learning-exchange-filter-group" style="grid-column: span 4; display: flex; justify-content: flex-end;">
                    <button type="submit" class="learning-exchange-search-btn">Search</button>
                </div>
            </div>

            <div class="learning-exchange-filter-actions">
                <a href="<?php echo esc_url(get_permalink()); ?>" class="learning-exchange-reset-btn">
                    <svg width="19" height="17" viewBox="0 0 19 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8.05029 0.771484C9.43992 0.153309 10.9698 -0.00869072 12.4458 0.306641C13.9218 0.621984 15.2765 1.40051 16.3384 2.54102C17.3999 3.68135 18.1212 5.13316 18.4136 6.71191C18.7059 8.29071 18.5566 9.92724 17.9829 11.415C17.4091 12.9029 16.4365 14.1765 15.187 15.0732C13.9373 15.9701 12.4667 16.4502 10.9614 16.4502H10.811V14.8164H10.9614C12.1569 14.8164 13.3269 14.4354 14.3228 13.7207C15.3185 13.0059 16.0965 11.9887 16.5562 10.7969C17.0158 9.60485 17.1363 8.29242 16.9019 7.02637C16.6674 5.76028 16.0887 4.59825 15.2407 3.6875C14.3929 2.77698 13.3138 2.15879 12.1411 1.9082C10.9684 1.65766 9.75241 1.78555 8.64697 2.27734C7.54153 2.76915 6.59505 3.60309 5.92822 4.6748C5.26132 5.74682 4.90479 7.00864 4.90479 8.2998V12.0518L6.87939 9.93066L6.98877 9.81348L7.09912 9.93066L7.96729 10.8643L8.06299 10.9668L7.96729 11.0684L4.24365 15.0684L4.13428 15.1865L4.02393 15.0684L0.300293 11.0684L0.20459 10.9668L0.300293 10.8643L1.16846 9.93066L1.27881 9.81348L1.38818 9.93066L3.36279 12.0518V8.2998C3.36279 6.69026 3.80765 5.11622 4.64111 3.77637C5.47472 2.43638 6.66074 1.38969 8.05029 0.771484Z" fill="#B1B1B1" stroke="#B1B1B1" stroke-width="0.3"/>
                    </svg>
                    Reset Search
                </a>
            </div>
        </form>

        <?php if ($query->have_posts()) : ?>
            <div class="learning-exchange-grid">
                <?php while ($query->have_posts()) : $query->the_post();
                    $post_id = get_the_ID();
                    $topics_terms = get_the_terms($post_id, 'topic');

                    // Check if event is upcoming based on schedule_start_time
                    $schedule_start_time = get_field('schedule_start_time', $post_id, false);
                    $schedule_end_time = get_field('schedule_end_time', $post_id, false);
                    $is_upcoming = false;
                    if ($schedule_start_time) {
                        $start_timestamp = strtotime($schedule_start_time);
                        $current_timestamp = current_time('timestamp');
                        $is_upcoming = ($start_timestamp > $current_timestamp);
                    }

                    // Format date/time for all events
                    $formatted_datetime = '';
                    $datetime_color = '#B1B1B1'; // Default color for past events

                    if ($schedule_start_time) {
                        $start_day = date('l', strtotime($schedule_start_time));
                        $start_date = date('j M', strtotime($schedule_start_time));

                        if ($is_upcoming) {
                            // Upcoming events: show full time range
                            $datetime_color = '#E86A5A';
                            $start_time = date('g:i a', strtotime($schedule_start_time));

                            if ($schedule_end_time) {
                                $end_time = date('g:i a', strtotime($schedule_end_time));
                                $formatted_datetime = $start_day . ', ' . $start_date . ' ' . $start_time . ' | ' . $start_day . ', ' . $start_date . ' ' . $end_time;
                            } else {
                                $formatted_datetime = $start_day . ', ' . $start_date . ' ' . $start_time;
                            }
                        } else {
                            // Past events: show only day and date
                            $formatted_datetime = $start_day . ', ' . $start_date;
                        }
                    }
                ?>
                    <a href="<?php the_permalink(); ?>" class="learning-exchange-card">
                        <div class="learning-exchange-card-inner">
                            <?php
                            // Check for video URL first
                            $video_url = get_field('video_url', $post_id);
                            $embed_url = learning_exchange_get_youtube_embed_url($video_url);

                            if ($embed_url) : ?>
                                <div class="learning-exchange-video-wrapper">
                                    <iframe
                                        class="learning-exchange-image"
                                        src="<?php echo esc_url($embed_url); ?>"
                                        frameborder="0"
                                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                        allowfullscreen>
                                    </iframe>
                                </div>
                            <?php elseif (has_post_thumbnail()) : ?>
                                <img src="<?php echo get_the_post_thumbnail_url($post_id, 'medium_large'); ?>" alt="<?php the_title(); ?>" class="learning-exchange-image">
                            <?php else : ?>
                                <div class="learning-exchange-image"></div>
                            <?php endif; ?>

                            <div class="learning-exchange-content">
                                <?php if ($formatted_datetime) : ?>
                                    <div class="learning-exchange-datetime" style="color: <?php echo esc_attr($datetime_color); ?>;">
                                        <?php echo esc_html($formatted_datetime); ?>
                                    </div>
                                <?php endif; ?>

                                <div class="learning-exchange-tags">
                                    <?php if ($is_upcoming) : ?>
                                        <span class="learning-exchange-tag learning-exchange-tag-upcoming">UPCOMING</span>
                                    <?php endif; ?>

                                    <?php if ($topics_terms && !is_wp_error($topics_terms)) : ?>
                                        <?php foreach ($topics_terms as $term) : ?>
                                            <span class="learning-exchange-tag learning-exchange-tag-topic"><?php echo esc_html($term->name); ?></span>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>

                                <h3 class="learning-exchange-title">
                                    <?php the_title(); ?>
                                </h3>
                            </div>
                        </div>
                    </a>
                <?php endwhile; ?>
            </div>
        <?php else : ?>
            <div class="learning-exchange-no-results">
                <svg width="155" height="145" viewBox="0 0 155 145" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M148 62.4316V67.4658C147.997 86.1736 140.568 104.114 127.347 117.342C114.126 130.569 96.1958 138 77.5 138H72.469C63.872 138.001 55.3589 136.308 47.4159 133.017C39.4729 129.726 32.2556 124.902 26.1761 118.819C20.0966 112.737 15.274 105.516 11.9837 97.5683C8.69349 89.6208 7 81.1025 7 72.5V65.3304C7.00293 49.8592 13.147 35.0227 24.0808 24.0839C35.0146 13.1452 49.8428 7 65.304 7C79.2218 7 92.5695 12.5324 102.411 22.38C112.252 32.2277 117.781 45.584 117.781 59.5106V64.3568C117.781 75.8694 113.211 86.9108 105.077 95.0525C96.9424 103.194 85.9093 107.77 74.404 107.773H72.469C63.1219 107.767 54.1594 104.049 47.55 97.435C40.9406 90.8214 37.2249 81.8531 37.219 72.5V67.4658C37.219 59.448 40.4013 51.7584 46.0661 46.0879C51.7308 40.4174 59.4143 37.2303 67.427 37.2274C78.5504 37.2274 87.573 46.2557 87.573 57.3863V60.263C87.573 69.8003 79.833 77.5453 70.3018 77.5453H67.427" stroke="#E5E5D3" stroke-width="14" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <h3 style="font-family: 'Work Sans', sans-serif; font-weight: 400; font-size: 30px; line-height: 100%; letter-spacing: 0%; text-align: center; color: #D9D9C3;">No Result Found</h3>
                <p style="font-family: 'Work Sans', sans-serif; font-weight: 400; font-size: 16px; line-height: 140%; letter-spacing: 0%; text-align: center; color: #D9D9C3;">Try different filters</p>
            </div>
        <?php endif; ?>

        <?php wp_reset_postdata(); ?>

        <div class="learning-exchange-buttons-section">
            <?php if ($paged < $total_pages) : ?>
                <button class="learning-exchange-load-more-btn" data-page="<?php echo $paged; ?>" data-max-pages="<?php echo $total_pages; ?>">
                    Load More
                </button>
            <?php endif; ?>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('.learning-exchange-load-more-btn').on('click', function() {
            var button = $(this);
            var currentPage = parseInt(button.data('page'));
            var maxPages = parseInt(button.data('max-pages'));
            var nextPage = currentPage + 1;

            // Disable button
            button.prop('disabled', true).text('Loading...');

            // Get all current filter values from URL
            var urlParams = new URLSearchParams(window.location.search);

            // AJAX request to load more posts
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    action: 'learning_exchange_load_more',
                    paged: nextPage,
                    keyword: urlParams.get('keyword') || '',
                    topic: urlParams.get('topic') || '',
                    month: urlParams.get('month') || '',
                    year: urlParams.get('year') || ''
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        // Append new cards to grid
                        $('.learning-exchange-grid').append(response.data.html);

                        // Update button state
                        if (nextPage >= maxPages) {
                            button.remove(); // Remove button if no more pages
                        } else {
                            button.data('page', nextPage);
                            button.prop('disabled', false).text('Load More');
                        }
                    } else {
                        button.prop('disabled', false).text('Load More');
                        alert('No more posts to load.');
                    }
                },
                error: function() {
                    button.prop('disabled', false).text('Load More');
                    alert('Error loading more posts. Please try again.');
                }
            });
        });
    });
    </script>

    <script>
    function toggleLearningExchangeFilters() {
        var content = document.querySelector('.learning-exchange-filter-accordion-content');
        var icon = document.querySelector('.learning-exchange-filter-accordion-icon');
        content.classList.toggle('active');
        icon.classList.toggle('active');
    }
    </script>
    <?php

    return ob_get_clean();
}

// AJAX handler for Learning Exchange Load More
add_action('wp_ajax_learning_exchange_load_more', 'learning_exchange_load_more_handler');
add_action('wp_ajax_nopriv_learning_exchange_load_more', 'learning_exchange_load_more_handler');

function learning_exchange_load_more_handler() {
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;
    $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : '';
    $selected_topic = isset($_POST['topic']) ? sanitize_text_field($_POST['topic']) : '';
    $selected_month = isset($_POST['month']) ? sanitize_text_field($_POST['month']) : '';
    $selected_year = isset($_POST['year']) ? sanitize_text_field($_POST['year']) : '';

    // Build query args (same as main query)
    $args = array(
        'post_type' => 'learning_exchanges',
        'post_status' => 'publish',
        'posts_per_page' => 6,
        'paged' => $paged,
        'meta_key' => 'schedule_start_time',
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'meta_type' => 'DATETIME',
    );

    // Add keyword search
    if (!empty($keyword)) {
        $args['s'] = $keyword;
    }

    // Add taxonomy filters
    if (!empty($selected_topic)) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'topic',
                'field' => 'slug',
                'terms' => $selected_topic,
            ),
        );
    }

    // Add date filters for month and year
    $meta_query = array('relation' => 'AND');

    // Always ensure schedule_start_time exists
    $meta_query[] = array(
        'key' => 'schedule_start_time',
        'compare' => 'EXISTS',
    );

    if (!empty($selected_month) || !empty($selected_year)) {

        if (!empty($selected_month) && !empty($selected_year)) {
            // Filter by specific month and year
            $start_date = $selected_year . '-' . str_pad($selected_month, 2, '0', STR_PAD_LEFT) . '-01 00:00:00';
            $end_date = date('Y-m-t 23:59:59', strtotime($start_date));

            $meta_query[] = array(
                'key' => 'schedule_start_time',
                'value' => array($start_date, $end_date),
                'compare' => 'BETWEEN',
                'type' => 'DATETIME',
            );
        } elseif (!empty($selected_year)) {
            // Filter by year only
            $start_date = $selected_year . '-01-01 00:00:00';
            $end_date = $selected_year . '-12-31 23:59:59';

            $meta_query[] = array(
                'key' => 'schedule_start_time',
                'value' => array($start_date, $end_date),
                'compare' => 'BETWEEN',
                'type' => 'DATETIME',
            );
        }
    }

    // Always apply the meta_query (includes EXISTS check)
    if (!empty($meta_query)) {
        $args['meta_query'] = $meta_query;
    }

    $query = new WP_Query($args);

    ob_start();

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
            $topics_terms = get_the_terms($post_id, 'topic');

            // Check if event is upcoming based on schedule_start_time
            $schedule_start_time = get_field('schedule_start_time', $post_id, false);
            $schedule_end_time = get_field('schedule_end_time', $post_id, false);
            $is_upcoming = false;
            if ($schedule_start_time) {
                $start_timestamp = strtotime($schedule_start_time);
                $current_timestamp = current_time('timestamp');
                $is_upcoming = ($start_timestamp > $current_timestamp);
            }

            // Format date/time for all events
            $formatted_datetime = '';
            $datetime_color = '#B1B1B1'; // Default color for past events

            if ($schedule_start_time) {
                $start_day = date('l', strtotime($schedule_start_time));
                $start_date = date('j M', strtotime($schedule_start_time));

                if ($is_upcoming) {
                    // Upcoming events: show full time range
                    $datetime_color = '#E86A5A';
                    $start_time = date('g:i a', strtotime($schedule_start_time));

                    if ($schedule_end_time) {
                        $end_time = date('g:i a', strtotime($schedule_end_time));
                        $formatted_datetime = $start_day . ', ' . $start_date . ' ' . $start_time . ' | ' . $start_day . ', ' . $start_date . ' ' . $end_time;
                    } else {
                        $formatted_datetime = $start_day . ', ' . $start_date . ' ' . $start_time;
                    }
                } else {
                    // Past events: show only day and date
                    $formatted_datetime = $start_day . ', ' . $start_date;
                }
            }
            ?>
            <a href="<?php the_permalink(); ?>" class="learning-exchange-card">
                <div class="learning-exchange-card-inner">
                    <?php
                    // Check for video URL first
                    $video_url = get_field('video_url', $post_id);
                    $embed_url = learning_exchange_get_youtube_embed_url($video_url);

                    if ($embed_url) : ?>
                        <div class="learning-exchange-video-wrapper">
                            <iframe
                                class="learning-exchange-image"
                                src="<?php echo esc_url($embed_url); ?>"
                                frameborder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowfullscreen>
                            </iframe>
                        </div>
                    <?php elseif (has_post_thumbnail()) : ?>
                        <img src="<?php echo get_the_post_thumbnail_url($post_id, 'medium_large'); ?>" alt="<?php the_title(); ?>" class="learning-exchange-image">
                    <?php else : ?>
                        <div class="learning-exchange-image"></div>
                    <?php endif; ?>

                    <div class="learning-exchange-content">
                        <?php if ($formatted_datetime) : ?>
                            <div class="learning-exchange-datetime" style="color: <?php echo esc_attr($datetime_color); ?>;">
                                <?php echo esc_html($formatted_datetime); ?>
                            </div>
                        <?php endif; ?>

                        <div class="learning-exchange-tags">
                            <?php if ($is_upcoming) : ?>
                                <span class="learning-exchange-tag learning-exchange-tag-upcoming">UPCOMING</span>
                            <?php endif; ?>

                            <?php if ($topics_terms && !is_wp_error($topics_terms)) : ?>
                                <?php foreach ($topics_terms as $term) : ?>
                                    <span class="learning-exchange-tag learning-exchange-tag-topic"><?php echo esc_html($term->name); ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <h3 class="learning-exchange-title">
                            <?php the_title(); ?>
                        </h3>
                    </div>
                </div>
            </a>
            <?php
        }
    }

    wp_reset_postdata();

    $html = ob_get_clean();

    wp_send_json_success(array('html' => $html));
}

// Shortcode for single Learning Exchange details
function learning_exchange_single_details_display() {
    $post_id = get_the_ID();

    // Get schedule times
    $schedule_start_time = get_field('schedule_start_time', $post_id);
    $schedule_end_time = get_field('schedule_end_time', $post_id);

    // Get post author
    $author_id = get_post_field('post_author', $post_id);
    $author_name = get_the_author_meta('display_name', $author_id);

    // Try to get full_name from ACF if it exists
    if (function_exists('get_field')) {
        $full_name = get_field('full_name', 'user_' . $author_id);
        if ($full_name) {
            $author_name = $full_name;
        }
    }

    // Format date and time
    $date_display = '';
    $time_display = '';

    if ($schedule_start_time) {
        $start_timestamp = strtotime($schedule_start_time);
        // Format: Thursday, 29 Jan
        $date_display = date('l, j M', $start_timestamp);

        // Format time: 9:00 am - 10:00 am
        $start_time = date('g:i a', $start_timestamp);
        if ($schedule_end_time) {
            $end_timestamp = strtotime($schedule_end_time);
            $end_time = date('g:i a', $end_timestamp);
            $time_display = $start_time . ' - ' . $end_time;
        } else {
            $time_display = $start_time;
        }
    }

    // Get topic taxonomy terms
    $topics_terms = get_the_terms($post_id, 'topic');

    ob_start();
    ?>

    <style>
        .learning-exchange-single-container {
            max-width: 600px;
        }
        .learning-exchange-tags-single {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 24px;
        }
        .learning-exchange-resource-tag {
            border-radius: 20px;
            padding: 3px 7px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-style: normal;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
        }
        .learning-exchange-tag-topic-single {
            background: transparent;
            border: 1px solid #2C2C2C;
            color: #2C2C2C;
        }
        .learning-exchange-single-details {
            border-radius: 8px;
            max-width: 600px;
        }
        .learning-exchange-detail-item {
            padding: 12px 12px 12px 0;
            border-bottom: 1px solid #EBEBE6;
        }
        .learning-exchange-detail-item:last-child {
            border-bottom: none;
        }
        .learning-exchange-detail-label {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-size: 12px;
            line-height: 140%;
            letter-spacing: 0.02em;
            text-transform: uppercase;
            color: #999999;
            margin-bottom: 4px;
        }
        .learning-exchange-detail-value {
            font-family: "Work Sans", sans-serif;
            font-weight: 400;
            font-size: 16px;
            line-height: 150%;
            color: #2C2C2C;
        }
    </style>

    <div class="learning-exchange-single-container">
        <?php if ($topics_terms && !is_wp_error($topics_terms)) : ?>
            <div class="learning-exchange-tags-single">
                <?php foreach ($topics_terms as $term) : ?>
                    <span class="learning-exchange-resource-tag learning-exchange-tag-topic-single"><?php echo esc_html($term->name); ?></span>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="learning-exchange-single-details">
            <?php if ($date_display) : ?>
                <div class="learning-exchange-detail-item">
                    <div class="learning-exchange-detail-label">Date</div>
                    <div class="learning-exchange-detail-value"><?php echo esc_html($date_display); ?></div>
                </div>
            <?php endif; ?>

            <?php if ($time_display) : ?>
                <div class="learning-exchange-detail-item">
                    <div class="learning-exchange-detail-label">Time</div>
                    <div class="learning-exchange-detail-value"><?php echo esc_html($time_display); ?></div>
                </div>
            <?php endif; ?>

            <?php if ($author_name) : ?>
                <div class="learning-exchange-detail-item">
                    <div class="learning-exchange-detail-label">Hosted By</div>
                    <div class="learning-exchange-detail-value"><?php echo esc_html($author_name); ?></div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode('learning_exchange_single_details', 'learning_exchange_single_details_display');

// Shortcode for single Learning Exchange video/image display
function learning_exchange_single_media_display() {
    $post_id = get_the_ID();

    // Check for video URL first
    $video_url = get_field('video_url', $post_id);
    $embed_url = learning_exchange_get_youtube_embed_url($video_url);

    ob_start();
    ?>

    <style>
        .learning-exchange-single-media {
            width: 100%;
            max-width: 100%;
            margin-bottom: 30px;
        }
        .learning-exchange-single-video-wrapper {
            position: relative;
            width: 296px;
            height: 165px;
            overflow: hidden;
            border-radius: 10px;
            background: #000;
        }
        .learning-exchange-single-video-wrapper iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: 0;
        }
        .learning-exchange-single-image {
            width: 296px;
            height: 165px;
            border-radius: 10px;
            object-fit: cover;
            display: block;
        }
    </style>

    <div class="learning-exchange-single-media">
        <?php if ($embed_url) : ?>
            <div class="learning-exchange-single-video-wrapper">
                <iframe
                    src="<?php echo esc_url($embed_url); ?>"
                    frameborder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                    allowfullscreen>
                </iframe>
            </div>
        <?php elseif (has_post_thumbnail()) : ?>
            <img src="<?php echo get_the_post_thumbnail_url($post_id, 'large'); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="learning-exchange-single-image">
        <?php endif; ?>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode('learning_exchange_single_media', 'learning_exchange_single_media_display');

// Shortcode for upcoming Learning Exchanges banner/slider
function upcoming_learning_exchanges_banner() {
    ob_start();

    // Query upcoming learning exchanges
    $args = array(
        'post_type' => 'learning_exchanges',
        'posts_per_page' => -1,
        'meta_key' => 'schedule_start_time',
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_query' => array(
            array(
                'key' => 'schedule_start_time',
                'value' => current_time('Y-m-d H:i:s'),
                'compare' => '>=',
                'type' => 'DATETIME'
            )
        )
    );

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '';
    }

    $count = $query->post_count;
    $is_slider = $count > 1;

    ?>
    <style>
        .upcoming-le-banner-wrapper {
            width: 100%;
            max-width: 1030px;
            margin: 0 auto;
            position: relative;
        }
        .upcoming-le-banner-container {
            width: 100%;
            height: 266px;
            position: relative;
            overflow: hidden;
        }
        .upcoming-le-banner-slide {
            width: 100%;
            height: 266px;
            border-radius: 10px;
            overflow: hidden;
            background: #E86A5A;
            padding: 12px;
            display: flex;
            position: relative;
        }
        .upcoming-le-banner-content {
            flex: 1;
            padding: 40px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            color: #FFFFFF;
        }
        .upcoming-le-banner-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
        }
        .upcoming-le-banner-tag {
            font-family: "Work Sans", sans-serif;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
            color: #FFFFFF;
        }
        .upcoming-le-banner-tag-upcoming {
            font-weight: 800;
        }
        .upcoming-le-banner-tag-topic {
            font-weight: 500;
        }
        .upcoming-le-banner-title {
            font-family: "Forum", serif;
            font-weight: 400;
            font-size: 36px;
            line-height: 100%;
            letter-spacing: 0%;
            margin-top: 0;
            margin-bottom: 36px;
            color: #FFFFFF;
        }
        .upcoming-le-banner-datetime {
            display: flex;
            align-items: center;
            gap: 8px;
            max-width: 176px;
        }
        .upcoming-le-banner-datetime svg {
            width: 29px;
            height: 30px;
            flex-shrink: 0;
        }
        .upcoming-le-banner-datetime span {
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-size: 14px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #FFFFFF;
            flex: 1;
        }
        .upcoming-le-banner-bottom-row {
            display: flex;
            align-items: center;
            gap: 24px;
        }
        .upcoming-le-banner-register {
            display: inline-block;
            background: #FFFFFF;
            color: #E86A5A;
            padding: 10px 24px;
            border-radius: 36px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
            text-decoration: none;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }
        .upcoming-le-banner-register:hover {
            background: #F5F5F5;
            transform: translateY(-2px);
        }
        .upcoming-le-banner-media {
            width: 435px;
            height: 242px;
            position: relative;
            flex-shrink: 0;
            border-radius: 6px;
            overflow: hidden;
        }
        .upcoming-le-banner-video-wrapper {
            width: 100%;
            height: 100%;
            position: relative;
            background: #000;
        }
        .upcoming-le-banner-video-wrapper iframe {
            width: 100%;
            height: 100%;
            border: 0;
        }
        .upcoming-le-banner-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        /* Slider Controls */
        .upcoming-le-slider-controls {
            position: absolute;
            bottom: 20px;
            left: 40px;
            display: flex;
            gap: 12px;
            z-index: 10;
        }
        .upcoming-le-slider-arrow {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        .upcoming-le-slider-arrow:hover {
            background: #FFFFFF;
            transform: scale(1.1);
        }
        .upcoming-le-slider-arrow svg {
            width: 20px;
            height: 20px;
            fill: #E86A5A;
        }
        .upcoming-le-slider-dots {
            position: absolute;
            bottom: 20px;
            right: 40px;
            display: flex;
            gap: 8px;
            z-index: 10;
        }
        .upcoming-le-slider-dot {
            width: 8px;
            height: 8px;
            background: rgba(255, 255, 255, 0.5);
            border: none;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upcoming-le-slider-dot.active {
            width: 24px;
            border-radius: 4px;
            background: #FFFFFF;
        }

        /* Hide slides by default in slider mode */
        .upcoming-le-slides .upcoming-le-banner-slide {
            display: none;
        }
        .upcoming-le-slides .upcoming-le-banner-slide.active {
            display: flex;
        }

        @media (max-width: 768px) {
            .upcoming-le-banner-container {
                height: auto;
            }
            .upcoming-le-banner-slide {
                flex-direction: column;
                height: auto;
                min-height: auto;
            }
            .upcoming-le-banner-content {
                padding: 24px 0;
                width: 100%;
            }
            .upcoming-le-banner-title {
                font-size: 24px;
            }
            .upcoming-le-banner-media {
                width: 100%;
                height: 200px;
                order: -1;
            }
            .upcoming-le-slider-controls {
                position: relative;
                left: auto;
                bottom: auto;
                justify-content: center;
                margin-top: 16px;
                padding: 0 24px 24px;
            }
            .upcoming-le-slider-dots {
                position: relative;
                right: auto;
                bottom: auto;
                justify-content: center;
                padding: 0 24px 16px;
            }
        }
    </style>

    <div class="upcoming-le-banner-wrapper">
        <div class="upcoming-le-banner-container">
            <div class="upcoming-le-slides">
                <?php
                $slide_index = 0;
                while ($query->have_posts()) :
                    $query->the_post();
                    $post_id = get_the_ID();
                    $slide_index++;

                    // Get ACF fields
                    $start_time = get_field('schedule_start_time', $post_id, false);
                    $end_time = get_field('schedule_end_time', $post_id, false);
                    $video_url = get_field('video_url', $post_id);
                    $meeting_link = get_field('meeting_link', $post_id);

                    // Get topics
                    $topics = get_the_terms($post_id, 'topic');

                    // Format date and time
                    $datetime_formatted = '';
                    if ($start_time) {
                        // Try to create DateTime object from the field value
                        $date_obj = false;

                        // Try different date formats
                        if (strtotime($start_time)) {
                            $date_obj = new DateTime($start_time);
                        }

                        if ($date_obj) {
                            $date_part = $date_obj->format('l, j M');
                            $start_time_str = $date_obj->format('g:i a');

                            if ($end_time) {
                                $end_date_obj = false;
                                if (strtotime($end_time)) {
                                    $end_date_obj = new DateTime($end_time);
                                }

                                if ($end_date_obj) {
                                    $end_time_str = $end_date_obj->format('g:i a');
                                    $datetime_formatted = $date_part . ' ' . $start_time_str . ' - ' . $end_time_str . ' EDT';
                                } else {
                                    $datetime_formatted = $date_part . ' ' . $start_time_str . ' EDT';
                                }
                            } else {
                                $datetime_formatted = $date_part . ' ' . $start_time_str . ' EDT';
                            }
                        }
                    }

                    // Get video embed URL
                    $embed_url = '';
                    if ($video_url) {
                        $embed_url = learning_exchange_get_youtube_embed_url($video_url);
                    }

                    $active_class = ($slide_index === 1) ? 'active' : '';
                ?>
                <div class="upcoming-le-banner-slide <?php echo $active_class; ?>">
                    <div class="upcoming-le-banner-content">
                        <div class="upcoming-le-banner-tags">
                            <span class="upcoming-le-banner-tag upcoming-le-banner-tag-upcoming">UPCOMING</span>
                            <?php if ($topics && !is_wp_error($topics)) : ?>
                                <?php foreach ($topics as $topic) : ?>
                                    <span class="upcoming-le-banner-tag upcoming-le-banner-tag-topic"><?php echo esc_html($topic->name); ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <h2 class="upcoming-le-banner-title"><?php the_title(); ?></h2>

                        <div class="upcoming-le-banner-bottom-row">
                            <?php if ($datetime_formatted) : ?>
                            <div class="upcoming-le-banner-datetime">
                                <svg width="29" height="30" viewBox="0 0 29 30" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M0.75 10.5878H27.75M7.09269 3.77703V0.75M21.3641 3.77703V0.75M22.35 3.77703H6.15C4.71783 3.77703 3.34432 4.33513 2.33162 5.32857C1.31893 6.32201 0.75 7.66939 0.75 9.07432V23.4527C0.75 24.8576 1.31893 26.205 2.33162 27.1985C3.34432 28.1919 4.71783 28.75 6.15 28.75H22.35C23.7822 28.75 25.1557 28.1919 26.1684 27.1985C27.1811 26.205 27.75 24.8576 27.75 23.4527V9.07432C27.75 7.66939 27.1811 6.32201 26.1684 5.32857C25.1557 4.33513 23.7822 3.77703 22.35 3.77703Z" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                <span><?php echo esc_html($datetime_formatted); ?></span>
                            </div>
                            <?php endif; ?>

                            <?php if ($meeting_link) : ?>
                                <a href="<?php echo esc_url($meeting_link); ?>" class="upcoming-le-banner-register" target="_blank" rel="noopener noreferrer">REGISTER</a>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="upcoming-le-banner-media">
                        <?php if ($embed_url) : ?>
                            <div class="upcoming-le-banner-video-wrapper">
                                <iframe
                                    src="<?php echo esc_url($embed_url); ?>"
                                    frameborder="0"
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                    allowfullscreen>
                                </iframe>
                            </div>
                        <?php elseif (has_post_thumbnail()) : ?>
                            <img src="<?php echo get_the_post_thumbnail_url($post_id, 'large'); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="upcoming-le-banner-image">
                        <?php endif; ?>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>

            <?php if ($is_slider) : ?>
            <!-- Slider Controls -->
            <div class="upcoming-le-slider-controls">
                <button class="upcoming-le-slider-arrow upcoming-le-prev" onclick="upcomingLESlider.prev()">
                    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
                <button class="upcoming-le-slider-arrow upcoming-le-next" onclick="upcomingLESlider.next()">
                    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
            </div>

            <div class="upcoming-le-slider-dots">
                <?php for ($i = 1; $i <= $count; $i++) : ?>
                    <button class="upcoming-le-slider-dot <?php echo ($i === 1) ? 'active' : ''; ?>"
                            onclick="upcomingLESlider.goToSlide(<?php echo $i - 1; ?>)"></button>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($is_slider) : ?>
    <script>
        var upcomingLESlider = {
            currentSlide: 0,
            totalSlides: <?php echo $count; ?>,
            slides: null,
            dots: null,

            init: function() {
                this.slides = document.querySelectorAll('.upcoming-le-banner-slide');
                this.dots = document.querySelectorAll('.upcoming-le-slider-dot');
            },

            goToSlide: function(index) {
                // Remove active class from all slides and dots
                this.slides.forEach(function(slide) {
                    slide.classList.remove('active');
                });
                this.dots.forEach(function(dot) {
                    dot.classList.remove('active');
                });

                // Add active class to current slide and dot
                this.slides[index].classList.add('active');
                this.dots[index].classList.add('active');
                this.currentSlide = index;
            },

            next: function() {
                var nextSlide = (this.currentSlide + 1) % this.totalSlides;
                this.goToSlide(nextSlide);
            },

            prev: function() {
                var prevSlide = (this.currentSlide - 1 + this.totalSlides) % this.totalSlides;
                this.goToSlide(prevSlide);
            }
        };

        // Initialize slider when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                upcomingLESlider.init();
            });
        } else {
            upcomingLESlider.init();
        }

        // Auto-advance slider every 5 seconds
        setInterval(function() {
            upcomingLESlider.next();
        }, 5000);
    </script>
    <?php endif; ?>

    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('upcoming_learning_exchanges_banner', 'upcoming_learning_exchanges_banner');

// Shortcode for upcoming Learning Exchanges - Mobile-First UI
function upcoming_learning_exchanges_mobile() {
    ob_start();

    // Query upcoming learning exchanges
    $args = array(
        'post_type' => 'learning_exchanges',
        'posts_per_page' => -1,
        'meta_key' => 'schedule_start_time',
        'orderby' => 'meta_value',
        'order' => 'ASC',
        'meta_query' => array(
            array(
                'key' => 'schedule_start_time',
                'value' => current_time('Y-m-d H:i:s'),
                'compare' => '>=',
                'type' => 'DATETIME'
            )
        )
    );

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '';
    }

    $count = $query->post_count;
    $is_slider = $count > 1;

    ?>
    <style>
        .upcoming-le-mobile-wrapper {
            width: 100%;
            max-width: 500px;
            margin: 0 auto;
            position: relative;
        }
        .upcoming-le-mobile-container {
            width: 100%;
            position: relative;
            overflow: hidden;
        }
        .upcoming-le-mobile-slide {
            width: 100%;
            border-radius: 10px;
            overflow: hidden;
            background: #BDCEBA;
            padding: 12px 12px 40px 12px;
            display: flex;
            flex-direction: column;
            position: relative;
        }
        .upcoming-le-mobile-media {
            width: 100%;
            height: 266px;
            position: relative;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 24px;
        }
        .upcoming-le-mobile-video-wrapper {
            width: 100%;
            height: 100%;
            position: relative;
            background: #000;
        }
        .upcoming-le-mobile-video-wrapper iframe {
            width: 100%;
            height: 100%;
            border: 0;
        }
        .upcoming-le-mobile-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .upcoming-le-mobile-content {
            padding: 0;
            display: flex;
            flex-direction: column;
            color: #2C2C2C;
        }
        .upcoming-le-mobile-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 16px;
            flex-wrap: wrap;
        }
        .upcoming-le-mobile-tag {
            font-family: "Work Sans", sans-serif;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
            color: #2C2C2C;
        }
        .upcoming-le-mobile-tag-upcoming {
            font-weight: 800;
        }
        .upcoming-le-mobile-tag-topic {
            font-weight: 500;
        }
        .upcoming-le-mobile-title {
            font-family: "Forum", serif;
            font-weight: 400;
            font-size: 36px;
            line-height: 100%;
            letter-spacing: 0%;
            margin: 0 0 36px 0;
            color: #2C2C2C;
        }
        .upcoming-le-mobile-bottom-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .upcoming-le-mobile-datetime {
            display: flex;
            align-items: center;
            gap: 8px;
            max-width: 176px;
        }
        .upcoming-le-mobile-datetime svg {
            width: 29px;
            height: 30px;
            flex-shrink: 0;
        }
        .upcoming-le-mobile-datetime span {
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-size: 14px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #2C2C2C;
            flex: 1;
        }
        .upcoming-le-mobile-register {
            display: inline-block;
            background: #0165A0;
            color: #FFFFFF;
            padding: 10px 24px;
            border-radius: 36px;
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 14px;
            line-height: 100%;
            letter-spacing: 0%;
            text-transform: uppercase;
            text-decoration: none;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }
        .upcoming-le-mobile-register:hover {
            background: #014d7a;
            transform: translateY(-2px);
        }

        /* Slider Controls */
        .upcoming-le-mobile-slider-controls {
            display: flex;
            gap: 12px;
            justify-content: center;
            margin-top: 16px;
            padding-bottom: 16px;
        }
        .upcoming-le-mobile-slider-arrow {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        .upcoming-le-mobile-slider-arrow:hover {
            background: #FFFFFF;
            transform: scale(1.1);
        }
        .upcoming-le-mobile-slider-arrow svg {
            width: 20px;
            height: 20px;
            fill: #E86A5A;
        }
        .upcoming-le-mobile-slider-dots {
            display: flex;
            gap: 8px;
            justify-content: center;
            padding-bottom: 16px;
        }
        .upcoming-le-mobile-slider-dot {
            width: 8px;
            height: 8px;
            background: rgba(255, 255, 255, 0.5);
            border: none;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upcoming-le-mobile-slider-dot.active {
            width: 24px;
            border-radius: 4px;
            background: #FFFFFF;
        }

        /* Hide slides by default in slider mode */
        .upcoming-le-mobile-slides .upcoming-le-mobile-slide {
            display: none;
        }
        .upcoming-le-mobile-slides .upcoming-le-mobile-slide.active {
            display: flex;
        }

        /* Mobile adjustments */
        @media (max-width: 768px) {
            .upcoming-le-mobile-wrapper {
                max-width: 425px;
            }
            .upcoming-le-mobile-title {
                font-size: 24px;
            }
            .upcoming-le-mobile-content {
                padding: 0;
            }
        }

        /* Desktop padding */
        @media (min-width: 769px) {
            .upcoming-le-mobile-content {
                padding: 0 18px;
            }
        }
    </style>

    <div class="upcoming-le-mobile-wrapper">
        <div class="upcoming-le-mobile-container">
            <div class="upcoming-le-mobile-slides">
                <?php
                $slide_index = 0;
                while ($query->have_posts()) :
                    $query->the_post();
                    $post_id = get_the_ID();
                    $slide_index++;

                    // Get ACF fields
                    $start_time = get_field('schedule_start_time', $post_id, false);
                    $end_time = get_field('schedule_end_time', $post_id, false);
                    $video_url = get_field('video_url', $post_id);
                    $meeting_link = get_field('meeting_link', $post_id);

                    // Get topics
                    $topics = get_the_terms($post_id, 'topic');

                    // Format date and time
                    $datetime_formatted = '';
                    if ($start_time) {
                        // Try to create DateTime object from the field value
                        $date_obj = false;

                        // Try different date formats
                        if (strtotime($start_time)) {
                            $date_obj = new DateTime($start_time);
                        }

                        if ($date_obj) {
                            $date_part = $date_obj->format('l, j M');
                            $start_time_str = $date_obj->format('g:i a');

                            if ($end_time) {
                                $end_date_obj = false;
                                if (strtotime($end_time)) {
                                    $end_date_obj = new DateTime($end_time);
                                }

                                if ($end_date_obj) {
                                    $end_time_str = $end_date_obj->format('g:i a');
                                    $datetime_formatted = $date_part . ' ' . $start_time_str . ' - ' . $end_time_str . ' EDT';
                                } else {
                                    $datetime_formatted = $date_part . ' ' . $start_time_str . ' EDT';
                                }
                            } else {
                                $datetime_formatted = $date_part . ' ' . $start_time_str . ' EDT';
                            }
                        }
                    }

                    // Get video embed URL
                    $embed_url = '';
                    if ($video_url) {
                        $embed_url = learning_exchange_get_youtube_embed_url($video_url);
                    }

                    $active_class = ($slide_index === 1) ? 'active' : '';
                ?>
                <div class="upcoming-le-mobile-slide <?php echo $active_class; ?>">
                    <div class="upcoming-le-mobile-media">
                        <?php if ($embed_url) : ?>
                            <div class="upcoming-le-mobile-video-wrapper">
                                <iframe
                                    src="<?php echo esc_url($embed_url); ?>"
                                    frameborder="0"
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                    allowfullscreen>
                                </iframe>
                            </div>
                        <?php elseif (has_post_thumbnail()) : ?>
                            <img src="<?php echo get_the_post_thumbnail_url($post_id, 'large'); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="upcoming-le-mobile-image">
                        <?php endif; ?>
                    </div>

                    <div class="upcoming-le-mobile-content">
                        <div class="upcoming-le-mobile-tags">
                            <span class="upcoming-le-mobile-tag upcoming-le-mobile-tag-upcoming">UPCOMING</span>
                            <?php if ($topics && !is_wp_error($topics)) : ?>
                                <?php foreach ($topics as $topic) : ?>
                                    <span class="upcoming-le-mobile-tag upcoming-le-mobile-tag-topic"><?php echo esc_html($topic->name); ?></span>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>

                        <h2 class="upcoming-le-mobile-title"><?php the_title(); ?></h2>

                        <div class="upcoming-le-mobile-bottom-row">
                            <?php if ($datetime_formatted) : ?>
                            <div class="upcoming-le-mobile-datetime">
                                <svg width="29" height="30" viewBox="0 0 29 30" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M0.75 10.5878H27.75M7.09269 3.77703V0.75M21.3641 3.77703V0.75M22.35 3.77703H6.15C4.71783 3.77703 3.34432 4.33513 2.33162 5.32857C1.31893 6.32201 0.75 7.66939 0.75 9.07432V23.4527C0.75 24.8576 1.31893 26.205 2.33162 27.1985C3.34432 28.1919 4.71783 28.75 6.15 28.75H22.35C23.7822 28.75 25.1557 28.1919 26.1684 27.1985C27.1811 26.205 27.75 24.8576 27.75 23.4527V9.07432C27.75 7.66939 27.1811 6.32201 26.1684 5.32857C25.1557 4.33513 23.7822 3.77703 22.35 3.77703Z" stroke="#2C2C2C" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                                </svg>
                                <span><?php echo esc_html($datetime_formatted); ?></span>
                            </div>
                            <?php endif; ?>

                            <?php if ($meeting_link) : ?>
                                <a href="<?php echo esc_url($meeting_link); ?>" class="upcoming-le-mobile-register" target="_blank" rel="noopener noreferrer">REGISTER</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>

            <?php if ($is_slider) : ?>
            <!-- Slider Controls -->
            <div class="upcoming-le-mobile-slider-controls">
                <button class="upcoming-le-mobile-slider-arrow upcoming-le-mobile-prev" onclick="upcomingLEMobileSlider.prev()">
                    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
                <button class="upcoming-le-mobile-slider-arrow upcoming-le-mobile-next" onclick="upcomingLEMobileSlider.next()">
                    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
            </div>

            <div class="upcoming-le-mobile-slider-dots">
                <?php for ($i = 1; $i <= $count; $i++) : ?>
                    <button class="upcoming-le-mobile-slider-dot <?php echo ($i === 1) ? 'active' : ''; ?>"
                            onclick="upcomingLEMobileSlider.goToSlide(<?php echo $i - 1; ?>)"></button>
                <?php endfor; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($is_slider) : ?>
    <script>
        var upcomingLEMobileSlider = {
            currentSlide: 0,
            totalSlides: <?php echo $count; ?>,
            slides: null,
            dots: null,

            init: function() {
                this.slides = document.querySelectorAll('.upcoming-le-mobile-slide');
                this.dots = document.querySelectorAll('.upcoming-le-mobile-slider-dot');
            },

            goToSlide: function(index) {
                // Remove active class from all slides and dots
                this.slides.forEach(function(slide) {
                    slide.classList.remove('active');
                });
                this.dots.forEach(function(dot) {
                    dot.classList.remove('active');
                });

                // Add active class to current slide and dot
                this.slides[index].classList.add('active');
                this.dots[index].classList.add('active');
                this.currentSlide = index;
            },

            next: function() {
                var nextSlide = (this.currentSlide + 1) % this.totalSlides;
                this.goToSlide(nextSlide);
            },

            prev: function() {
                var prevSlide = (this.currentSlide - 1 + this.totalSlides) % this.totalSlides;
                this.goToSlide(prevSlide);
            }
        };

        // Initialize slider when DOM is ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', function() {
                upcomingLEMobileSlider.init();
            });
        } else {
            upcomingLEMobileSlider.init();
        }

        // Auto-advance slider every 5 seconds
        setInterval(function() {
            upcomingLEMobileSlider.next();
        }, 5000);
    </script>
    <?php endif; ?>

    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('upcoming_learning_exchanges_mobile', 'upcoming_learning_exchanges_mobile');

// Shortcode for Past Learning Exchanges - Latest 3
function past_learning_exchanges_grid() {
    ob_start();

    // Query past learning exchanges (not upcoming)
    $args = array(
        'post_type' => 'learning_exchanges',
        'posts_per_page' => 3,
        'meta_key' => 'schedule_start_time',
        'orderby' => 'meta_value',
        'order' => 'DESC',
        'meta_query' => array(
            array(
                'key' => 'schedule_start_time',
                'value' => current_time('Y-m-d H:i:s'),
                'compare' => '<',
                'type' => 'DATETIME'
            )
        )
    );

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '';
    }

    ?>
    <style>
        .past-le-grid-wrapper {
            width: 100%;
            margin: 0 auto;
        }
        .past-le-grid {
            display: flex;
            flex-direction: column;
            gap: 24px;
        }
        .past-le-card {
            background: transparent;
            border-radius: 0;
            padding: 0;
            display: flex;
            flex-direction: row;
            align-items: center;
            gap: 24px;
            text-decoration: none;
            transition: transform 0.3s ease;
        }
        .past-le-card:hover {
            transform: translateY(-5px);
        }
        .past-le-media {
            width: 180px;
            height: 101px;
            position: relative;
            border-radius: 6px;
            overflow: hidden;
            flex-shrink: 0;
        }
        .past-le-video-wrapper {
            width: 100%;
            height: 100%;
            position: relative;
            background: #000;
        }
        .past-le-video-wrapper iframe {
            width: 100%;
            height: 100%;
            border: 0;
        }
        .past-le-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .past-le-content {
            display: flex;
            flex-direction: column;
            flex: 1;
            max-width: 246px;
        }
        .past-le-tags {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }
        .past-le-tag {
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-size: 10px;
            line-height: 140%;
            letter-spacing: 0%;
            text-transform: uppercase;
            color: #2C2C2C;
        }
        .past-le-title {
            font-family: "Work Sans", sans-serif;
            font-weight: 600;
            font-size: 16px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #2C2C2C;
            margin: 0 0 12px 0;
        }
        .past-le-datetime {
            font-family: "Work Sans", sans-serif;
            font-weight: 500;
            font-size: 14px;
            line-height: 120%;
            letter-spacing: 0%;
            color: #B1B1B1;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .past-le-datetime svg {
            width: 20px;
            height: 20px;
            flex-shrink: 0;
        }

        /* Mobile Layout */
        @media (max-width: 768px) {
            .past-le-card {
                flex-direction: column;
                align-items: flex-start;
                gap: 16px;
            }
            .past-le-media {
                width: 100%;
                height: 177px;
            }
        }
    </style>

    <div class="past-le-grid-wrapper">
        <div class="past-le-grid">
            <?php
            while ($query->have_posts()) :
                $query->the_post();
                $post_id = get_the_ID();

                // Get ACF fields
                $start_time = get_field('schedule_start_time', $post_id, false);
                $video_url = get_field('video_url', $post_id);

                // Get topics
                $topics = get_the_terms($post_id, 'topic');

                // Format date
                $date_formatted = '';
                if ($start_time) {
                    if (strtotime($start_time)) {
                        $date_obj = new DateTime($start_time);
                        $date_formatted = $date_obj->format('l, j M');
                    }
                }

                // Get video embed URL
                $embed_url = '';
                if ($video_url) {
                    $embed_url = learning_exchange_get_youtube_embed_url($video_url);
                }
            ?>
            <a href="<?php the_permalink(); ?>" class="past-le-card">
                <div class="past-le-media">
                    <?php if ($embed_url) : ?>
                        <div class="past-le-video-wrapper">
                            <iframe
                                src="<?php echo esc_url($embed_url); ?>"
                                frameborder="0"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                                allowfullscreen>
                            </iframe>
                        </div>
                    <?php elseif (has_post_thumbnail()) : ?>
                        <img src="<?php echo get_the_post_thumbnail_url($post_id, 'medium_large'); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="past-le-image">
                    <?php endif; ?>
                </div>

                <div class="past-le-content">
                    <?php if ($topics && !is_wp_error($topics)) : ?>
                    <div class="past-le-tags">
                        <?php foreach ($topics as $topic) : ?>
                            <span class="past-le-tag"><?php echo esc_html($topic->name); ?></span>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <h3 class="past-le-title"><?php the_title(); ?></h3>

                    <?php if ($date_formatted) : ?>
                    <div class="past-le-datetime">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <rect x="3" y="4" width="14" height="13" rx="1.5" stroke="#B1B1B1" stroke-width="1.5" fill="none"/>
                            <line x1="3" y1="7.5" x2="17" y2="7.5" stroke="#B1B1B1" stroke-width="1.5"/>
                            <line x1="6.5" y1="2" x2="6.5" y2="5" stroke="#B1B1B1" stroke-width="1.5" stroke-linecap="round"/>
                            <line x1="13.5" y1="2" x2="13.5" y2="5" stroke="#B1B1B1" stroke-width="1.5" stroke-linecap="round"/>
                        </svg>
                        <span><?php echo esc_html($date_formatted); ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </a>
            <?php endwhile; ?>
        </div>
    </div>

    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('past_learning_exchanges_grid', 'past_learning_exchanges_grid');

// AJAX Login Form Shortcode
function ajax_login_form_shortcode() {
    // If user is already logged in, show a message
    if (is_user_logged_in()) {
        return '<p style="text-align: center;">You are already logged in.</p>';
    }

    ob_start();
    ?>
    <style>
        /* Force all form fields to stay visible in popups */
        .elementor-location-popup .ajax-login-form .ajax-login-field,
        [data-elementor-type="popup"] .ajax-login-form .ajax-login-field {
            display: flex !important;
            visibility: visible !important;
            opacity: 1 !important;
            height: auto !important;
            max-height: none !important;
            overflow: visible !important;
        }

        .ajax-login-form-wrapper {
            max-width: 400px !important;
            margin: 0 auto !important;
            box-sizing: border-box !important;
        }
        #ajax-login-form,
        .ajax-login-form {
            display: flex !important;
            flex-direction: column !important;
            gap: 20px !important;
        }
        #ajax-login-form .ajax-login-field,
        .ajax-login-form .ajax-login-field {
            display: flex !important;
            flex-direction: column !important;
            gap: 8px !important;
        }

        /* Label styles with ID selectors */
        #ajax-login-form .ajax-login-field label,
        #ajax-login-form label[for="ajax-login-username"],
        #ajax-login-form label[for="ajax-login-password"],
        .ajax-login-form .ajax-login-field label {
            font-family: "Work Sans", sans-serif !important;
            font-weight: 500 !important;
            font-size: 12px !important;
            color: #B1B1B1 !important;
            margin: 0 !important;
            padding: 0 !important;
            line-height: 100% !important;
            letter-spacing: 0% !important;
        }

        /* Input styles with ID selectors */
        #ajax-login-username,
        #ajax-login-password,
        #ajax-login-form .ajax-login-field input[type="text"],
        #ajax-login-form .ajax-login-field input[type="password"],
        .ajax-login-form .ajax-login-field input[type="text"],
        .ajax-login-form .ajax-login-field input[type="password"] {
            padding: 12px 16px !important;
            border: 1px solid #EBEBE6 !important;
            border-radius: 6px !important;
            font-family: "Work Sans", sans-serif !important;
            font-size: 14px !important;
            transition: border-color 0.3s ease !important;
            width: 100% !important;
            box-sizing: border-box !important;
            background: #FFFFFF !important;
            color: #2C2C2C !important;
            line-height: 1.5 !important;
            box-shadow: 1px 2px 6px 0px rgba(0, 0, 0, 0.15) inset !important;
        }
        #ajax-login-username:focus,
        #ajax-login-password:focus,
        #ajax-login-form .ajax-login-field input[type="text"]:focus,
        #ajax-login-form .ajax-login-field input[type="password"]:focus,
        .ajax-login-form .ajax-login-field input[type="text"]:focus,
        .ajax-login-form .ajax-login-field input[type="password"]:focus {
            outline: none !important;
            border-color: #0165A0 !important;
        }

        /* Error state for input fields */
        .ajax-login-form .ajax-login-field input.ajax-error {
            border-color: #f44336 !important;
            background-color: #fff5f5 !important;
        }

        /* Forgot password link styling */
        .ajax-login-forgot-password {
            margin-top: 8px !important;
        }
        .ajax-login-forgot-password a {
            font-family: "Work Sans", sans-serif !important;
            font-weight: 500 !important;
            font-size: 12px !important;
            line-height: 160% !important;
            letter-spacing: 0% !important;
            text-align: left !important;
            color: #B1B1B1 !important;
            text-decoration: none !important;
            display: block !important;
        }
        .ajax-login-forgot-password a:hover {
            text-decoration: underline !important;
        }

        /* Button container to align right */
        #ajax-login-form button[type="submit"] {
            margin-left: auto !important;
        }

        #ajax-login-submit,
        .ajax-login-form .ajax-login-submit {
            background: #0165A0 !important;
            color: #FFFFFF !important;
            padding: 10px 24px !important;
            border: none !important;
            border-radius: 30px !important;
            font-family: "Work Sans", sans-serif !important;
            font-weight: 600 !important;
            font-size: 14px !important;
            text-transform: uppercase !important;
            cursor: pointer !important;
            transition: background 0.3s ease !important;
            width: 135px !important;
            line-height: 100% !important;
            letter-spacing: 0% !important;
            display: block !important;
        }
        #ajax-login-submit:hover,
        .ajax-login-form .ajax-login-submit:hover {
            background: #014d7a !important;
        }
        #ajax-login-submit:disabled,
        .ajax-login-form .ajax-login-submit:disabled {
            background: #ccc !important;
            cursor: not-allowed !important;
            opacity: 0.6 !important;
            pointer-events: none !important;
        }

        /* Loading state */
        .ajax-login-form.ajax-loading {
            position: relative !important;
            opacity: 0.6 !important;
            pointer-events: none !important;
        }
        .ajax-login-form.ajax-loading::before {
            content: '' !important;
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            width: 40px !important;
            height: 40px !important;
            margin: -20px 0 0 -20px !important;
            border: 3px solid #f3f3f3 !important;
            border-top: 3px solid #3498db !important;
            border-radius: 50% !important;
            animation: ajax-login-spin 1s linear infinite !important;
            z-index: 1000 !important;
        }
        @keyframes ajax-login-spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .ajax-login-form-wrapper .ajax-login-message {
            padding: 12px 15px !important;
            border-radius: 2px !important;
            font-family: "Work Sans", sans-serif !important;
            font-size: 14px !important;
            line-height: 1.5 !important;
            margin-bottom: 15px !important;
            display: none !important;
            position: relative !important;
            z-index: 10001 !important;
        }
        .ajax-login-form-wrapper .ajax-login-message.error {
            background-color: #ffebee !important;
            border-left: 4px solid #f44336 !important;
            color: #c62828 !important;
            display: block !important;
        }
        .ajax-login-form-wrapper .ajax-login-message.success {
            background-color: #e8f5e9 !important;
            border-left: 4px solid #4caf50 !important;
            color: #2e7d32 !important;
            display: block !important;
        }

        /* Ensure errors are visible in popups */
        .popup .ajax-login-message,
        .modal .ajax-login-message,
        [role="dialog"] .ajax-login-message {
            z-index: 10001 !important;
            position: relative !important;
        }

        .ajax-login-form .ajax-login-links {
            display: flex !important;
            flex-direction: column !important;
            gap: 10px !important;
            margin-top: 10px !important;
        }
        .ajax-login-form .ajax-login-links a {
            font-family: "Work Sans", sans-serif !important;
            font-size: 14px !important;
            color: #0165A0 !important;
            text-decoration: none !important;
            text-align: center !important;
        }
        .ajax-login-form .ajax-login-links a:hover {
            text-decoration: underline !important;
        }
    </style>

    <div class="ajax-login-form-wrapper">
        <div id="ajax-login-message" class="ajax-login-message"></div>

        <form id="ajax-login-form" class="ajax-login-form">
            <div class="ajax-login-field">
                <label for="ajax-login-username">Email</label>
                <input type="text" id="ajax-login-username" name="username" required autocomplete="username">
            </div>

            <div class="ajax-login-field">
                <label for="ajax-login-password">Password</label>
                <input type="password" id="ajax-login-password" name="password" required autocomplete="current-password">
                <div class="ajax-login-forgot-password">
                    <a href="https://kdn.coloredcow.com/password-reset/">Forgot Password?</a>
                </div>
            </div>

            <button type="submit" class="ajax-login-submit" id="ajax-login-submit">
                Log In
            </button>
        </form>
    </div>

    <script>
    (function() {
        var loginForm = document.getElementById('ajax-login-form');
        var submitButton = document.getElementById('ajax-login-submit');
        var messageDiv = document.getElementById('ajax-login-message');

        if (loginForm) {
            loginForm.addEventListener('submit', function(e) {
                e.preventDefault();

                // Disable submit button
                submitButton.disabled = true;
                submitButton.textContent = 'Logging in...';

                // Clear previous messages
                messageDiv.className = 'ajax-login-message';
                messageDiv.textContent = '';

                // Get form data
                var username = document.getElementById('ajax-login-username').value;
                var password = document.getElementById('ajax-login-password').value;

                // Create form data
                var formData = new FormData();
                formData.append('action', 'ajax_login');
                formData.append('username', username);
                formData.append('password', password);
                formData.append('remember', '0');
                formData.append('nonce', '<?php echo wp_create_nonce('ajax-login-nonce'); ?>');

                // Send AJAX request
                fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
                    method: 'POST',
                    body: formData
                })
                .then(function(response) {
                    return response.json();
                })
                .then(function(data) {
                    if (data.success) {
                        // Success
                        messageDiv.className = 'ajax-login-message success';
                        messageDiv.textContent = data.data.message;

                        // Redirect after 1 second
                        setTimeout(function() {
                            window.location.href = data.data.redirect;
                        }, 1000);
                    } else {
                        // Error
                        messageDiv.className = 'ajax-login-message error';
                        messageDiv.textContent = data.data.message;

                        // Re-enable submit button
                        submitButton.disabled = false;
                        submitButton.textContent = 'Log In';
                    }
                })
                .catch(function(error) {
                    // Network error
                    messageDiv.className = 'ajax-login-message error';
                    messageDiv.textContent = 'An error occurred. Please try again.';

                    // Re-enable submit button
                    submitButton.disabled = false;
                    submitButton.textContent = 'Log In';
                });
            });
        }
    })();
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode('ajax_login_form', 'ajax_login_form_shortcode');

// AJAX Login Handler
add_action('wp_ajax_nopriv_ajax_login', 'handle_ajax_login');
function handle_ajax_login() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax-login-nonce')) {
        wp_send_json_error(array('message' => 'Security check failed. Please refresh the page and try again.'));
    }

    // Get credentials
    $username = sanitize_text_field($_POST['username']);
    $password = $_POST['password'];
    $remember = isset($_POST['remember']) && $_POST['remember'] === '1';

    // Validate inputs
    if (empty($username) || empty($password)) {
        wp_send_json_error(array('message' => 'Please enter both username and password.'));
    }

    // Attempt login
    $creds = array(
        'user_login'    => $username,
        'user_password' => $password,
        'remember'      => $remember
    );

    $user = wp_signon($creds, is_ssl());

    if (is_wp_error($user)) {
        // Login failed
        $error_message = $user->get_error_message();

        // Customize error messages
        if (strpos($error_message, 'username') !== false) {
            $error_message = 'Invalid username or email address.';
        } elseif (strpos($error_message, 'password') !== false) {
            $error_message = 'Incorrect password.';
        }

        wp_send_json_error(array('message' => $error_message));
    } else {
        // Login successful
        wp_send_json_success(array(
            'message' => 'Login successful! Redirecting...',
            'redirect' => home_url()
        ));
    }
}
