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

// Global Variables
$user = wp_get_current_user();
$home_url = esc_url(home_url('/'));
$logout_nav_url = esc_url(wp_logout_url($home_url));
$page_kicker = sanitize_text_field((string) $this->get_event_hero_kicker_text());

// Setup UI Labels
$ui_labels = isset($ui_labels) && is_array($ui_labels) ? $ui_labels : [];
$profile_key = sanitize_key((string) ($ui_labels['profile_key'] ?? ''));
$available_tabs = isset($available_tabs) && is_array($available_tabs) ? array_values(array_filter(array_map('sanitize_key', $available_tabs))) : ['account', 'analytics', 'listings', 'submit', 'inbox', 'saved'];
if (empty($available_tabs)) {
    $available_tabs = ['account', 'analytics', 'listings', 'submit', 'inbox', 'saved'];
}
$show_analytics_tab = in_array('analytics', $available_tabs, true);
$show_listings_tab = in_array('listings', $available_tabs, true);
$show_submit_tab = in_array('submit', $available_tabs, true);
$show_inbox_tab = in_array('inbox', $available_tabs, true);
$show_saved_tab = in_array('saved', $available_tabs, true);
$show_account_tab = in_array('account', $available_tabs, true);
$initial_tab = sanitize_key((string) ($initial_tab ?? 'account'));
if (!in_array($initial_tab, $available_tabs, true)) {
    $initial_tab = $show_account_tab ? 'account' : (string) ($available_tabs[0] ?? 'analytics');
}
$requested_tab = isset($_GET['eep_tab']) ? sanitize_key((string) wp_unslash($_GET['eep_tab'])) : '';
if ($requested_tab !== '' && in_array($requested_tab, $available_tabs, true)) {
    $initial_tab = $requested_tab;
}
$is_events_profile = (string) ($ui_labels['is_events_profile'] ?? '1') === '1';

// Account Specific Variables
$account_description = isset($account_description) ? (string) $account_description : (string) ($ui_labels['account_description'] ?? __('Update your profile and manage your listing activity.', 'nexdirectory'));
$gdpr_marketing_opt_in = !empty($gdpr_marketing_opt_in);
$event_messages_enabled = !isset($event_messages_enabled) || !empty($event_messages_enabled);
$gdpr_terms_accepted_label = isset($gdpr_terms_accepted_label) ? sanitize_text_field((string) $gdpr_terms_accepted_label) : '';
$team_access_events = isset($team_access_events) && is_array($team_access_events) ? $team_access_events : [];
$selected_team_access_event_id = isset($selected_team_access_event_id) ? absint((int) $selected_team_access_event_id) : 0;
$team_access_members = isset($team_access_members) && is_array($team_access_members) ? $team_access_members : [];
$team_access_followers = isset($team_access_followers) && is_array($team_access_followers) ? $team_access_followers : [];
$team_access_can_manage_selected = !empty($team_access_can_manage_selected);
$team_access_manage_action = isset($team_access_manage_action) ? esc_url((string) $team_access_manage_action) : esc_url(admin_url('admin-post.php'));
$team_access_base_url = isset($team_access_base_url) ? esc_url((string) $team_access_base_url) : esc_url(eep_add_query_arg(['eep_tab' => 'account', 'account_subtab' => 'team-access'], $home_url) . '#account');
$team_access_selected_url = isset($team_access_selected_url) ? esc_url((string) $team_access_selected_url) : $team_access_base_url;
$initial_account_subtab = isset($_GET['account_subtab']) ? sanitize_key((string) wp_unslash($_GET['account_subtab'])) : 'profile';
if (!in_array($initial_account_subtab, ['profile', 'team-access'], true)) {
    $initial_account_subtab = 'profile';
}

echo $this->render_notice();
?>

<script src="https://cdn.tailwindcss.com"></script>
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/intersect@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/collapse@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

<style>
    :root {
        --eep-page-side-padding: clamp(10px, 2.2vw, 28px);
        --eep-page-side-padding-mobile: 12px;
    }
    .pb-safe { padding-bottom: env(safe-area-inset-bottom); }
    .eep-account-action-btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        min-height: 2.5rem;
        padding: 0.5rem 0.875rem;
        border-radius: 0.75rem;
        border: 1px solid #e5e7eb;
        background: #f8fafc;
        color: #374151;
        font-size: 0.75rem;
        font-weight: 600;
        line-height: 1;
        white-space: nowrap;
        transition: background-color 160ms ease, border-color 160ms ease, color 160ms ease, transform 160ms ease;
    }
    .eep-account-action-btn:hover {
        background: #f1f5f9;
        border-color: #cbd5e1;
        color: #111827;
    }
    .eep-account-action-btn-danger {
        background: #dc2626;
        border-color: #dc2626;
        color: #ffffff;
    }
    .eep-account-action-btn-danger:hover {
        background: #b91c1c;
        border-color: #b91c1c;
        color: #ffffff;
    }
</style>

<script>
    tailwind.config = {
        theme: {
            extend: {
                fontFamily: { sans: ['Inter', 'sans-serif'] },
                colors: {
                    brand: {
                        50: 'color-mix(in srgb, var(--eep-primary) 8%, #ffffff)',
                        100: 'color-mix(in srgb, var(--eep-primary) 14%, #ffffff)',
                        300: 'color-mix(in srgb, var(--eep-primary) 36%, #ffffff)',
                        500: 'var(--eep-primary)',
                        600: 'var(--eep-primary-hover)',
                        700: 'color-mix(in srgb, var(--eep-primary-hover) 80%, #000000)',
                        800: 'color-mix(in srgb, var(--eep-primary-hover) 64%, #000000)',
                        900: 'color-mix(in srgb, var(--eep-primary-hover) 48%, #000000)'
                    }
                }
            }
        },
        plugins: [
            function ({ addUtilities }) {
                addUtilities({
                    '.scrollbar-hide': {
                        '-ms-overflow-style': 'none',
                        'scrollbar-width': 'none',
                        '&::-webkit-scrollbar': { display: 'none' }
                    }
                })
            }
        ]
    }

    document.addEventListener('alpine:init', () => {
        const initialTab = <?php echo wp_json_encode($initial_tab); ?>;
        const allowedTabs = <?php echo wp_json_encode($available_tabs); ?>;
        const clearSubmitDraftStorage = () => {
            try {
                window.localStorage.removeItem('eep_submit_draft');
                window.localStorage.removeItem('eep_submit_form_state_v1');
            } catch (e) {}
        };
        const normalizeTab = (candidate) => {
            const tab = String(candidate || '').toLowerCase();
            return allowedTabs.includes(tab) ? tab : initialTab;
        };
        const getTabFromUrl = () => {
            const params = new URLSearchParams(window.location.search || '');
            const fromQuery = params.get('eep_tab');
            if (fromQuery && allowedTabs.includes(String(fromQuery).toLowerCase())) {
                return String(fromQuery).toLowerCase();
            }
            if (window.location.hash) {
                return normalizeTab(window.location.hash.substring(1));
            }
            return initialTab;
        };
        const setTabInUrl = (tab, options = {}) => {
            const clearEditContext = !!(options && options.clearEditContext);
            const url = new URL(window.location.href);
            url.searchParams.set('eep_tab', tab);
            if (clearEditContext) {
                url.searchParams.delete('edit_event_id');
            }
            if (url.hash) {
                url.hash = '';
            }
            window.history.replaceState({}, '', url.toString());
        };

        Alpine.data('accountApp', () => ({
            activeTab: normalizeTab(getTabFromUrl()),
            clearSubmitEditContext: false,
            init() {
                window.addEventListener('popstate', () => {
                    this.activeTab = normalizeTab(getTabFromUrl());
                });
                window.addEventListener('eep:account:set-tab', (event) => {
                    const requested = event && event.detail ? event.detail.tab : '';
                    this.activeTab = normalizeTab(requested);
                });
                this.$watch('activeTab', value => {
                    const normalized = normalizeTab(value);
                    setTabInUrl(normalized, { clearEditContext: normalized === 'submit' && this.clearSubmitEditContext });
                    this.clearSubmitEditContext = false;
                });
            },
            setTab(tab) {
                const normalized = normalizeTab(tab);
                if (normalized === 'submit') {
                    clearSubmitDraftStorage();
                    const submitUrl = new URL(window.location.href);
                    submitUrl.searchParams.set('eep_tab', 'submit');
                    submitUrl.searchParams.delete('edit_event_id');
                    submitUrl.searchParams.set('eep_new', '1');
                    submitUrl.hash = 'submit';
                    window.location.assign(submitUrl.toString());
                    return;
                }
                this.clearSubmitEditContext = normalized === 'submit';
                this.activeTab = normalized;
            }
        }))
    });
</script>

<div class="bg-gray-50 text-gray-800 font-sans antialiased selection:bg-brand-100 selection:text-brand-700 min-h-screen flex flex-col md:flex-row pb-24 md:pb-0" x-data="accountApp()">

    <aside class="hidden md:flex w-64 flex-col bg-white border-r border-gray-200 h-screen sticky top-0 shrink-0 z-40 shadow-sm">
        <div class="p-6 border-b border-gray-100">
            <p class="text-[10px] font-semibold text-brand-500 uppercase tracking-wider mb-0.5"><?php echo esc_html($page_kicker); ?></p>
            <a href="<?php echo $home_url; ?>" class="font-bold text-xl tracking-tighter text-gray-900 active:scale-95 transition-transform duration-200">
                Workspace
            </a>
            <p class="text-xs text-gray-500 mt-1 truncate">Welcome, <?php echo esc_html($user->display_name); ?></p>
        </div>
        <nav class="flex-1 p-4 space-y-1 overflow-y-auto">
            <?php if ($show_analytics_tab) : ?>
            <button type="button" @click="setTab('analytics')" :class="activeTab === 'analytics' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'analytics' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path></svg>
                <span>Dashboard</span>
            </button>
            <?php endif; ?>
            <?php if ($show_listings_tab) : ?>
            <button type="button" @click="setTab('listings')" :class="activeTab === 'listings' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'listings' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path></svg>
                <span>My Listings</span>
            </button>
            <?php endif; ?>
            <?php if ($show_submit_tab) : ?>
            <button type="button" @click="setTab('submit')" :class="activeTab === 'submit' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'submit' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                <span>Add New</span>
            </button>
            <?php endif; ?>
            <?php if ($show_inbox_tab) : ?>
            <button type="button" @click="setTab('inbox')" :class="activeTab === 'inbox' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'inbox' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                <span>Messages</span>
            </button>
            <?php endif; ?>
            <?php if ($show_saved_tab) : ?>
            <button type="button" @click="setTab('saved')" :class="activeTab === 'saved' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'saved' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"></path></svg>
                <span>Saved & Attending</span>
            </button>
            <?php endif; ?>
            <?php if ($show_account_tab) : ?>
            <button type="button" @click="setTab('account')" :class="activeTab === 'account' ? 'bg-brand-50 text-brand-600 font-semibold' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'" class="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-[13px] transition-all text-left">
                <svg class="w-5 h-5" :class="activeTab === 'account' ? 'text-brand-500' : 'text-gray-400'" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path></svg>
                <span>Account Settings</span>
            </button>
            <?php endif; ?>
        </nav>
        <div class="p-4 border-t border-gray-100">
            <a href="<?php echo $logout_nav_url; ?>" class="eep-force-accent-action w-full flex items-center justify-center gap-2 py-2.5 px-4 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm font-semibold rounded-xl transition-all shadow-sm">
                Logout
            </a>
        </div>
    </aside>

    <header class="md:hidden bg-white/90 backdrop-blur-md border-b border-gray-200 sticky top-0 z-40 px-4 py-3 flex items-center justify-between">
        <h1 class="font-bold text-lg text-gray-900 capitalize" x-text="activeTab.replace('-', ' ')">Workspace</h1>
        <div class="w-8 h-8 rounded-full bg-brand-100 text-brand-600 flex items-center justify-center font-bold text-xs uppercase shadow-sm border border-brand-200">
            <?php echo esc_html(substr($user->display_name, 0, 2)); ?>
        </div>
    </header>

    <main class="eep-workspace-main flex-1 min-w-0 w-full max-w-none p-4 sm:p-6 lg:p-8">

        <?php if ($show_account_tab) : ?>
        <section x-show="activeTab === 'account'" x-transition.opacity.duration.300ms x-cloak x-data="{ accountSubTab: '<?php echo esc_attr($initial_account_subtab); ?>' }">
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6 sm:mb-8">
                <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php esc_html_e('Account Management', 'nexdirectory'); ?></h2>
                <p class="text-sm sm:text-base text-gray-500 max-w-2xl"><?php echo esc_html($account_description); ?></p>
            </div>

            <div class="flex items-center gap-2 mb-4 p-1 bg-gray-200/50 rounded-xl inline-flex w-full sm:w-auto overflow-x-auto scrollbar-hide">
                <button type="button" @click="accountSubTab = 'profile'" :class="accountSubTab === 'profile' ? 'bg-white text-gray-900 shadow-sm font-semibold' : 'text-gray-500 hover:text-gray-700 font-medium'" class="flex-1 sm:flex-none px-4 py-2 rounded-lg text-sm transition-all whitespace-nowrap">
                    <?php esc_html_e('Profile', 'nexdirectory'); ?>
                </button>
                <button type="button" @click="accountSubTab = 'team-access'" :class="accountSubTab === 'team-access' ? 'bg-white text-indigo-700 shadow-sm font-semibold' : 'text-gray-500 hover:text-gray-700 font-medium'" class="flex-1 sm:flex-none px-4 py-2 rounded-lg text-sm transition-all whitespace-nowrap">
                    <?php esc_html_e('Team Access', 'nexdirectory'); ?>
                </button>
            </div>

            <div x-show="accountSubTab === 'profile'" x-transition.opacity.duration.300ms>
                <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-100 bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden max-w-3xl">
                    <div class="border-b border-gray-100 px-5 sm:px-6 py-4 sm:py-5 bg-gray-50/50 flex items-center justify-between">
                        <h3 class="text-lg font-bold text-gray-900 flex items-center gap-2">
                            <svg class="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                            <?php esc_html_e('Profile Details', 'nexdirectory'); ?>
                        </h3>
                    </div>

                    <div class="p-5 sm:p-6">
                        <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'account', admin_url('admin-post.php'))); ?>#account" class="space-y-6">
                            <input type="hidden" name="action" value="eep_account_update">
                            <?php wp_nonce_field('eep_account_update_nonce', 'eep_account_nonce'); ?>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1.5"><?php esc_html_e('Username', 'nexdirectory'); ?></label>
                                    <input type="text" value="<?php echo esc_attr($user->user_login); ?>" disabled class="w-full px-4 py-3 rounded-xl border border-gray-200 bg-gray-50 text-gray-500 cursor-not-allowed outline-none text-sm shadow-sm">
                                </div>

                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1.5"><?php esc_html_e('Display Name', 'nexdirectory'); ?></label>
                                    <input type="text" name="display_name" value="<?php echo esc_attr($user->display_name); ?>" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-sm transition-all shadow-sm">
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5"><?php esc_html_e('Email Address', 'nexdirectory'); ?></label>
                                <input type="email" name="user_email" value="<?php echo esc_attr($user->user_email); ?>" required class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-sm transition-all shadow-sm">
                            </div>

                            <div class="bg-gray-50 rounded-xl p-4 sm:p-5 border border-gray-100">
                                <h4 class="font-semibold text-gray-900 mb-2"><?php esc_html_e('Communication & GDPR', 'nexdirectory'); ?></h4>
                                <p class="text-xs sm:text-sm text-gray-500 mb-4"><?php esc_html_e('Essential event-account emails (verification, moderation, RSVP/system updates) remain enabled for platform operation.', 'nexdirectory'); ?></p>
                                
                                <label class="flex items-start gap-3 cursor-pointer group mb-3">
                                    <div class="mt-0.5">
                                        <input type="checkbox" name="eep_gdpr_marketing_opt_in" value="1" <?php checked($gdpr_marketing_opt_in, true); ?> class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                    </div>
                                    <span class="text-sm text-gray-700 group-hover:text-gray-900 transition-colors"><?php esc_html_e('Allow organizer announcements and platform news emails (non-essential).', 'nexdirectory'); ?></span>
                                </label>

                                <?php if ($is_events_profile) : ?>
                                    <input type="hidden" name="eep_event_messages_enabled" value="0">
                                    <label class="flex items-start gap-3 cursor-pointer group">
                                        <div class="mt-0.5">
                                            <input type="checkbox" name="eep_event_messages_enabled" value="1" <?php checked($event_messages_enabled, true); ?> class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                        </div>
                                        <span class="text-sm text-gray-700 group-hover:text-gray-900 transition-colors"><?php esc_html_e('Show the Message button on my event pages.', 'nexdirectory'); ?></span>
                                    </label>
                                    <p class="text-xs text-gray-500 mt-2"><?php esc_html_e('If disabled, visitors will no longer see Message and the Visit Event Site button will expand to full width.', 'nexdirectory'); ?></p>
                                <?php endif; ?>

                                <?php if ($gdpr_terms_accepted_label !== '') : ?>
                                    <p class="text-xs text-brand-600 font-medium bg-brand-50 inline-block px-2.5 py-1 rounded-md border border-brand-100">
                                        <?php echo esc_html(sprintf(__('GDPR acceptance recorded: %s', 'nexdirectory'), $gdpr_terms_accepted_label)); ?>
                                    </p>
                                <?php endif; ?>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1.5"><?php esc_html_e('New Password (optional)', 'nexdirectory'); ?></label>
                                <input type="password" name="new_pass" autocomplete="new-password" placeholder="••••••••" class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none text-sm transition-all shadow-sm">
                            </div>

                            <div class="pt-4 border-t border-gray-100 flex items-center justify-end">
                                <button type="submit" class="eep-force-accent-action w-full sm:w-auto bg-gray-900 hover:bg-black active:scale-95 text-white px-8 py-3 rounded-xl text-sm font-semibold transition-all shadow-sm">
                                    <?php esc_html_e('Save Account Settings', 'nexdirectory'); ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div x-show="accountSubTab === 'team-access'" x-transition.opacity.duration.300ms style="display:none;">
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                    <div class="p-5 sm:p-6 border-b border-gray-100 bg-gray-50/50">
                        <h3 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Team Access', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500"><?php esc_html_e('Invite by email or followers, assign roles, choose event/app scope, and manage per-event access.', 'nexdirectory'); ?></p>
                    </div>

                    <div class="p-5 sm:p-6 space-y-6">
                        <?php if (empty($team_access_events)) : ?>
                            <div class="rounded-xl border border-gray-200 bg-gray-50 px-4 py-4 text-sm text-gray-600">
                                <?php esc_html_e('No events are available yet. Create your first event to configure team access.', 'nexdirectory'); ?>
                            </div>
                        <?php else : ?>
                            <?php $team_events_page_url = (isset($my_events_url) && is_string($my_events_url) && $my_events_url !== '') ? $my_events_url : home_url('/'); ?>
                            <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
                                <div class="lg:col-span-2">
                                    <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Selected Event', 'nexdirectory'); ?></label>
                                    <select onchange="window.location.href=this.value;" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                        <?php foreach ($team_access_events as $team_event_option) : ?>
                                            <?php
                                            $team_event_option = is_array($team_event_option) ? $team_event_option : [];
                                            $team_event_id = absint((int) ($team_event_option['id'] ?? 0));
                                            if ($team_event_id <= 0) {
                                                continue;
                                            }
                                            $team_event_url = eep_add_query_arg([
                                                'eep_tab' => 'account',
                                                'account_subtab' => 'team-access',
                                                'team_event' => $team_event_id,
                                            ], $team_events_page_url) . '#account';
                                            $team_event_title = sanitize_text_field((string) ($team_event_option['title'] ?? ''));
                                            if ($team_event_title === '') {
                                                $team_event_title = sprintf(__('Event #%d', 'nexdirectory'), $team_event_id);
                                            }
                                            $team_event_status = sanitize_key((string) ($team_event_option['status'] ?? ''));
                                            $team_event_date = sanitize_text_field((string) ($team_event_option['date_label'] ?? ''));
                                            $team_event_label = $team_event_title;
                                            if ($team_event_date !== '') {
                                                $team_event_label .= ' - ' . $team_event_date;
                                            }
                                            if ($team_event_status !== '') {
                                                $team_event_label .= ' (' . ucfirst($team_event_status) . ')';
                                            }
                                            ?>
                                            <option value="<?php echo esc_url($team_event_url); ?>" <?php selected($selected_team_access_event_id, $team_event_id); ?>><?php echo esc_html($team_event_label); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="lg:col-span-1 flex flex-col justify-end gap-2">
                                    <a href="<?php echo esc_url($team_access_base_url); ?>" class="inline-flex items-center justify-center px-4 py-3 rounded-xl border border-gray-300 text-sm font-semibold text-gray-700 bg-white hover:bg-gray-50 transition-colors">
                                        <?php esc_html_e('Reset Event', 'nexdirectory'); ?>
                                    </a>
                                </div>
                            </div>

                            <?php if ($selected_team_access_event_id > 0 && $team_access_can_manage_selected) : ?>
                                <form method="post" action="<?php echo esc_url($team_access_manage_action); ?>" class="space-y-5 border border-gray-200 rounded-xl p-4 bg-gray-50/50">
                                    <input type="hidden" name="action" value="eep_invite_event_team_member">
                                    <input type="hidden" name="event_id" value="<?php echo esc_attr((string) $selected_team_access_event_id); ?>">
                                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($team_access_selected_url); ?>">
                                    <input type="hidden" name="team_status" value="invited">
                                    <?php wp_nonce_field('eep_event_team_invite_' . $selected_team_access_event_id, 'eep_event_team_invite_nonce'); ?>

                                    <div class="grid grid-cols-1 md:grid-cols-4 gap-3">
                                        <div class="md:col-span-2">
                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Invite by Email', 'nexdirectory'); ?></label>
                                            <input id="eep-team-email-input" type="email" name="team_email" placeholder="member@example.com" class="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Role', 'nexdirectory'); ?></label>
                                            <select name="team_role" class="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                                <option value="owner"><?php esc_html_e('Owner', 'nexdirectory'); ?></option>
                                                <option value="editor" selected><?php esc_html_e('Editor', 'nexdirectory'); ?></option>
                                                <option value="app_moderator"><?php esc_html_e('App Moderator', 'nexdirectory'); ?></option>
                                                <option value="support"><?php esc_html_e('Support', 'nexdirectory'); ?></option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Followers', 'nexdirectory'); ?></label>
                                            <select name="team_follower_user_id" onchange="var opt=this.options[this.selectedIndex];var email=opt?opt.getAttribute('data-email'):'';var input=document.getElementById('eep-team-email-input');if(input&&email){input.value=email;}" class="w-full px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                                <option value=""><?php esc_html_e('Select follower', 'nexdirectory'); ?></option>
                                                <?php foreach ($team_access_followers as $follower_row) : ?>
                                                    <?php
                                                    $follower_row = is_array($follower_row) ? $follower_row : [];
                                                    $follower_user_id = absint((int) ($follower_row['user_id'] ?? 0));
                                                    $follower_email = sanitize_email((string) ($follower_row['email'] ?? ''));
                                                    if ($follower_user_id <= 0 || $follower_email === '') {
                                                        continue;
                                                    }
                                                    $follower_name = sanitize_text_field((string) ($follower_row['name'] ?? $follower_email));
                                                    ?>
                                                    <option value="<?php echo esc_attr((string) $follower_user_id); ?>" data-email="<?php echo esc_attr($follower_email); ?>">
                                                        <?php echo esc_html($follower_name . ' - ' . $follower_email); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                                        <div class="border border-gray-200 rounded-xl p-4 bg-white">
                                            <p class="text-sm font-semibold text-gray-900 mb-2"><?php esc_html_e('Access Scope', 'nexdirectory'); ?></p>
                                            <label class="flex items-center gap-2 text-sm text-gray-700 mb-2">
                                                <input type="hidden" name="team_scope_website" value="0">
                                                <input type="checkbox" name="team_scope_website" value="1" checked class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                                <?php esc_html_e('Website permissions', 'nexdirectory'); ?>
                                            </label>
                                            <label class="flex items-center gap-2 text-sm text-gray-700">
                                                <input type="hidden" name="team_scope_webapp" value="0">
                                                <input type="checkbox" name="team_scope_webapp" value="1" checked class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                                <?php esc_html_e('Web App permissions', 'nexdirectory'); ?>
                                            </label>
                                        </div>
                                        <div class="border border-gray-200 rounded-xl p-4 bg-white">
                                            <p class="text-sm font-semibold text-gray-900 mb-2"><?php esc_html_e('Apply To Events', 'nexdirectory'); ?></p>
                                            <div class="max-h-36 overflow-y-auto pr-1 space-y-1">
                                                <?php foreach ($team_access_events as $team_event_option) : ?>
                                                    <?php
                                                    $team_event_option = is_array($team_event_option) ? $team_event_option : [];
                                                    $team_event_id = absint((int) ($team_event_option['id'] ?? 0));
                                                    if ($team_event_id <= 0) {
                                                        continue;
                                                    }
                                                    $team_event_title = sanitize_text_field((string) ($team_event_option['title'] ?? ''));
                                                    if ($team_event_title === '') {
                                                        $team_event_title = sprintf(__('Event #%d', 'nexdirectory'), $team_event_id);
                                                    }
                                                    $team_event_checked = $selected_team_access_event_id > 0 ? ($team_event_id === $selected_team_access_event_id) : true;
                                                    ?>
                                                    <label class="flex items-center gap-2 text-sm text-gray-700">
                                                        <input type="checkbox" name="team_event_ids[]" value="<?php echo esc_attr((string) $team_event_id); ?>" <?php checked($team_event_checked); ?> class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                                        <span class="truncate"><?php echo esc_html($team_event_title); ?></span>
                                                    </label>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 pt-1">
                                        <p class="text-xs text-gray-500"><?php esc_html_e('Invites are sent automatically by email. The invitee must accept to become active.', 'nexdirectory'); ?></p>
                                        <button type="submit" class="inline-flex items-center justify-center px-5 py-2.5 bg-brand-600 hover:bg-brand-700 text-white text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95" style="color:#ffffff !important;">
                                            <?php esc_html_e('Send Invite', 'nexdirectory'); ?>
                                        </button>
                                    </div>
                                </form>
                            <?php endif; ?>

                            <?php if ($selected_team_access_event_id > 0) : ?>
                                <div>
                                    <h4 class="text-sm font-bold text-gray-900 mb-3"><?php esc_html_e('Current Team Members', 'nexdirectory'); ?></h4>
                                    <?php if (!empty($team_access_members)) : ?>
                                        <div class="space-y-3">
                                            <?php foreach ($team_access_members as $team_member) : ?>
                                                <?php
                                                $team_member = is_array($team_member) ? $team_member : [];
                                                $member_id = sanitize_text_field((string) ($team_member['id'] ?? ''));
                                                if ($member_id === '') {
                                                    continue;
                                                }
                                                $member_email = sanitize_email((string) ($team_member['email'] ?? ''));
                                                $member_display_name = sanitize_text_field((string) ($team_member['display_name'] ?? __('Member', 'nexdirectory')));
                                                $member_role = sanitize_key((string) ($team_member['role'] ?? 'support'));
                                                $member_status = sanitize_key((string) ($team_member['status'] ?? 'invited'));
                                                $member_scope_website = (string) ($team_member['scope_website'] ?? '1') === '1' ? '1' : '0';
                                                $member_scope_webapp = (string) ($team_member['scope_webapp'] ?? '1') === '1' ? '1' : '0';
                                                $member_scope_label = sanitize_text_field((string) ($team_member['scope_label'] ?? ''));
                                                $is_primary_owner = !empty($team_member['is_primary_owner']);
                                                $invited_ts = strtotime((string) ($team_member['invited_at'] ?? ''));
                                                $accepted_ts = strtotime((string) ($team_member['accepted_at'] ?? ''));
                                                $status_class = $member_status === 'active'
                                                    ? 'bg-green-50 text-green-700 border-green-200'
                                                    : ($member_status === 'disabled' ? 'bg-gray-100 text-gray-600 border-gray-200' : 'bg-amber-50 text-amber-700 border-amber-200');
                                                ?>
                                                <div class="border border-gray-200 rounded-xl p-4 bg-white shadow-sm">
                                                    <div class="flex flex-col xl:flex-row gap-4 xl:items-center xl:justify-between">
                                                        <div class="min-w-0">
                                                            <div class="flex items-center gap-2 flex-wrap">
                                                                <h5 class="font-semibold text-gray-900 truncate"><?php echo esc_html($member_display_name); ?></h5>
                                                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo esc_attr($status_class); ?>">
                                                                    <?php echo esc_html(sanitize_text_field((string) ($team_member['status_label'] ?? ucfirst($member_status)))); ?>
                                                                </span>
                                                                <?php if ($member_scope_label !== '') : ?>
                                                                    <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border bg-indigo-50 text-indigo-700 border-indigo-200">
                                                                        <?php echo esc_html($member_scope_label); ?>
                                                                    </span>
                                                                <?php endif; ?>
                                                            </div>
                                                            <p class="text-sm text-gray-500 truncate"><?php echo esc_html($member_email !== '' ? $member_email : __('No email', 'nexdirectory')); ?></p>
                                                            <div class="flex items-center gap-4 text-[11px] text-gray-400 mt-1 flex-wrap">
                                                                <span><?php echo esc_html($invited_ts ? sprintf(__('Invited %s', 'nexdirectory'), wp_date(get_option('date_format') . ' ' . get_option('time_format'), $invited_ts)) : __('Invite date unavailable', 'nexdirectory')); ?></span>
                                                                <?php if ($accepted_ts) : ?>
                                                                    <span><?php echo esc_html(sprintf(__('Accepted %s', 'nexdirectory'), wp_date(get_option('date_format') . ' ' . get_option('time_format'), $accepted_ts))); ?></span>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>

                                                        <?php if ($team_access_can_manage_selected) : ?>
                                                        <div class="w-full xl:w-auto flex flex-col gap-2">
                                                            <form method="post" action="<?php echo esc_url($team_access_manage_action); ?>" class="flex flex-col sm:flex-row sm:items-center gap-2">
                                                                <input type="hidden" name="action" value="eep_update_event_team_member">
                                                                <input type="hidden" name="event_id" value="<?php echo esc_attr((string) $selected_team_access_event_id); ?>">
                                                                <input type="hidden" name="member_id" value="<?php echo esc_attr($member_id); ?>">
                                                                <input type="hidden" name="redirect_to" value="<?php echo esc_attr($team_access_selected_url); ?>">
                                                                <?php wp_nonce_field('eep_event_team_manage_' . $selected_team_access_event_id, 'eep_event_team_manage_nonce'); ?>
                                                                <select name="team_role" class="px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none">
                                                                    <option value="owner" <?php selected($member_role, 'owner'); ?>><?php esc_html_e('Owner', 'nexdirectory'); ?></option>
                                                                    <option value="editor" <?php selected($member_role, 'editor'); ?>><?php esc_html_e('Editor', 'nexdirectory'); ?></option>
                                                                    <option value="app_moderator" <?php selected($member_role, 'app_moderator'); ?>><?php esc_html_e('App Moderator', 'nexdirectory'); ?></option>
                                                                    <option value="support" <?php selected($member_role, 'support'); ?>><?php esc_html_e('Support', 'nexdirectory'); ?></option>
                                                                </select>
                                                                <select name="team_status" class="px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none">
                                                                    <option value="invited" <?php selected($member_status, 'invited'); ?>><?php esc_html_e('Invited', 'nexdirectory'); ?></option>
                                                                    <option value="active" <?php selected($member_status, 'active'); ?>><?php esc_html_e('Active', 'nexdirectory'); ?></option>
                                                                    <option value="disabled" <?php selected($member_status, 'disabled'); ?>><?php esc_html_e('Disabled', 'nexdirectory'); ?></option>
                                                                </select>
                                                                <label class="inline-flex items-center gap-1 text-xs text-gray-700 whitespace-nowrap">
                                                                    <input type="hidden" name="team_scope_website" value="0">
                                                                    <input type="checkbox" name="team_scope_website" value="1" <?php checked($member_scope_website, '1'); ?> class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                                                    <?php esc_html_e('Website', 'nexdirectory'); ?>
                                                                </label>
                                                                <label class="inline-flex items-center gap-1 text-xs text-gray-700 whitespace-nowrap">
                                                                    <input type="hidden" name="team_scope_webapp" value="0">
                                                                    <input type="checkbox" name="team_scope_webapp" value="1" <?php checked($member_scope_webapp, '1'); ?> class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500">
                                                                    <?php esc_html_e('Web App', 'nexdirectory'); ?>
                                                                </label>
                                                                <button type="submit" class="px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 border border-gray-200 rounded-lg text-sm font-semibold transition-colors active:scale-95">
                                                                    <?php esc_html_e('Update', 'nexdirectory'); ?>
                                                                </button>
                                                            </form>
                                                            <?php if (!$is_primary_owner) : ?>
                                                                <form method="post" action="<?php echo esc_url($team_access_manage_action); ?>" onsubmit="return confirm('<?php echo esc_js(__('Remove this team member?', 'nexdirectory')); ?>');">
                                                                    <input type="hidden" name="action" value="eep_remove_event_team_member">
                                                                    <input type="hidden" name="event_id" value="<?php echo esc_attr((string) $selected_team_access_event_id); ?>">
                                                                    <input type="hidden" name="member_id" value="<?php echo esc_attr($member_id); ?>">
                                                                    <input type="hidden" name="redirect_to" value="<?php echo esc_attr($team_access_selected_url); ?>">
                                                                    <?php wp_nonce_field('eep_event_team_manage_' . $selected_team_access_event_id, 'eep_event_team_manage_nonce'); ?>
                                                                    <button type="submit" class="w-full px-3 py-2 bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 rounded-lg text-sm font-semibold transition-colors active:scale-95">
                                                                        <?php esc_html_e('Remove', 'nexdirectory'); ?>
                                                                    </button>
                                                                </form>
                                                            <?php endif; ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else : ?>
                                        <p class="text-sm text-gray-500"><?php esc_html_e('No team members yet. Invite collaborators above.', 'nexdirectory'); ?></p>
                                    <?php endif; ?>
                                </div>
                            <?php else : ?>
                                <p class="text-sm text-gray-500"><?php esc_html_e('Select an event to manage team access.', 'nexdirectory'); ?></p>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </section>
        <?php endif; ?>

<?php
        // Analytics specific variables mapping
        $analytics_title = isset($analytics_title) ? (string) $analytics_title : sanitize_text_field((string) ($ui_labels['owner_analytics_title'] ?? __('Analytics', 'nexdirectory')));
        $analytics_description = isset($analytics_description) ? (string) $analytics_description : sanitize_text_field((string) ($ui_labels['owner_analytics_description'] ?? __('Review listing views, clicks, enquiries, and discovery performance.', 'nexdirectory')));
        $report = isset($report) && is_array($report) ? $report : [];
        $totals = isset($report['totals']) && is_array($report['totals']) ? $report['totals'] : [];
        $analytics_rows = isset($report['rows']) && is_array($report['rows']) ? $report['rows'] : [];
        $comparison = isset($report['comparison']) && is_array($report['comparison']) ? $report['comparison'] : [];
        $deltas = isset($comparison['deltas']) && is_array($comparison['deltas']) ? $comparison['deltas'] : [];
        $boost_impact = isset($report['boost_impact']) && is_array($report['boost_impact']) ? $report['boost_impact'] : [];
        $boosted_metrics = isset($boost_impact['boosted']) && is_array($boost_impact['boosted']) ? $boost_impact['boosted'] : [];
        $non_boosted_metrics = isset($boost_impact['non_boosted']) && is_array($boost_impact['non_boosted']) ? $boost_impact['non_boosted'] : [];
        $boost_shares = isset($boost_impact['shares']) && is_array($boost_impact['shares']) ? $boost_impact['shares'] : [];
        $boost_uplift = isset($boost_impact['uplift']) && is_array($boost_impact['uplift']) ? $boost_impact['uplift'] : [];
        $trend_rows = isset($report['trend']) && is_array($report['trend']) ? $report['trend'] : [];
        $trend_meta = isset($report['trend_meta']) && is_array($report['trend_meta']) ? $report['trend_meta'] : [];
        $days = isset($days) ? absint((int) $days) : 30;
        $events_url = isset($events_url) ? (string) $events_url : $this->get_profile_route_default_url('events', $profile_key);
        
        $trend_display = $trend_rows;
        if (count($trend_display) > 30) { $trend_display = array_slice($trend_display, -30); }
        $trend_max = max(1, (int) ($trend_meta['max_value'] ?? 0));

        $delta_badge_class = static function ($delta_row) {
            $trend = sanitize_key((string) ($delta_row['trend'] ?? 'flat'));
            if ($trend === 'up') return 'bg-green-50 text-green-700 border-green-200';
            if ($trend === 'down') return 'bg-red-50 text-red-700 border-red-200';
            return 'bg-gray-100 text-gray-600 border-gray-200';
        };
        $delta_badge_text = static function ($delta_row) {
            $value = (float) ($delta_row['change_pct'] ?? 0);
            return ($value > 0 ? '+' : '') . number_format($value, 2);
        };
        $uplift_badge_class = static function ($value) {
            if ((float) $value > 0) return 'bg-green-50 text-green-700 border-green-200';
            if ((float) $value < 0) return 'bg-red-50 text-red-700 border-red-200';
            return 'bg-gray-100 text-gray-600 border-gray-200';
        };
        ?>
        <?php if ($show_analytics_tab) : ?>
        <section x-show="activeTab === 'analytics'" x-transition.opacity.duration.300ms x-cloak>
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6 sm:mb-8 flex flex-col lg:flex-row lg:items-end justify-between gap-4">
                <div>
                    <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php echo esc_html($analytics_title); ?></h2>
                    <p class="text-sm sm:text-base text-gray-500 max-w-2xl"><?php echo esc_html($analytics_description); ?></p>
                </div>

                <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                    <?php $current_url = esc_url_raw((string) $this->current_url()); ?>
                    <select onchange="window.location.href=this.value;" class="bg-white border border-gray-200 text-sm font-medium text-gray-700 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-brand-500 px-4 py-2.5 outline-none shadow-sm transition-all cursor-pointer">
                        <?php
                        $ranges = [7 => __('Last 7 days', 'nexdirectory'), 30 => __('Last 30 days', 'nexdirectory'), 90 => __('Last 90 days', 'nexdirectory'), 365 => __('Last 12 months', 'nexdirectory')];
                        foreach ($ranges as $range_value => $range_label) :
                            $range_url = eep_add_query_arg('eep_owner_days', (int) $range_value, eep_remove_query_arg('eep_owner_days', $current_url)) . '#analytics';
                            ?>
                            <option value="<?php echo esc_url($range_url); ?>" <?php selected($days, (int) $range_value); ?>><?php echo esc_html((string) $range_label); ?></option>
                        <?php endforeach; ?>
                    </select>

                    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="flex items-center gap-2">
                        <input type="hidden" name="action" value="eep_export_owner_analytics">
                        <input type="hidden" name="eep_owner_days" value="<?php echo esc_attr((string) $days); ?>">
                        <?php wp_nonce_field('eep_export_owner_analytics_nonce', 'eep_export_owner_analytics_nonce'); ?>
                        
                        <select name="eep_export_format" class="bg-white border border-gray-200 text-sm font-medium text-gray-700 rounded-xl focus:ring-2 focus:ring-brand-500 focus:border-brand-500 px-3 py-2.5 outline-none shadow-sm transition-all cursor-pointer">
                            <option value="csv">CSV</option>
                            <option value="json">JSON</option>
                        </select>
                        <button type="submit" class="eep-force-accent-action bg-gray-900 hover:bg-black active:scale-95 text-white px-5 py-2.5 rounded-xl text-sm font-semibold transition-all shadow-sm whitespace-nowrap">
                            <?php esc_html_e('Export', 'nexdirectory'); ?>
                        </button>
                    </form>
                </div>
            </div>

            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-100 grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6 sm:mb-8">
                <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors">
                    <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Listing Views', 'nexdirectory'); ?></span>
                    <div class="flex items-end justify-between gap-2 flex-wrap mt-2">
                        <strong class="text-2xl sm:text-3xl font-bold text-gray-900 leading-none"><?php echo esc_html((string) ((int) ($totals['listing_views'] ?? 0))); ?></strong>
                        <?php $views_delta = isset($deltas['listing_views']) && is_array($deltas['listing_views']) ? $deltas['listing_views'] : []; ?>
                        <small class="px-2 py-1 rounded-md text-[10px] sm:text-xs font-bold border <?php echo esc_attr($delta_badge_class($views_delta)); ?>">
                            <?php echo esc_html($delta_badge_text($views_delta)); ?>%
                        </small>
                    </div>
                </article>
                <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors">
                    <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Enquiries', 'nexdirectory'); ?></span>
                    <div class="flex items-end justify-between gap-2 flex-wrap mt-2">
                        <strong class="text-2xl sm:text-3xl font-bold text-gray-900 leading-none"><?php echo esc_html((string) ((int) ($totals['enquiries_received'] ?? 0))); ?></strong>
                        <?php $enquiries_delta = isset($deltas['enquiries_received']) && is_array($deltas['enquiries_received']) ? $deltas['enquiries_received'] : []; ?>
                        <small class="px-2 py-1 rounded-md text-[10px] sm:text-xs font-bold border <?php echo esc_attr($delta_badge_class($enquiries_delta)); ?>">
                            <?php echo esc_html($delta_badge_text($enquiries_delta)); ?>%
                        </small>
                    </div>
                </article>
                <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors">
                    <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Web Clicks', 'nexdirectory'); ?></span>
                    <div class="flex items-end justify-between gap-2 flex-wrap mt-2">
                        <strong class="text-2xl sm:text-3xl font-bold text-gray-900 leading-none"><?php echo esc_html((string) ((int) ($totals['click_website'] ?? 0))); ?></strong>
                        <?php $website_delta = isset($deltas['click_website']) && is_array($deltas['click_website']) ? $deltas['click_website'] : []; ?>
                        <small class="px-2 py-1 rounded-md text-[10px] sm:text-xs font-bold border <?php echo esc_attr($delta_badge_class($website_delta)); ?>">
                            <?php echo esc_html($delta_badge_text($website_delta)); ?>%
                        </small>
                    </div>
                </article>
                <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors">
                    <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Conversion', 'nexdirectory'); ?></span>
                    <div class="flex items-end justify-between gap-2 flex-wrap mt-2">
                        <strong class="text-2xl sm:text-3xl font-bold text-gray-900 leading-none"><?php echo esc_html(number_format((float) ($totals['conversion_rate'] ?? 0), 2)); ?>%</strong>
                        <?php $conversion_delta = isset($deltas['conversion_rate']) && is_array($deltas['conversion_rate']) ? $deltas['conversion_rate'] : []; ?>
                        <small class="px-2 py-1 rounded-md text-[10px] sm:text-xs font-bold border <?php echo esc_attr($delta_badge_class($conversion_delta)); ?>">
                            <?php echo esc_html($delta_badge_text($conversion_delta)); ?>%
                        </small>
                    </div>
                </article>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 sm:gap-8 mb-6 sm:mb-8">
                <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-200 lg:col-span-2 bg-white rounded-2xl border border-gray-100 shadow-sm p-5 sm:p-6 flex flex-col h-full">
                    <div class="mb-6">
                        <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('Views & Enquiries Trend', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500"><?php esc_html_e('Visual trend for your selected reporting window.', 'nexdirectory'); ?></p>
                    </div>
                    <?php if (!empty($trend_display)) : ?>
                        <?php
                        $trend_count = count($trend_display);
                        $views_points = [];
                        $enquiries_points = [];
                        $first_label = sanitize_text_field((string) ($trend_display[0]['label'] ?? ''));
                        $last_label = sanitize_text_field((string) ($trend_display[$trend_count - 1]['label'] ?? ''));
                        $sum_views = 0;
                        $sum_enquiries = 0;
                        $max_views = 0;
                        $max_enquiries = 0;

                        foreach ($trend_display as $index => $trend_row) {
                            $trend_views = max(0, (int) ($trend_row['listing_views'] ?? 0));
                            $trend_enquiries = max(0, (int) ($trend_row['enquiries_received'] ?? 0));
                            $sum_views += $trend_views;
                            $sum_enquiries += $trend_enquiries;
                            $max_views = max($max_views, $trend_views);
                            $max_enquiries = max($max_enquiries, $trend_enquiries);

                            $x = $trend_count > 1 ? ($index / ($trend_count - 1)) * 100 : 50;
                            $views_y = 100 - (($trend_views / $trend_max) * 100);
                            $enquiries_y = 100 - (($trend_enquiries / $trend_max) * 100);

                            $views_points[] = number_format((float) $x, 3, '.', '') . ',' . number_format((float) $views_y, 3, '.', '');
                            $enquiries_points[] = number_format((float) $x, 3, '.', '') . ',' . number_format((float) $enquiries_y, 3, '.', '');
                        }
                        ?>
                        <div class="flex flex-col">
                            <div class="relative h-[25vh] max-h-[25vh] rounded-xl border border-gray-100 bg-gradient-to-b from-white to-gray-50/60 p-3 sm:p-4">
                                <div class="absolute inset-0 pointer-events-none">
                                    <svg class="w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
                                        <line x1="0" y1="25" x2="100" y2="25" stroke="#f1f5f9" stroke-width="0.6"></line>
                                        <line x1="0" y1="50" x2="100" y2="50" stroke="#f1f5f9" stroke-width="0.6"></line>
                                        <line x1="0" y1="75" x2="100" y2="75" stroke="#f1f5f9" stroke-width="0.6"></line>
                                    </svg>
                                </div>
                                <svg class="relative w-full h-full" viewBox="0 0 100 100" preserveAspectRatio="none" role="img" aria-label="<?php esc_attr_e('Views and enquiries trend chart', 'nexdirectory'); ?>">
                                    <polyline points="<?php echo esc_attr(implode(' ', $views_points)); ?>" fill="none" stroke="var(--eep-primary)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"></polyline>
                                    <polyline points="<?php echo esc_attr(implode(' ', $enquiries_points)); ?>" fill="none" stroke="#1d4ed8" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"></polyline>
                                </svg>
                            </div>

                            <div class="mt-3 flex flex-wrap items-center gap-3 text-xs">
                                <span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-md bg-brand-50 text-brand-700 border border-brand-100">
                                    <span class="w-2 h-2 rounded-full bg-brand-500"></span>
                                    <?php esc_html_e('Views', 'nexdirectory'); ?>
                                </span>
                                <span class="inline-flex items-center gap-1.5 px-2 py-1 rounded-md bg-blue-50 text-blue-700 border border-blue-100">
                                    <span class="w-2 h-2 rounded-full bg-blue-600"></span>
                                    <?php esc_html_e('Enquiries', 'nexdirectory'); ?>
                                </span>
                                <span class="text-gray-500"><?php echo esc_html($first_label); ?></span>
                                <span class="text-gray-300">-</span>
                                <span class="text-gray-500"><?php echo esc_html($last_label); ?></span>
                            </div>

                            <div class="mt-3 grid grid-cols-3 gap-2 text-xs">
                                <div class="rounded-lg border border-gray-100 bg-white px-3 py-2">
                                    <p class="text-gray-500"><?php esc_html_e('Total Views', 'nexdirectory'); ?></p>
                                    <p class="text-sm font-bold text-gray-900"><?php echo esc_html((string) ((int) $sum_views)); ?></p>
                                </div>
                                <div class="rounded-lg border border-gray-100 bg-white px-3 py-2">
                                    <p class="text-gray-500"><?php esc_html_e('Total Enquiries', 'nexdirectory'); ?></p>
                                    <p class="text-sm font-bold text-gray-900"><?php echo esc_html((string) ((int) $sum_enquiries)); ?></p>
                                </div>
                                <div class="rounded-lg border border-gray-100 bg-white px-3 py-2">
                                    <p class="text-gray-500"><?php esc_html_e('Peak Day', 'nexdirectory'); ?></p>
                                    <p class="text-sm font-bold text-gray-900"><?php echo esc_html(sprintf(__('V %1$d / E %2$d', 'nexdirectory'), (int) $max_views, (int) $max_enquiries)); ?></p>
                                </div>
                            </div>
                        </div>
                    <?php else : ?>
                        <div class="flex-1 flex items-center justify-center min-h-[200px]">
                            <p class="text-sm font-medium text-gray-400"><?php esc_html_e('No trend data available for this period.', 'nexdirectory'); ?></p>
                        </div>
                    <?php endif; ?>
                </div>

                <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-300 lg:col-span-1 bg-white rounded-2xl border border-gray-100 shadow-sm p-5 sm:p-6 flex flex-col h-full">
                    <div class="mb-5">
                        <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('Boost Impact', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500"><?php esc_html_e('Performance between boosted vs non-boosted.', 'nexdirectory'); ?></p>
                    </div>

                    <div class="space-y-4 mb-6">
                        <div class="bg-brand-50 rounded-xl p-4 border border-brand-100">
                            <h4 class="font-bold text-brand-700 text-sm mb-2 flex items-center gap-1.5"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg> <?php esc_html_e('Boosted', 'nexdirectory'); ?></h4>
                            <div class="grid grid-cols-2 gap-y-2 text-xs">
                                <span class="text-brand-600 font-medium">Listings:</span> <strong class="text-brand-900 text-right"><?php echo (int) ($boosted_metrics['listings'] ?? 0); ?></strong>
                                <span class="text-brand-600 font-medium">Views:</span> <strong class="text-brand-900 text-right"><?php echo (int) ($boosted_metrics['listing_views'] ?? 0); ?></strong>
                                <span class="text-brand-600 font-medium">Enquiries:</span> <strong class="text-brand-900 text-right"><?php echo (int) ($boosted_metrics['enquiries_received'] ?? 0); ?></strong>
                                <span class="text-brand-600 font-medium">Conv. Rate:</span> <strong class="text-brand-900 text-right"><?php echo number_format((float) ($boosted_metrics['conversion_rate'] ?? 0), 2); ?>%</strong>
                            </div>
                        </div>
                        <div class="bg-gray-50 rounded-xl p-4 border border-gray-200">
                            <h4 class="font-bold text-gray-700 text-sm mb-2"><?php esc_html_e('Standard', 'nexdirectory'); ?></h4>
                            <div class="grid grid-cols-2 gap-y-2 text-xs">
                                <span class="text-gray-500 font-medium">Listings:</span> <strong class="text-gray-900 text-right"><?php echo (int) ($non_boosted_metrics['listings'] ?? 0); ?></strong>
                                <span class="text-gray-500 font-medium">Views:</span> <strong class="text-gray-900 text-right"><?php echo (int) ($non_boosted_metrics['listing_views'] ?? 0); ?></strong>
                                <span class="text-gray-500 font-medium">Enquiries:</span> <strong class="text-gray-900 text-right"><?php echo (int) ($non_boosted_metrics['enquiries_received'] ?? 0); ?></strong>
                                <span class="text-gray-500 font-medium">Conv. Rate:</span> <strong class="text-gray-900 text-right"><?php echo number_format((float) ($non_boosted_metrics['conversion_rate'] ?? 0), 2); ?>%</strong>
                            </div>
                        </div>
                    </div>

                    <div class="mt-auto">
                        <p class="text-[11px] text-gray-500 font-medium uppercase tracking-wider mb-2">Uplift Metrics</p>
                        <div class="flex flex-wrap gap-2">
                            <?php
                            $views_uplift = (float) ($boost_uplift['views_per_listing_pct'] ?? 0);
                            $enquiries_uplift = (float) ($boost_uplift['enquiries_per_listing_pct'] ?? 0);
                            $conversion_uplift = (float) ($boost_uplift['conversion_rate_pct'] ?? 0);
                            ?>
                            <span class="px-2 py-1 rounded text-[10px] font-bold border <?php echo esc_attr($uplift_badge_class($views_uplift)); ?>"><?php echo esc_html(sprintf(__('Views: %s%%', 'nexdirectory'), number_format($views_uplift, 2))); ?></span>
                            <span class="px-2 py-1 rounded text-[10px] font-bold border <?php echo esc_attr($uplift_badge_class($enquiries_uplift)); ?>"><?php echo esc_html(sprintf(__('Enq: %s%%', 'nexdirectory'), number_format($enquiries_uplift, 2))); ?></span>
                            <span class="px-2 py-1 rounded text-[10px] font-bold border <?php echo esc_attr($uplift_badge_class($conversion_uplift)); ?>"><?php echo esc_html(sprintf(__('Conv: %s%%', 'nexdirectory'), number_format($conversion_uplift, 2))); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-400 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                    <h3 class="font-bold text-gray-900"><?php esc_html_e('Performance by Listing', 'nexdirectory'); ?></h3>
                </div>
                
                <?php if (!empty($analytics_rows)) : ?>
                    <div class="overflow-x-auto scrollbar-hide">
                        <table class="w-full text-left text-sm text-gray-600 whitespace-nowrap">
                            <thead class="bg-white text-xs uppercase text-gray-400 font-semibold border-b border-gray-100">
                                <tr>
                                    <th class="px-5 py-4"><?php esc_html_e('Listing', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Boosted', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Views', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Phone', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Website', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('WhatsApp', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Enquiries', 'nexdirectory'); ?></th>
                                    <th class="px-5 py-4"><?php esc_html_e('Conv.', 'nexdirectory'); ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-50">
                                <?php foreach ($analytics_rows as $row) : ?>
                                    <?php $title = sanitize_text_field((string) ($row['title'] ?? '')); ?>
                                    <?php $row_boosted = !empty($row['is_boosted']); ?>
                                    <tr class="hover:bg-gray-50/80 transition-colors">
                                        <td class="px-5 py-4 font-medium text-gray-900 max-w-[200px] truncate">
                                            <a href="<?php echo esc_url((string) ($row['url'] ?? '#')); ?>" class="hover:text-brand-600 transition-colors"><?php echo esc_html($title !== '' ? $title : ('#' . (string) ((int) ($row['event_id'] ?? 0)))); ?></a>
                                        </td>
                                        <td class="px-5 py-4">
                                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo $row_boosted ? 'bg-brand-50 text-brand-600 border-brand-200' : 'bg-gray-50 text-gray-500 border-gray-200'; ?>">
                                                <?php echo esc_html($row_boosted ? __('Yes', 'nexdirectory') : __('No', 'nexdirectory')); ?>
                                            </span>
                                        </td>
                                        <td class="px-5 py-4 font-semibold text-gray-800"><?php echo esc_html((string) ((int) ($row['listing_views'] ?? 0))); ?></td>
                                        <td class="px-5 py-4"><?php echo esc_html((string) ((int) ($row['click_phone'] ?? 0))); ?></td>
                                        <td class="px-5 py-4"><?php echo esc_html((string) ((int) ($row['click_website'] ?? 0))); ?></td>
                                        <td class="px-5 py-4"><?php echo esc_html((string) ((int) ($row['click_whatsapp'] ?? 0))); ?></td>
                                        <td class="px-5 py-4 font-semibold text-gray-800"><?php echo esc_html((string) ((int) ($row['enquiries_received'] ?? 0))); ?></td>
                                        <td class="px-5 py-4 text-brand-600 font-bold"><?php echo esc_html((string) ((float) ($row['conversion_rate'] ?? 0))); ?>%</td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else : ?>
                    <div class="p-10 text-center flex flex-col items-center justify-center">
                        <div class="w-16 h-16 bg-gray-50 text-gray-400 rounded-full flex items-center justify-center mb-4">
                            <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path></svg>
                        </div>
                        <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('No analytics yet', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500 mt-1 mb-5"><?php esc_html_e('Publish listings and share them to start collecting performance data.', 'nexdirectory'); ?></p>
                        <a href="<?php echo esc_url($events_url); ?>" class="eep-force-accent-action bg-gray-900 hover:bg-black text-white px-6 py-2.5 rounded-xl text-sm font-semibold transition-all active:scale-95 shadow-sm"><?php esc_html_e('Browse Listings', 'nexdirectory'); ?></a>
                    </div>
                <?php endif; ?>
            </div>

        </section>
        <?php endif; ?>
<?php
        // My Listings & Boosts Variables
        $my_items_title = sanitize_text_field((string) ($ui_labels['my_items_title'] ?? __('My Listings', 'nexdirectory')));
        $my_items_description = sanitize_text_field((string) ($ui_labels['my_items_description'] ?? __('Manage submissions, update details, and monitor moderation status.', 'nexdirectory')));
        $plural_label = sanitize_text_field((string) ($ui_labels['plural'] ?? __('Listings', 'nexdirectory')));
        $singular_label = sanitize_text_field((string) ($ui_labels['singular'] ?? __('Listing', 'nexdirectory')));
        $delete_prompt = $is_events_profile ? __('Delete this event?', 'nexdirectory') : sprintf(__('Delete this %s?', 'nexdirectory'), strtolower((string) $singular_label));
        $attendees_heading = $is_events_profile ? __('Attendees', 'nexdirectory') : __('Followers', 'nexdirectory');
        $edit_action_label = sanitize_text_field((string) ($ui_labels['single_edit_cta'] ?? __('Edit', 'nexdirectory')));
        
        $boosts_enabled = method_exists($this, 'is_boost_enabled') ? (bool) $this->is_boost_enabled() : false;
        $boost_test_free_mode = $boosts_enabled && method_exists($this, 'boost_test_free_mode_enabled') ? (bool) $this->boost_test_free_mode_enabled() : false;
        $boost_gateway_stripe_enabled = isset($boost_gateway_stripe_enabled) ? !empty($boost_gateway_stripe_enabled) : ($boosts_enabled && (string) get_option('eep_boost_stripe_enabled', '0') === '1');
        $boost_gateway_paypal_enabled = isset($boost_gateway_paypal_enabled) ? !empty($boost_gateway_paypal_enabled) : ($boosts_enabled && (string) get_option('eep_boost_paypal_enabled', '0') === '1');
        $boost_checkout_available = $boosts_enabled && ($boost_test_free_mode || $boost_gateway_stripe_enabled || $boost_gateway_paypal_enabled);
        $boost_duration_pricing = $boosts_enabled && method_exists($this, 'get_boost_duration_pricing') ? (array) $this->get_boost_duration_pricing() : [];
        $boost_currency = sanitize_text_field((string) get_option('eep_boost_currency', 'USD'));
        $boost_badge_label = sanitize_text_field((string) get_option('eep_boost_featured_badge_text', __('Featured', 'nexdirectory')));
        $boost_history_rows = isset($boost_history_rows) && is_array($boost_history_rows) ? $boost_history_rows : [];
        
        $my_events_url = isset($my_events_url) ? (string) $my_events_url : $this->get_platform_page_url('eep_page_my_events_url', $this->get_profile_route_slugs('my_items'), $this->get_profile_route_default_url('my_items'));
        $attendees_panel = isset($attendees_panel) && is_array($attendees_panel) ? $attendees_panel : null;
        $initial_listings_subtab = sanitize_key((string) ($initial_listings_subtab ?? 'manage'));
        if (!in_array($initial_listings_subtab, ['manage', 'boosts', 'webapp'], true)) {
            $initial_listings_subtab = 'manage';
        }
        $webapp_event_options = isset($webapp_event_options) && is_array($webapp_event_options) ? $webapp_event_options : [];
        $selected_webapp_event_id = isset($selected_webapp_event_id) ? absint((int) $selected_webapp_event_id) : 0;
        if ($is_events_profile && empty($webapp_event_options) && isset($query) && $query instanceof WP_Query && !empty($query->posts)) {
            foreach ((array) $query->posts as $webapp_fallback_post) {
                $webapp_fallback_id = 0;
                if ($webapp_fallback_post instanceof WP_Post) {
                    $webapp_fallback_id = absint((int) $webapp_fallback_post->ID);
                } elseif (is_numeric($webapp_fallback_post)) {
                    $webapp_fallback_id = absint((int) $webapp_fallback_post);
                } elseif (is_array($webapp_fallback_post) && isset($webapp_fallback_post['ID'])) {
                    $webapp_fallback_id = absint((int) $webapp_fallback_post['ID']);
                }
                if ($webapp_fallback_id <= 0) {
                    continue;
                }
                $webapp_event_options[] = [
                    'id' => $webapp_fallback_id,
                    'title' => sanitize_text_field((string) get_the_title($webapp_fallback_id)),
                    'status' => sanitize_key((string) get_post_status($webapp_fallback_id)),
                    'date_label' => sanitize_text_field((string) $this->format_event_date($webapp_fallback_id)),
                ];
            }
            if ($selected_webapp_event_id <= 0 && !empty($webapp_event_options)) {
                $selected_webapp_event_id = absint((int) ($webapp_event_options[0]['id'] ?? 0));
            }
        }
        $webapp_prefill = isset($webapp_prefill) && is_array($webapp_prefill) ? $webapp_prefill : [];
        $selected_event_webapp_url = isset($selected_event_webapp_url) ? esc_url_raw((string) $selected_event_webapp_url) : '';
        $selected_event_manifest_url = isset($selected_event_manifest_url) ? esc_url_raw((string) $selected_event_manifest_url) : '';
        $selected_event_service_worker_url = isset($selected_event_service_worker_url) ? esc_url_raw((string) $selected_event_service_worker_url) : '';
        $selected_event_service_worker_scope = isset($selected_event_service_worker_scope) ? sanitize_text_field((string) $selected_event_service_worker_scope) : '';
        $webapp_manage_page_url = isset($webapp_manage_page_url) ? (string) $webapp_manage_page_url : eep_add_query_arg([
            'eep_tab' => 'listings',
            'listings_subtab' => 'webapp',
        ], $my_events_url) . '#listings';
        $webapp_selected_manage_url = isset($webapp_selected_manage_url) ? (string) $webapp_selected_manage_url : ($selected_webapp_event_id > 0
            ? eep_add_query_arg([
                'eep_tab' => 'listings',
                'listings_subtab' => 'webapp',
                'webapp_event' => $selected_webapp_event_id,
            ], $my_events_url) . '#listings'
            : $webapp_manage_page_url);

        // Calculate Boost Stats
        $boost_listing_count = 0; $boost_active_count = 0; $boost_expiring_soon_count = 0; $next_expiry_ts = 0; $now_ts = time();
        if ($boosts_enabled && isset($query) && $query instanceof WP_Query && !empty($query->posts) && is_array($query->posts)) {
            foreach ($query->posts as $boost_post_obj) {
                if (!$boost_post_obj instanceof WP_Post) continue;
                $boost_listing_count++;
                $state = method_exists($this, 'get_listing_boost_state') ? (array) $this->get_listing_boost_state((int) $boost_post_obj->ID) : [];
                if (empty($state['active'])) continue;
                $boost_active_count++;
                $expires_ts = isset($state['expires_ts']) ? absint((int) $state['expires_ts']) : 0;
                if ($expires_ts > $now_ts && $expires_ts <= ($now_ts + (7 * DAY_IN_SECONDS))) $boost_expiring_soon_count++;
                if ($expires_ts > 0 && ($next_expiry_ts <= 0 || $expires_ts < $next_expiry_ts)) $next_expiry_ts = $expires_ts;
            }
        }
        $next_expiry_label = $next_expiry_ts > 0 ? wp_date(get_option('date_format') . ' ' . get_option('time_format'), $next_expiry_ts) : '';
        ?>

        <?php if ($show_listings_tab) : ?>
        <section x-show="activeTab === 'listings'" x-transition.opacity.duration.300ms x-cloak x-data="{ subTab: '<?php echo esc_attr($initial_listings_subtab); ?>', attendeesOpen: <?php echo !empty($attendees_panel) ? 'true' : 'false'; ?> }">
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6">
                <div class="flex flex-col sm:flex-row sm:items-end justify-between gap-4">
                    <div>
                        <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php echo esc_html($my_items_title); ?></h2>
                        <p class="text-sm sm:text-base text-gray-500 max-w-2xl"><?php echo esc_html($my_items_description); ?></p>
                    </div>
                    <?php if ($show_submit_tab) : ?>
                    <button type="button" @click="setTab('submit')" class="eep-force-accent-action w-full sm:w-auto bg-brand-600 hover:bg-brand-700 text-white px-5 py-2.5 rounded-xl text-sm font-semibold active:scale-95 transition-all shadow-sm flex items-center justify-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                        <?php esc_html_e('Add New', 'nexdirectory'); ?>
                    </button>
                    <?php endif; ?>
                </div>

                <?php $listings_subtab_count = 1 + ($is_events_profile ? 1 : 0) + ($boosts_enabled ? 1 : 0); ?>
                <div class="mt-6 p-2 bg-gray-200/50 rounded-2xl grid gap-2 w-full" style="grid-template-columns: repeat(<?php echo esc_attr((string) max(1, (int) $listings_subtab_count)); ?>, minmax(0, 1fr));">
                    <button @click="subTab = 'manage'" :class="subTab === 'manage' ? 'bg-white text-gray-900 shadow-sm font-semibold' : 'text-gray-500 hover:text-gray-700 font-medium'" class="w-full min-h-[52px] px-5 py-3 rounded-xl text-sm sm:text-base transition-all whitespace-nowrap text-center">
                        <?php esc_html_e('Active Listings', 'nexdirectory'); ?>
                    </button>
                    <?php if ($is_events_profile) : ?>
                    <button type="button" disabled aria-disabled="true" class="w-full min-h-[52px] px-5 py-3 rounded-xl text-sm sm:text-base transition-all whitespace-nowrap flex items-center justify-center gap-1.5 bg-gray-100 text-gray-400 cursor-not-allowed border border-gray-200">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h18M7 5v14m10-14v14M3 19h18"></path></svg>
                        <?php esc_html_e('WEB APP', 'nexdirectory'); ?>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wide bg-gray-200 text-gray-600"><?php esc_html_e('Coming Soon', 'nexdirectory'); ?></span>
                    </button>
                    <?php endif; ?>
                    <?php if ($boosts_enabled) : ?>
                    <button @click="subTab = 'boosts'" :class="subTab === 'boosts' ? 'bg-white text-brand-600 shadow-sm font-semibold' : 'text-gray-500 hover:text-gray-700 font-medium'" class="w-full min-h-[52px] px-5 py-3 rounded-xl text-sm sm:text-base transition-all whitespace-nowrap flex items-center justify-center gap-1.5">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
                        <?php esc_html_e('Boost Hub', 'nexdirectory'); ?>
                    </button>
                    <?php endif; ?>
                </div>
            </div>

            <div x-show="subTab === 'manage'" x-transition.opacity.duration.300ms>
                <?php if (isset($query) && $query instanceof WP_Query && $query->have_posts()) : ?>
                    <div class="space-y-4">
                        <?php while ($query->have_posts()) : $query->the_post(); ?>
                            <?php 
                            $event_status = (string) get_post_status(get_the_ID()); 
                            $edit_target_id = (int) get_the_ID();
                            $edit_base_url = (string) ($submit_event_url ?? '');
                            if ($edit_base_url === '') {
                                $edit_base_url = (string) ($my_events_url ?? home_url('/'));
                            }
                            $edit_event_url = eep_add_query_arg([
                                'eep_tab' => 'submit',
                                'edit_event_id' => $edit_target_id,
                            ], $edit_base_url) . '#submit';
                            $can_edit_target = is_callable([$this, 'user_can_edit_event']) ? (bool) $this->user_can_edit_event($edit_target_id) : true;
                            $is_demo_locked_target = is_callable([$this, 'is_demo_event_edit_locked']) ? (bool) $this->is_demo_event_edit_locked($edit_target_id, (int) get_current_user_id()) : false;
                            $duplicate_event_url = wp_nonce_url(
                                eep_add_query_arg([
                                    'action' => 'eep_duplicate_event',
                                    'post' => (int) $edit_target_id,
                                ], admin_url('admin.php')),
                                'eep_duplicate_event_' . (int) $edit_target_id
                            );
                            $view_event_url = (string) get_permalink(get_the_ID());
                            $view_event_label = __('View', 'nexdirectory');

                            if ($event_status !== 'publish' && $can_edit_target) {
                                $preview_url = get_preview_post_link($edit_target_id);
                                if ((!is_string($preview_url) || $preview_url === '') && $edit_target_id > 0) {
                                    $preview_url = eep_add_query_arg(['p' => $edit_target_id, 'post_type' => $this::POST_TYPE, 'preview' => 'true'], home_url('/'));
                                }
                                if (is_string($preview_url) && $preview_url !== '') {
                                    $view_event_url = $preview_url;
                                } elseif (is_string($edit_event_url) && $edit_event_url !== '') {
                                    $view_event_url = $edit_event_url;
                                }
                                $view_event_label = __('Preview', 'nexdirectory');
                            }

                            $boost_state = $boosts_enabled && method_exists($this, 'get_listing_boost_state') ? (array) $this->get_listing_boost_state(get_the_ID()) : [];
                            $boost_active = !empty($boost_state['active']);
                            $can_toggle_live_draft = $this->can_manage_event_team($edit_target_id, get_current_user_id()) || $this->user_can_moderate_events(get_current_user_id());
                            $toggle_redirect_url = (string) ($my_events_url ?? home_url('/'));
                            if ($toggle_redirect_url === '') {
                                $toggle_redirect_url = home_url('/');
                            }
                            $toggle_redirect_url = eep_add_query_arg('eep_tab', 'listings', $toggle_redirect_url) . '#listings';
                            $webapp_manage_url = eep_add_query_arg([
                                'eep_tab' => 'listings',
                                'listings_subtab' => 'webapp',
                                'webapp_event' => $edit_target_id,
                            ], $my_events_url) . '#listings';

                            $ticket_status_display = '';
                            if ($is_events_profile) {
                                $ticket_sales_enabled = (string) get_post_meta(get_the_ID(), 'eep_ticket_sales_enabled', true) === '1';
                                $ticket_price_raw = trim((string) get_post_meta(get_the_ID(), 'eep_ticket_price', true));
                                $ticket_price_amount = 0.0;
                                if ($ticket_price_raw !== '') {
                                    $normalized_ticket_price = str_replace(',', '.', $ticket_price_raw);
                                    if (is_numeric($normalized_ticket_price)) {
                                        $ticket_price_amount = max(0.0, (float) $normalized_ticket_price);
                                    } elseif (preg_match('/\d+(?:\.\d{1,2})?/', $normalized_ticket_price, $ticket_price_match)) {
                                        $ticket_price_amount = max(0.0, (float) ($ticket_price_match[0] ?? 0));
                                    }
                                }

                                if ($ticket_sales_enabled) {
                                    if ($ticket_price_amount > 0) {
                                        $ticket_currency = strtoupper(sanitize_text_field((string) get_option('eep_ticket_currency', 'USD')));
                                        $ticket_status_display = sprintf('%1$s %2$s', $ticket_currency, number_format_i18n($ticket_price_amount, 2));
                                    } else {
                                        $ticket_status_display = __('Free', 'nexdirectory');
                                    }
                                } else {
                                    $ticket_status_display = __('Not enabled', 'nexdirectory');
                                }
                            }
                            ?>
                            <div class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors flex flex-col lg:flex-row gap-5 lg:items-center justify-between">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-1.5 flex-wrap">
                                        <h3 class="font-bold text-gray-900 text-lg truncate"><a href="<?php echo esc_url($view_event_url); ?>" class="hover:text-brand-600 transition-colors"><?php the_title(); ?></a></h3>
                                        <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo $event_status === 'publish' ? 'bg-green-50 text-green-700 border-green-200' : 'bg-amber-50 text-amber-700 border-amber-200'; ?>">
                                            <?php echo esc_html(method_exists($this, 'event_status_badge') ? eep_strip_all_tags($this->event_status_badge($event_status)) : ucfirst($event_status)); ?>
                                        </span>
                                        <?php if ($boost_active) : ?>
                                            <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-brand-50 text-brand-600 border border-brand-200 flex items-center gap-1">
                                                <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
                                                <?php echo esc_html($boost_badge_label); ?>
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                    <p class="text-sm text-gray-500 flex items-center gap-2">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                        <?php echo esc_html(method_exists($this, 'format_event_date') ? $this->format_event_date(get_the_ID()) : get_the_date()); ?>
                                    </p>
                                    <?php if ($is_events_profile) : ?>
                                        <p class="text-sm text-gray-500 flex items-center gap-2 mt-1">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 14l6-6m-5.5-2h5a2 2 0 012 2v5a2 2 0 01-.586 1.414l-6.5 6.5a2 2 0 01-2.828 0l-4.5-4.5a2 2 0 010-2.828l6.5-6.5A2 2 0 019.5 6z"></path></svg>
                                            <?php echo esc_html(sprintf(__('Ticket: %s', 'nexdirectory'), $ticket_status_display)); ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php $moderation_note = get_post_meta(get_the_ID(), 'eep_moderation_note', true); ?>
                                    <?php if ($moderation_note) : ?>
                                        <p class="text-xs text-red-500 mt-3 bg-red-50 px-3 py-2 rounded-lg border border-red-100"><?php echo esc_html($moderation_note); ?></p>
                                    <?php endif; ?>
                                </div>

                                <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 shrink-0">
                                    <?php if ($can_toggle_live_draft) : ?>
                                        <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'listings', admin_url('admin-post.php'))); ?>#listings" class="eep-inline-form eep-live-toggle-form w-full sm:w-auto">
                                            <input type="hidden" name="action" value="eep_toggle_event_live_draft">
                                            <input type="hidden" name="post_id" value="<?php echo esc_attr(get_the_ID()); ?>">
                                            <input type="hidden" name="redirect_to" value="<?php echo esc_attr($toggle_redirect_url); ?>">
                                            <input type="hidden" name="desired_state" value="draft">
                                            <?php wp_nonce_field('eep_toggle_event_live_draft_' . get_the_ID(), 'eep_toggle_event_live_draft_nonce'); ?>
                                            <label class="eep-live-toggle" title="<?php esc_attr_e('Toggle between Live and Draft status', 'nexdirectory'); ?>">
                                                <input type="checkbox" name="desired_state" value="live" <?php checked($event_status, 'publish'); ?> onchange="this.form.submit()">
                                                <span class="eep-live-toggle-track" aria-hidden="true"></span>
                                                <span class="eep-live-toggle-label eep-live-toggle-label-live"><?php esc_html_e('Live', 'nexdirectory'); ?></span>
                                                <span class="eep-live-toggle-label eep-live-toggle-label-draft"><?php esc_html_e('Draft', 'nexdirectory'); ?></span>
                                            </label>
                                            <?php if ($event_status === 'pending') : ?>
                                                <small class="eep-live-toggle-meta"><?php esc_html_e('Pending moderation', 'nexdirectory'); ?></small>
                                            <?php endif; ?>
                                        </form>
                                    <?php endif; ?>
                                    <div class="flex items-center gap-2 grid grid-cols-2 sm:flex">
                                        <a href="<?php echo esc_url($view_event_url); ?>" class="eep-account-action-btn w-full sm:w-36 active:scale-95"><?php echo esc_html($view_event_label); ?></a>
                                        <?php if ($can_edit_target) : ?>
                                            <a href="<?php echo esc_url($edit_event_url); ?>" class="eep-account-action-btn w-full sm:w-36 active:scale-95"><?php echo esc_html($edit_action_label); ?></a>
                                        <?php elseif ($is_demo_locked_target) : ?>
                                            <?php $demo_locked_edit_tip = __('Demo listing locked. Duplicate to use 1 free event credit, or upgrade.', 'nexdirectory'); ?>
                                            <span role="button" aria-disabled="true" title="<?php echo esc_attr($demo_locked_edit_tip); ?>" class="eep-account-action-btn w-full sm:w-36 opacity-60 cursor-not-allowed select-none"><?php echo esc_html($edit_action_label); ?></span>
                                            <a href="<?php echo esc_url($duplicate_event_url); ?>" title="<?php echo esc_attr($demo_locked_edit_tip); ?>" class="eep-account-action-btn w-full sm:w-36 active:scale-95"><?php esc_html_e('Use Free Credit', 'nexdirectory'); ?></a>
                                        <?php endif; ?>
                                    </div>
                                    <div class="flex items-center gap-2 grid grid-cols-2 sm:flex">
                                        <a href="<?php echo esc_url(eep_add_query_arg('attendees_event', (string) get_the_ID(), $my_events_url)); ?>#listings" class="eep-account-action-btn w-full sm:w-36 active:scale-95">
                                            <?php echo esc_html($attendees_heading); ?>
                                        </a>
                                        <?php $can_delete_event = (int) get_post_field('post_author', get_the_ID()) === (int) get_current_user_id() || $this->user_can_moderate_events(); ?>
                                        <?php if ($can_delete_event) : ?>
                                            <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'listings', admin_url('admin-post.php'))); ?>#listings" onsubmit="return confirm('<?php echo esc_js($delete_prompt); ?>');" class="w-full sm:w-36">
                                                <input type="hidden" name="action" value="eep_delete_event">
                                                <input type="hidden" name="post_id" value="<?php echo esc_attr(get_the_ID()); ?>">
                                                <?php wp_nonce_field('eep_delete_event_' . get_the_ID(), 'eep_delete_nonce'); ?>
                                                <button type="submit" class="eep-account-action-btn eep-account-action-btn-danger w-full active:scale-95">
                                                    <?php esc_html_e('Delete', 'nexdirectory'); ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                        <?php wp_reset_postdata(); ?>
                        <?php if ($query instanceof WP_Query) { $query->rewind_posts(); } ?>
                    </div>
                <?php else : ?>
                    <div class="bg-white rounded-2xl border border-gray-100 p-10 text-center shadow-sm">
                        <div class="w-16 h-16 bg-gray-50 text-gray-400 rounded-full flex items-center justify-center mx-auto mb-4">
                            <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 002 2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
                        </div>
                        <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('No listings found', 'nexdirectory'); ?></h3>
                        <p class="text-gray-500 text-sm mt-1 mb-5"><?php echo esc_html(sprintf(__('You have not submitted any %s yet.', 'nexdirectory'), strtolower((string) $plural_label))); ?></p>
                        <?php if ($show_submit_tab) : ?>
                            <button type="button" @click="setTab('submit')" class="eep-force-accent-action inline-block bg-brand-600 text-white px-6 py-2.5 rounded-xl text-sm font-semibold hover:bg-brand-700 transition-colors active:scale-95 shadow-sm">Create Listing</button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>

            <?php if ($is_events_profile) : ?>
            <div x-show="subTab === 'webapp'" x-transition.opacity.duration.300ms style="display:none;">
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                    <div class="p-5 sm:p-6 border-b border-gray-100 bg-gray-50/50">
                        <h3 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Event Web App', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500"><?php esc_html_e('This module is temporarily hidden from MVP front-end screens and will return in a future release.', 'nexdirectory'); ?></p>
                    </div>
                    <div class="p-5 sm:p-6">
                        <div class="rounded-xl border border-gray-200 bg-gray-50 px-4 py-5 text-sm text-gray-600">
                            <p class="font-semibold text-gray-800 mb-1"><?php esc_html_e('Coming Soon', 'nexdirectory'); ?></p>
                            <p><?php esc_html_e('App configuration is disabled for MVP. Existing app settings are preserved and can be resumed later.', 'nexdirectory'); ?></p>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($boosts_enabled) : ?>
            <div x-show="subTab === 'boosts'" x-transition.opacity.duration.300ms style="display: none;">
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                    <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm">
                        <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Total Listings', 'nexdirectory'); ?></span>
                        <strong class="text-2xl font-bold text-gray-900"><?php echo esc_html((string) $boost_listing_count); ?></strong>
                    </article>
                    <article class="bg-white rounded-2xl border border-brand-200 p-5 shadow-sm bg-brand-50/30">
                        <span class="text-[10px] sm:text-xs font-semibold text-brand-600 uppercase tracking-wider mb-1 block"><?php esc_html_e('Active Boosts', 'nexdirectory'); ?></span>
                        <strong class="text-2xl font-bold text-brand-900"><?php echo esc_html((string) $boost_active_count); ?></strong>
                    </article>
                    <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm">
                        <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Expiring Soon', 'nexdirectory'); ?></span>
                        <strong class="text-2xl font-bold text-gray-900"><?php echo esc_html((string) $boost_expiring_soon_count); ?></strong>
                    </article>
                    <article class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm">
                        <span class="text-[10px] sm:text-xs font-semibold text-gray-400 uppercase tracking-wider mb-1 block"><?php esc_html_e('Next Expiry', 'nexdirectory'); ?></span>
                        <strong class="text-base sm:text-lg font-bold text-gray-900 truncate block mt-1"><?php echo esc_html($next_expiry_label !== '' ? $next_expiry_label : __('N/A', 'nexdirectory')); ?></strong>
                    </article>
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden mb-6">
                    <div class="p-5 sm:p-6 border-b border-gray-100 bg-gray-50/50">
                        <h3 class="text-lg font-bold text-gray-900 mb-1"><?php esc_html_e('Boost a Listing', 'nexdirectory'); ?></h3>
                        <p class="text-sm text-gray-500"><?php esc_html_e('Gain priority placement and a featured badge to drive more enquiries.', 'nexdirectory'); ?></p>
                    </div>
                    <div class="p-5 sm:p-6">
                        <?php if (!$boost_checkout_available) : ?>
                            <div class="p-4 bg-amber-50 text-amber-800 rounded-xl text-sm border border-amber-200">
                                <?php esc_html_e('No payment gateways are enabled for boosts. Contact an administrator.', 'nexdirectory'); ?>
                            </div>
                        <?php else : ?>
                            <?php if ($boost_test_free_mode) : ?>
                                <div class="mb-5 p-4 bg-green-50 text-green-800 rounded-xl text-sm border border-green-200 flex items-start gap-3">
                                    <svg class="w-5 h-5 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                    <?php esc_html_e('Free test mode is enabled. Boosts activate instantly without payment checkout.', 'nexdirectory'); ?>
                                </div>
                            <?php endif; ?>

                            <?php if ($query instanceof WP_Query) { $query->rewind_posts(); } ?>
                            <?php if (isset($query) && $query instanceof WP_Query && $query->have_posts()) : ?>
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                                    <?php while ($query->have_posts()) : $query->the_post(); ?>
                                        <?php 
                                        $boost_state = method_exists($this, 'get_listing_boost_state') ? (array) $this->get_listing_boost_state(get_the_ID()) : [];
                                        $boost_active = !empty($boost_state['active']);
                                        ?>
                                        <div class="border border-gray-200 hover:border-brand-200 transition-colors rounded-xl p-4 flex flex-col justify-between bg-gray-50/30">
                                            <div class="mb-4">
                                                <h4 class="font-bold text-gray-900 truncate mb-1.5" title="<?php echo esc_attr(get_the_title()); ?>"><?php the_title(); ?></h4>
                                                <?php if ($boost_active) : ?>
                                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-brand-50 text-brand-600 border border-brand-200 uppercase tracking-wider">
                                                        <?php echo esc_html($boost_state['expires_label'] ? sprintf(__('Expires %s', 'nexdirectory'), $boost_state['expires_label']) : __('Active Boost', 'nexdirectory')); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-bold bg-gray-100 text-gray-500 border border-gray-200 uppercase tracking-wider">
                                                        <?php esc_html_e('Not Boosted', 'nexdirectory'); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                            
                                            <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'listings', admin_url('admin-post.php'))); ?>#listings" class="space-y-2">
                                                <input type="hidden" name="action" value="eep_boost_checkout">
                                                <input type="hidden" name="post_id" value="<?php echo esc_attr(get_the_ID()); ?>">
                                                <?php wp_nonce_field('eep_boost_checkout_' . get_the_ID(), 'eep_boost_checkout_nonce'); ?>
                                                
                                                <select name="duration_days" class="w-full px-3 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 shadow-sm">
                                                    <?php foreach ((array) $boost_duration_pricing as $boost_days => $boost_price) : ?>
                                                        <?php if ($boost_days <= 0 || (!$boost_test_free_mode && $boost_price <= 0)) continue; ?>
                                                        <option value="<?php echo esc_attr((string) $boost_days); ?>">
                                                            <?php echo esc_html($boost_test_free_mode ? sprintf(__('%1$d days (Free)', 'nexdirectory'), $boost_days) : sprintf(__('%1$d days (%2$s %3$s)', 'nexdirectory'), $boost_days, $boost_currency, number_format((float)$boost_price, 2))); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>

                                                <?php if ($boost_test_free_mode) : ?>
                                                    <input type="hidden" name="gateway" value="test_free">
                                                <?php else: ?>
                                                    <select name="gateway" class="w-full px-3 py-2 bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 shadow-sm">
                                                        <?php if (!empty($boost_gateway_stripe_enabled)) : ?><option value="stripe">Stripe</option><?php endif; ?>
                                                        <?php if (!empty($boost_gateway_paypal_enabled)) : ?><option value="paypal">PayPal</option><?php endif; ?>
                                                    </select>
                                                <?php endif; ?>

                                                <button type="submit" class="w-full py-2 bg-gray-900 hover:bg-black text-white rounded-lg text-sm font-semibold transition-colors active:scale-95 shadow-sm mt-1">
                                                    <?php echo esc_html($boost_active ? __('Extend Boost', 'nexdirectory') : __('Purchase Boost', 'nexdirectory')); ?>
                                                </button>
                                            </form>
                                        </div>
                                    <?php endwhile; wp_reset_postdata(); ?>
                                </div>
                            <?php else: ?>
                                <p class="text-sm text-gray-500"><?php esc_html_e('No listings available to boost.', 'nexdirectory'); ?></p>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                    <div class="p-5 border-b border-gray-100">
                        <h3 class="font-bold text-gray-900"><?php esc_html_e('Boost History', 'nexdirectory'); ?></h3>
                    </div>
                    <div class="overflow-x-auto scrollbar-hide">
                        <?php if (!empty($boost_history_rows)) : ?>
                            <table class="w-full text-left text-sm text-gray-600 whitespace-nowrap">
                                <thead class="bg-gray-50/50 text-xs uppercase text-gray-400 font-semibold border-b border-gray-100">
                                    <tr>
                                        <th class="px-5 py-3"><?php esc_html_e('Listing', 'nexdirectory'); ?></th>
                                        <th class="px-5 py-3"><?php esc_html_e('Package', 'nexdirectory'); ?></th>
                                        <th class="px-5 py-3"><?php esc_html_e('Amount', 'nexdirectory'); ?></th>
                                        <th class="px-5 py-3"><?php esc_html_e('Status', 'nexdirectory'); ?></th>
                                        <th class="px-5 py-3"><?php esc_html_e('Expires', 'nexdirectory'); ?></th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-50">
                                    <?php foreach ($boost_history_rows as $row) : ?>
                                        <tr class="hover:bg-gray-50/50 transition-colors">
                                            <td class="px-5 py-4 font-medium text-gray-900 max-w-[200px] truncate"><a href="<?php echo esc_url((string) ($row['post_url'] ?? '#')); ?>" class="hover:text-brand-600 transition-colors"><?php echo esc_html((string) ($row['title'] ?? '')); ?></a></td>
                                            <td class="px-5 py-4"><?php echo esc_html(($row['duration_days'] ?? 0) . ' days'); ?></td>
                                            <td class="px-5 py-4"><?php echo esc_html(sprintf('%s %s', sanitize_text_field((string) ($row['currency'] ?? $boost_currency)), number_format((float) ($row['total_amount'] ?? 0), 2))); ?></td>
                                            <td class="px-5 py-4">
                                                <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo ($row['status'] ?? '') === 'active' || ($row['status'] ?? '') === 'paid' ? 'bg-green-50 text-green-700 border-green-200' : 'bg-gray-100 text-gray-600 border-gray-200'; ?>">
                                                    <?php echo esc_html((string) ($row['status_label'] ?? ucfirst($row['status'] ?? ''))); ?>
                                                </span>
                                            </td>
                                            <td class="px-5 py-4 font-medium"><?php echo esc_html((string) ($row['expires_label'] ?? '-')); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php else : ?>
                            <div class="p-8 text-center">
                                <p class="text-sm text-gray-500"><?php esc_html_e('No boost orders found.', 'nexdirectory'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
            <?php endif; ?>

            <?php if (!empty($attendees_panel)) : ?>
            <div id="eep-attendees-modal" class="fixed inset-0 z-[2147483600] flex items-center justify-center p-3 sm:p-6 bg-gray-900/60 backdrop-blur-sm" x-show="attendeesOpen" x-cloak>
                <div class="relative w-full bg-white rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[88vh] sm:max-h-[90vh]" style="max-width:min(1040px,90vw);">
                    <div class="sticky top-0 z-10 flex items-center justify-between p-5 border-b border-gray-100 bg-gray-50/95 backdrop-blur">
                        <div>
                            <h3 class="text-lg font-bold text-gray-900"><?php echo esc_html($attendees_heading); ?>: <?php echo esc_html((string) ($attendees_panel['event_title'] ?? '')); ?></h3>
                            <p class="text-xs text-gray-500 mt-1 font-medium">Confirmed: <?php echo (int)($attendees_panel['yes_count'] ?? 0); ?> • Waitlist: <?php echo (int)($attendees_panel['waitlist_count'] ?? 0); ?></p>
                        </div>
                        <button @click="attendeesOpen = false" class="text-gray-400 hover:text-gray-900 transition-colors p-2 rounded-lg hover:bg-gray-200">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>
                    </div>

                    <div class="p-5 sm:p-6 overflow-y-auto flex-1 bg-white space-y-6">
                        <div class="bg-gray-50 border border-gray-200 rounded-xl p-5">
                            <div class="flex flex-col sm:flex-row sm:items-start justify-between mb-4 gap-3">
                                <div>
                                    <h4 class="font-bold text-gray-900"><?php esc_html_e('Message Attendees', 'nexdirectory'); ?></h4>
                                    <p class="text-xs text-gray-500 mt-1 max-w-lg"><?php esc_html_e('Only attendees who opted into comms will receive this update.', 'nexdirectory'); ?></p>
                                </div>
                                <form method="post" action="<?php echo esc_url((string) ($attendees_panel['export_action'] ?? admin_url('admin-post.php'))); ?>">
                                    <input type="hidden" name="action" value="eep_export_event_attendees">
                                    <input type="hidden" name="event_id" value="<?php echo esc_attr((string) ($attendees_panel['event_id'] ?? '0')); ?>">
                                    <input type="hidden" name="eep_export_attendees_nonce" value="<?php echo esc_attr((string) ($attendees_panel['export_nonce'] ?? '')); ?>">
                                    <button type="submit" class="w-full sm:w-auto text-xs font-semibold bg-white border border-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-100 active:scale-95 transition-all shadow-sm">Export CSV</button>
                                </form>
                            </div>

                            <form method="post" action="<?php echo esc_url((string) ($attendees_panel['email_action'] ?? admin_url('admin-post.php'))); ?>" class="space-y-4">
                                <input type="hidden" name="action" value="eep_email_event_attendees">
                                <input type="hidden" name="event_id" value="<?php echo esc_attr((string) ($attendees_panel['event_id'] ?? '0')); ?>">
                                <input type="hidden" name="eep_email_attendees_nonce" value="<?php echo esc_attr((string) ($attendees_panel['email_nonce'] ?? '')); ?>">
                                
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    <select name="audience" class="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 outline-none shadow-sm">
                                        <option value="confirmed"><?php esc_html_e('Confirmed only', 'nexdirectory'); ?></option>
                                        <option value="waitlist"><?php esc_html_e('Waitlist only', 'nexdirectory'); ?></option>
                                        <option value="all"><?php esc_html_e('Confirmed + Waitlist', 'nexdirectory'); ?></option>
                                    </select>
                                    <input type="text" name="subject" required placeholder="Email Subject..." class="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 outline-none shadow-sm">
                                </div>
                                <textarea name="message" rows="3" required placeholder="Type your message here..." class="w-full px-3 py-2.5 bg-white border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 outline-none shadow-sm resize-none"></textarea>
                                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="send_copy" value="1" class="w-4 h-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500">
                                        <span class="text-sm font-medium text-gray-700">Send me a copy</span>
                                    </label>
                                    <button type="submit" class="w-full sm:w-auto bg-brand-600 hover:bg-brand-700 text-white px-6 py-2.5 rounded-lg text-sm font-semibold transition-all active:scale-95 shadow-sm" style="background:var(--eep-primary,#FF5E14) !important; color:#ffffff !important;">Send Update</button>
                                </div>
                            </form>
                        </div>

                        <?php if (!empty($attendees_panel['rows'])) : ?>
                            <div class="border border-gray-200 rounded-xl overflow-hidden shadow-sm">
                                <div class="overflow-x-auto scrollbar-hide">
                                    <table class="w-full text-left text-sm text-gray-600 whitespace-nowrap">
                                        <thead class="bg-gray-50/50 text-xs uppercase text-gray-400 font-semibold border-b border-gray-100">
                                            <tr>
                                                <th class="px-5 py-3">Name</th>
                                                <th class="px-5 py-3">Email</th>
                                                <th class="px-5 py-3">Status</th>
                                                <th class="px-5 py-3">Ticket</th>
                                                <th class="px-5 py-3">Payment</th>
                                                <th class="px-5 py-3">Purchased</th>
                                                <th class="px-5 py-3">Comms</th>
                                            </tr>
                                        </thead>
                                        <tbody class="divide-y divide-gray-50">
                                            <?php foreach ((array) $attendees_panel['rows'] as $row) : ?>
                                                <tr class="hover:bg-gray-50/50 transition-colors">
                                                    <td class="px-5 py-3 font-medium text-gray-900"><?php echo esc_html((string) ($row['name'] ?? '')); ?></td>
                                                    <td class="px-5 py-3"><a href="mailto:<?php echo esc_attr((string) ($row['email'] ?? '')); ?>" class="text-brand-600 hover:text-brand-700 font-medium"><?php echo esc_html((string) ($row['email'] ?? '')); ?></a></td>
                                                    <td class="px-5 py-3"><span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider bg-gray-100 text-gray-600 border border-gray-200"><?php echo esc_html((string) ($row['status_label'] ?? '')); ?></span></td>
                                                    <td class="px-5 py-3">
                                                        <?php if (!empty($row['ticket_uid'])) : ?>
                                                            <div class="space-y-1">
                                                                <span class="inline-flex items-center px-2 py-1 rounded-md bg-gray-900 text-white text-[10px] font-semibold tracking-wide"><?php echo esc_html((string) $row['ticket_uid']); ?></span>
                                                                <?php if (!empty($row['ticket_verify_url'])) : ?>
                                                                    <a href="<?php echo esc_url((string) $row['ticket_verify_url']); ?>" target="_blank" rel="noopener noreferrer" class="block text-[11px] font-semibold text-brand-600 hover:text-brand-700"><?php esc_html_e('Verify', 'nexdirectory'); ?></a>
                                                                <?php endif; ?>
                                                            </div>
                                                        <?php else : ?>
                                                            <span class="text-gray-300">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td class="px-5 py-3">
                                                        <?php if (!empty($row['ticket_total_label']) || !empty($row['ticket_payment_method']) || !empty($row['ticket_payment_status_label'])) : ?>
                                                            <div class="space-y-1 text-[11px] leading-tight">
                                                                <?php if (!empty($row['ticket_total_label'])) : ?><div class="font-semibold text-gray-800"><?php echo esc_html((string) $row['ticket_total_label']); ?></div><?php endif; ?>
                                                                <?php if (!empty($row['ticket_payment_method'])) : ?><div class="text-gray-600"><?php echo esc_html((string) $row['ticket_payment_method']); ?></div><?php endif; ?>
                                                                <?php if (!empty($row['ticket_payment_status_label'])) : ?><div class="text-gray-500 uppercase tracking-wide"><?php echo esc_html((string) $row['ticket_payment_status_label']); ?></div><?php endif; ?>
                                                            </div>
                                                        <?php else : ?>
                                                            <span class="text-gray-300">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td class="px-5 py-3 text-xs text-gray-500"><?php echo esc_html((string) ($row['ticket_purchased_label'] ?? '-')); ?></td>
                                                    <td class="px-5 py-3">
                                                        <?php echo (string) ($row['communication_opt_in'] ?? '0') === '1' ? '<span class="text-green-600 font-bold text-xs uppercase tracking-wide">Yes</span>' : '<span class="text-gray-400 font-bold text-xs uppercase tracking-wide">No</span>'; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>

        </section>
        <?php endif; ?>
<?php
        $prefill = isset($prefill) && is_array($prefill) ? $prefill : [];
        $is_edit_mode = !empty($prefill['is_edit']);
        $singular_lower = sanitize_text_field((string) ($ui_labels['singular_lower'] ?? strtolower($singular_label)));
        $is_job_profile = (string) ($ui_labels['is_job_profile'] ?? '0') === '1';
        $is_directory_profile = (string) ($ui_labels['is_directory_profile'] ?? '0') === '1';
        $is_marketplace_profile = (string) ($ui_labels['is_marketplace_profile'] ?? '0') === '1';

        $show_schedule_builder = $is_events_profile;
        $show_event_mode_toggle = $is_events_profile;
        $show_price_range_toggle = $is_events_profile;
        $show_capacity_field = $is_events_profile;
        $show_official_classification = $is_events_profile;
        $show_date_block = $is_events_profile;
        $show_video_embeds_section = $is_events_profile || $is_marketplace_profile || $is_directory_profile;
        $show_stream_field = $is_events_profile;

        // Dynamic Labels setup (condensed for space)
        $submit_add_title = $is_job_profile ? __('Add Job', 'nexdirectory') : ($is_directory_profile ? __('Add Listing', 'nexdirectory') : ($is_marketplace_profile ? __('Add Listing', 'nexdirectory') : __('Add Event', 'nexdirectory')));
        $submit_edit_title = str_replace('Add', 'Edit', $submit_add_title);
        $submit_primary_cta = $is_edit_mode ? str_replace('Add', 'Update', $submit_add_title) : str_replace('Add', 'Submit', $submit_add_title);
        
        $submit_recaptcha_required = !empty($submit_recaptcha_required);
        $use_rich_editor = isset($use_rich_editor) ? $use_rich_editor : true;
        
        $custom_form_fields = isset($custom_form_fields) && is_array($custom_form_fields) ? $custom_form_fields : [];
        $custom_fields_enabled = isset($custom_fields_enabled) && (bool) $custom_fields_enabled;
        $per_event_email_templates_enabled = isset($per_event_email_templates_enabled) && (bool) $per_event_email_templates_enabled;
        $organizer_event_seo_enabled = isset($organizer_event_seo_enabled) ? (bool) $organizer_event_seo_enabled : ((string) get_option('eep_enable_event_seo_fields', '1') === '1');
        $serp_preview_url = '';
        $editing_event_id = !empty($prefill['edit_event_id']) ? absint((int) $prefill['edit_event_id']) : 0;
        if ($is_edit_mode && $editing_event_id > 0) {
            if (trim((string) ($prefill['post_title'] ?? '')) === '') {
                $prefill['post_title'] = (string) $this->recover_existing_event_title_value($editing_event_id, (string) get_the_title($editing_event_id));
                if (trim((string) $prefill['post_title']) === '') {
                    $prefill['post_title'] = sprintf(__('Untitled Listing #%d', 'nexdirectory'), $editing_event_id);
                }
            }
            if (trim((string) ($prefill['eep_start_raw'] ?? '')) === '') {
                $prefill['eep_start_raw'] = (string) $this->recover_existing_event_datetime_value($editing_event_id, 'eep_start');
            }
            if (trim((string) ($prefill['eep_end_raw'] ?? '')) === '') {
                $prefill['eep_end_raw'] = (string) $this->recover_existing_event_datetime_value($editing_event_id, 'eep_end');
            }
            if (trim((string) ($prefill['eep_cover_image_url'] ?? '')) === '') {
                $prefill['eep_cover_image_url'] = (string) $this->get_event_cover_image_url($editing_event_id, 'full', 'thumbnail');
                if (trim((string) $prefill['eep_cover_image_url']) === '' && has_post_thumbnail($editing_event_id)) {
                    $prefill['eep_cover_image_url'] = esc_url_raw((string) get_the_post_thumbnail_url($editing_event_id, 'full'));
                }
            }
        }
        if (!empty($prefill['edit_event_id'])) {
            $serp_preview_url = (string) get_permalink((int) $prefill['edit_event_id']);
        }
        if (!is_string($serp_preview_url) || $serp_preview_url === '') {
            $serp_preview_url = isset($events_url) && is_string($events_url) && $events_url !== '' ? (string) $events_url : (string) home_url('/events/');
        }
        $serp_preview_url = esc_url_raw($serp_preview_url);

        // Date Parsing for Prefill
        $prefill_start_raw = str_replace('T', ' ', (string) ($prefill['eep_start_raw'] ?? $prefill['eep_start_local'] ?? ''));
        $prefill_end_raw = str_replace('T', ' ', (string) ($prefill['eep_end_raw'] ?? $prefill['eep_end_local'] ?? ''));
        $prefill_start_date = preg_match('/^(\d{4}-\d{2}-\d{2})/', $prefill_start_raw, $m) ? $m[1] : '';
        $prefill_start_time = preg_match('/\b(\d{2}:\d{2})\b/', $prefill_start_raw, $m) ? $m[1] : '';
        $prefill_end_date = preg_match('/^(\d{4}-\d{2}-\d{2})/', $prefill_end_raw, $m) ? $m[1] : '';
        $prefill_end_time = preg_match('/\b(\d{2}:\d{2})\b/', $prefill_end_raw, $m) ? $m[1] : '';

        // Alpine JSON setup
        $alpine_prefill = [
            'titleValue' => (string) ($prefill['post_title'] ?? ''),
            'excerptValue' => (string) ($prefill['post_excerpt'] ?? ''),
            'coverImage' => (string) ($prefill['eep_cover_image_url'] ?? ''),
            'galleryImages' => array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string) ($prefill['eep_gallery_urls'] ?? '')) ?: []))),
            'videoUrlsTextarea' => $show_video_embeds_section ? (string) ($prefill['eep_video_urls'] ?? '') : '',
            'videoEmbeds' => $show_video_embeds_section ? array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string) ($prefill['eep_video_urls'] ?? '')) ?: []))) ?: [''] : [],
            'startValue' => $prefill_start_date, 'startTimeValue' => $prefill_start_time,
            'endValue' => $prefill_end_date, 'endTimeValue' => $prefill_end_time,
            'cityValue' => (string) ($prefill['eep_city'] ?? ''), 'countryValue' => (string) ($prefill['eep_country'] ?? ''),
            'latValue' => (string) ($prefill['eep_lat'] ?? ''), 'lngValue' => (string) ($prefill['eep_lng'] ?? ''),
            'streamUrl' => $show_stream_field ? (string) ($prefill['eep_event_stream_url'] ?? '') : '',
            'metaTitleValue' => (string) ($prefill['eep_meta_title'] ?? ''),
            'metaDescriptionValue' => (string) ($prefill['eep_meta_description'] ?? ''),
            'serpUrl' => $serp_preview_url,
            'modeOption' => (string) ($prefill['eep_event_mode_option'] ?? 'in-person'),
            'isRecurring' => (string) ($prefill['eep_is_recurring'] ?? '0') === '1' ? '1' : '0',
            'sessions' => is_array($prefill['sessions'] ?? null) ? array_values((array) $prefill['sessions']) : [],
            'keySpeakers' => is_array($prefill['key_speakers'] ?? null) ? array_values((array) $prefill['key_speakers']) : [],
            'recurrenceUntil' => (string) ($prefill['eep_recurrence_until'] ?? ''),
        ];
        $alpine_json_flags = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
        if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
            $alpine_json_flags |= JSON_INVALID_UTF8_SUBSTITUTE;
        }
        $alpine_prefill_json = wp_json_encode($alpine_prefill, $alpine_json_flags);
        ?>

        <?php if ($show_submit_tab) : ?>
        <section x-show="activeTab === 'submit'" x-transition.opacity.duration.300ms x-cloak>
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6 sm:mb-8">
                <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php echo esc_html($is_edit_mode ? $submit_edit_title : $submit_add_title); ?></h2>
                <p class="text-sm sm:text-base text-gray-500 max-w-2xl">
                    <?php echo esc_html($is_edit_mode 
                        ? __('Update your details using the form below. Changes may require moderation.', 'nexdirectory') 
                        : __('Submit your details for review and publication.', 'nexdirectory')); ?>
                </p>
            </div>

            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-100">
                <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'submit', admin_url('admin-post.php'))); ?>#submit" enctype="multipart/form-data" id="eep-submit-form" class="space-y-6 sm:space-y-8" 
                      x-data='eepSubmitForm(<?php echo $alpine_prefill_json ?: '{}'; ?>)' 
                      data-eep-editing="<?php echo $is_edit_mode ? '1' : '0'; ?>" 
                      data-eep-requires-address="<?php echo ($is_events_profile || $is_directory_profile) ? '1' : '0'; ?>"
                      data-eep-initial-sessions="<?php echo esc_attr(wp_json_encode((array) ($prefill['sessions'] ?? []))); ?>" 
                      data-eep-recurrence-until="<?php echo esc_attr((string) ($prefill['eep_recurrence_until'] ?? '')); ?>">
                    
                    <input type="hidden" name="action" value="eep_submit_event">
                    <input type="hidden" name="eep_edit_post_id" value="<?php echo esc_attr((string) ($prefill['edit_event_id'] ?? '0')); ?>">
                    <?php wp_nonce_field('eep_submit_event_nonce', 'eep_nonce'); ?>
                    <input type="hidden" name="eep_website" class="eep-honeypot" tabindex="-1" autocomplete="off" aria-hidden="true">
                    <input type="hidden" name="eep_recaptcha_token" class="<?php echo $submit_recaptcha_required ? 'eep-recaptcha-token' : ''; ?>" value="">
                    
                    <input type="hidden" name="eep_sessions" :value="JSON.stringify(sessions)">
                    <input type="hidden" name="eep_key_speakers" :value="JSON.stringify(keySpeakers)">
                    <input type="hidden" name="eep_autosave_post_id" x-model="autosavePostId">
                    <input type="hidden" name="eep_recurrence" :value="isRecurring === '1' ? 'custom' : 'none'">
                    <input type="hidden" name="eep_recurrence_until" :value="recurrenceUntil">
                    <input type="hidden" name="eep_lat" id="eep-lat-input" x-model="latValue" value="<?php echo esc_attr((string) ($prefill['eep_lat'] ?? '')); ?>">
                    <input type="hidden" name="eep_lng" id="eep-lng-input" x-model="lngValue" value="<?php echo esc_attr((string) ($prefill['eep_lng'] ?? '')); ?>">
                    <input type="hidden" name="eep_country" x-model="countryValue" value="<?php echo esc_attr((string) ($prefill['eep_country'] ?? '')); ?>">

                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                            <h3 class="font-bold text-gray-900 flex items-center gap-2">
                                <svg class="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                <?php esc_html_e('General Information', 'nexdirectory'); ?>
                            </h3>
                        </div>
                        <div class="p-5 sm:p-6 space-y-5">
                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Title', 'nexdirectory'); ?></label>
                                <input type="text" name="post_title" required x-model="titleValue" value="<?php echo esc_attr((string) ($prefill['post_title'] ?? '')); ?>" @input.debounce.150ms="validateTitle" placeholder="<?php esc_attr_e('Listing name...', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                <p class="text-[11px] text-gray-500 mt-1" x-text="titleCounterText()"></p>
                                <p class="text-xs text-red-500 mt-1" x-show="titleError" x-text="titleError" x-cloak></p>
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Description', 'nexdirectory'); ?></label>
                                <?php if ($use_rich_editor && function_exists('wp_editor')) : ?>
                                    <div class="border border-gray-200 rounded-xl overflow-hidden focus-within:ring-2 focus-within:ring-brand-500 focus-within:border-brand-500 transition-all shadow-sm">
                                        <?php wp_editor((string) ($prefill['post_content'] ?? ''), 'eep_post_content_editor', ['textarea_name' => 'post_content', 'textarea_rows' => 8, 'media_buttons' => false, 'teeny' => true, 'tinymce' => ['wpautop' => true]]); ?>
                                    </div>
                                <?php else : ?>
                                    <textarea name="post_content" rows="6" required class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm resize-y"></textarea>
                                <?php endif; ?>
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Short Summary (Optional)', 'nexdirectory'); ?></label>
                                <textarea name="post_excerpt" rows="2" maxlength="220" x-model="excerptValue" @input="validateExcerpt" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm resize-none"><?php echo esc_textarea((string) ($prefill['post_excerpt'] ?? '')); ?></textarea>
                                <p class="text-[11px] text-gray-500 mt-1" x-text="excerptCounterText()"></p>
                                <p class="text-xs text-red-500 mt-1" x-show="excerptError" x-text="excerptError" x-cloak></p>
                            </div>

                            <?php if ($organizer_event_seo_enabled) : ?>
                            <div class="rounded-2xl border border-amber-200 bg-amber-50/60 p-4 sm:p-5 space-y-4">
                                <div class="flex items-start justify-between gap-3">
                                    <div>
                                        <h4 class="text-sm sm:text-base font-bold text-gray-900"><?php esc_html_e('SEO Snippet Preview', 'nexdirectory'); ?></h4>
                                        <p class="text-xs text-gray-600"><?php esc_html_e('Control how this event appears in Google results.', 'nexdirectory'); ?></p>
                                    </div>
                                    <button type="button" @click="fillSeoFromContent()" class="inline-flex items-center justify-center px-3 py-2 rounded-lg border border-amber-300 text-amber-700 hover:bg-amber-100 text-xs font-semibold transition-colors">
                                        <?php esc_html_e('Use Title + Summary', 'nexdirectory'); ?>
                                    </button>
                                </div>

                                <div class="grid grid-cols-1 gap-4">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Meta Title', 'nexdirectory'); ?></label>
                                        <input type="text" name="eep_meta_title" maxlength="60" x-model="metaTitleValue" @input="queueAutosave(220)" placeholder="<?php esc_attr_e('Best between 50 and 60 characters', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                        <div class="mt-1 flex items-center justify-between gap-3">
                                            <p class="text-[11px] text-gray-600"><span x-text="seoTitleCount()"></span> / 60</p>
                                            <p class="text-[11px] font-medium" :class="seoTitleStatusClass()" x-text="seoTitleStatusText()"></p>
                                        </div>
                                    </div>

                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Meta Description', 'nexdirectory'); ?></label>
                                        <textarea name="eep_meta_description" rows="3" maxlength="158" x-model="metaDescriptionValue" @input="queueAutosave(220)" placeholder="<?php esc_attr_e('Best between 120 and 158 characters', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm resize-y"></textarea>
                                        <div class="mt-1 flex items-center justify-between gap-3">
                                            <p class="text-[11px] text-gray-600"><span x-text="seoDescriptionCount()"></span> / 158</p>
                                            <p class="text-[11px] font-medium" :class="seoDescriptionStatusClass()" x-text="seoDescriptionStatusText()"></p>
                                        </div>
                                    </div>
                                </div>

                                <div class="rounded-xl bg-white border border-gray-200 p-4 shadow-sm">
                                    <p class="text-xs text-green-700 truncate" x-text="serpUrlPreview()"></p>
                                    <p class="text-lg leading-6 text-[#1a0dab] hover:underline cursor-pointer mt-1" x-text="serpTitlePreview()"></p>
                                    <p class="text-sm text-[#4d5156] mt-1 leading-5" x-text="serpDescriptionPreview()"></p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                            <h3 class="font-bold text-gray-900 flex items-center gap-2">
                                <svg class="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                <?php esc_html_e('Media & Images', 'nexdirectory'); ?>
                            </h3>
                        </div>
                        <div class="p-5 sm:p-6 space-y-6">
                            
                            <input type="file" name="eep_cover_file" x-ref="coverFileInput" accept="image/*" style="display:none;" @change="handleFileSelect($event, 'cover')">
                            <input type="file" name="eep_gallery_files[]" x-ref="galleryFileInput" accept="image/*" multiple style="display:none;" @change="handleFileSelect($event, 'gallery')">
                            
                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Cover Image', 'nexdirectory'); ?></label>
                                <div class="relative border-2 border-dashed border-gray-300 rounded-2xl hover:border-brand-400 bg-gray-50 hover:bg-brand-50 transition-colors cursor-pointer overflow-hidden min-h-[160px] flex items-center justify-center group" @dragover.prevent @drop.prevent="handleDrop($event, 'cover')" @click="openMedia('cover')">
                                    <template x-if="coverImage">
                                        <div class="absolute inset-0">
                                            <img :src="coverImage" class="w-full h-full object-cover">
                                            <div class="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                                                <span class="text-white font-semibold text-sm bg-black/50 px-3 py-1.5 rounded-lg">Change Image</span>
                                            </div>
                                            <button type="button" @click.stop="removeCover()" class="absolute top-2 right-2 bg-red-500 text-white rounded-full p-1.5 hover:bg-red-600 transition-colors shadow-sm">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                            </button>
                                        </div>
                                    </template>
                                    <template x-if="!coverImage">
                                        <div class="text-center p-6 pointer-events-none">
                                            <svg class="mx-auto h-10 w-10 text-gray-400 mb-2" stroke="currentColor" fill="none" viewBox="0 0 48 48"><path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                                            <p class="text-sm text-gray-600 font-medium">Click to upload or drag and drop</p>
                                            <p class="text-[11px] text-gray-400 mt-1">PNG, JPG up to 10MB</p>
                                        </div>
                                    </template>
                                </div>
                                <input type="hidden" name="eep_cover_image_url" x-model="coverImage">
                            </div>

                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Gallery Images (Optional)', 'nexdirectory'); ?></label>
                                <div class="relative border-2 border-dashed border-gray-300 rounded-2xl hover:border-brand-400 bg-gray-50 hover:bg-brand-50 transition-colors cursor-pointer py-6 flex items-center justify-center group" @dragover.prevent @drop.prevent="handleDrop($event, 'gallery')" @click="openMedia('gallery')">
                                    <div class="text-center pointer-events-none">
                                        <p class="text-sm text-gray-600 font-medium">Add to gallery (multiple allowed)</p>
                                    </div>
                                </div>
                                <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-4" x-show="galleryImages.length" x-cloak>
                                    <template x-for="(url, index) in galleryImages" :key="index">
                                        <div class="relative aspect-square rounded-xl overflow-hidden border border-gray-200 shadow-sm group">
                                            <img :src="url" class="w-full h-full object-cover">
                                            <button type="button" @click.stop="removeGallery(index)" class="absolute top-1 right-1 bg-red-500/90 text-white rounded-full p-1 hover:bg-red-600 transition-colors shadow-sm opacity-0 group-hover:opacity-100">
                                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                            </button>
                                        </div>
                                    </template>
                                </div>
                                <textarea name="eep_gallery_urls" x-model="galleryTextarea" style="display:none;"></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                            <h3 class="font-bold text-gray-900 flex items-center gap-2">
                                <svg class="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                <?php esc_html_e('Contact & Location', 'nexdirectory'); ?>
                            </h3>
                        </div>
                        <div class="p-5 sm:p-6 space-y-6">
                            
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Phone Number (Optional)', 'nexdirectory'); ?></label>
                                    <input type="text" name="eep_contact_phone" value="<?php echo esc_attr((string) ($prefill['eep_contact_phone'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                </div>
                                <div>
                                    <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Contact Email (Optional)', 'nexdirectory'); ?></label>
                                    <input type="email" name="eep_contact_email" value="<?php echo esc_attr((string) ($prefill['eep_contact_email'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                </div>
                            </div>

                            <hr class="border-gray-100">

                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Address', 'nexdirectory'); ?></label>
                                <input type="text" name="eep_address" id="eep-address-input" list="eep-address-suggestions" value="<?php echo esc_attr((string) ($prefill['eep_address'] ?? '')); ?>" placeholder="Start typing to search..." <?php echo ($is_events_profile || $is_directory_profile) ? 'required' : ''; ?> class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                <datalist id="eep-address-suggestions"></datalist>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('City / Area', 'nexdirectory'); ?></label>
                                    <input type="text" name="eep_city" x-model="cityValue" value="<?php echo esc_attr((string) ($prefill['eep_city'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm bg-gray-50">
                                </div>
                                <div>
                                    <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Venue Name (Optional)', 'nexdirectory'); ?></label>
                                    <input type="text" name="eep_venue" value="<?php echo esc_attr((string) ($prefill['eep_venue'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none transition-all shadow-sm">
                                </div>
                            </div>

                            <button type="button" id="eep-geocode-btn" class="w-full sm:w-auto px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-800 text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95 border border-gray-200">
                                <?php esc_html_e('Preview Location on Map', 'nexdirectory'); ?>
                            </button>
                            <div id="eep-location-preview" class="w-full h-48 sm:h-64 bg-gray-100 rounded-xl border border-gray-200 overflow-hidden shadow-inner hidden"></div>

                        </div>
                    </div>

                    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden">
                        <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                            <h3 class="font-bold text-gray-900 flex items-center gap-2">
                                <svg class="w-5 h-5 text-brand-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg>
                                <?php esc_html_e('Listing Specific Details', 'nexdirectory'); ?>
                            </h3>
                        </div>
                        <div class="p-5 sm:p-6 space-y-6">

                            <?php if ($is_job_profile) : ?>
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Company Name</label>
                                        <input type="text" name="eep_company_name" required value="<?php echo esc_attr((string) ($prefill['eep_company_name'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Employment Type</label>
                                        <select name="eep_job_type" required class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                            <option value="">Select type</option>
                                            <?php foreach (['Full-time', 'Part-time', 'Contract', 'Internship', 'Temporary', 'Freelance'] as $opt) : ?>
                                                <option value="<?php echo esc_attr($opt); ?>" <?php selected((string) ($prefill['eep_job_type'] ?? ''), $opt); ?>><?php echo esc_html($opt); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Work Location Type</label>
                                        <select name="eep_job_work_mode" required class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                            <option value="">Select location type</option>
                                            <option value="on-site" <?php selected((string) ($prefill['eep_job_work_mode'] ?? ''), 'on-site'); ?>>On-site</option>
                                            <option value="hybrid" <?php selected((string) ($prefill['eep_job_work_mode'] ?? ''), 'hybrid'); ?>>Hybrid</option>
                                            <option value="remote" <?php selected((string) ($prefill['eep_job_work_mode'] ?? ''), 'remote'); ?>>Remote</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Salary Range</label>
                                        <input type="text" name="eep_job_salary" required placeholder="e.g. £55,000 - £72,000" value="<?php echo esc_attr((string) ($prefill['eep_job_salary'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Application Deadline</label>
                                        <input type="date" name="eep_job_closing_date" required value="<?php echo esc_attr((string) ($prefill['eep_job_closing_date'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Application URL</label>
                                        <input type="url" name="eep_job_apply_url" placeholder="https://..." value="<?php echo esc_attr((string) ($prefill['eep_job_apply_url'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                </div>
                            
                            <?php elseif ($is_directory_profile) : ?>
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Business Name</label>
                                        <input type="text" name="eep_company_name" required value="<?php echo esc_attr((string) ($prefill['eep_company_name'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Business Type</label>
                                        <select name="eep_directory_business_type" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                            <option value="independent-business">Independent Business</option>
                                            <option value="agency">Agency</option>
                                            <option value="private-owner">Private Owner</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Service Area (Optional)</label>
                                        <input type="text" name="eep_directory_service_area" placeholder="London + 25 miles..." value="<?php echo esc_attr((string) ($prefill['eep_directory_service_area'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Operating Hours (Optional)</label>
                                        <input type="text" name="eep_directory_operating_hours" placeholder="Mon-Fri 09:00-18:00" value="<?php echo esc_attr((string) ($prefill['eep_directory_operating_hours'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                </div>
                            
                            <?php elseif ($is_marketplace_profile) : ?>
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Condition</label>
                                        <select name="eep_market_condition" required class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer">
                                            <option value="">Select condition</option>
                                            <?php foreach (['New', 'Like New', 'Used', 'Refurbished', 'For Parts'] as $opt) : ?>
                                                <option value="<?php echo esc_attr($opt); ?>" <?php selected((string) ($prefill['eep_market_condition'] ?? ''), $opt); ?>><?php echo esc_html($opt); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Asking Price</label>
                                        <input type="text" name="eep_price" required placeholder="e.g. £120" value="<?php echo esc_attr((string) ($prefill['eep_price'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                </div>
                                
                            <?php else : ?>
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Start Date</label>
                                        <input type="date" name="eep_start_date" required x-model="startValue" value="<?php echo esc_attr((string) $prefill_start_date); ?>" @input="validateDates" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                        <label class="block text-sm font-semibold text-gray-900 mt-3 mb-1.5">Start Time (Optional)</label>
                                        <input type="time" name="eep_start_time" x-model="startTimeValue" value="<?php echo esc_attr((string) $prefill_start_time); ?>" @input="validateDates" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">End Date</label>
                                        <input type="date" name="eep_end_date" x-model="endValue" value="<?php echo esc_attr((string) $prefill_end_date); ?>" @input="validateDates" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                        <label class="block text-sm font-semibold text-gray-900 mt-3 mb-1.5">End Time (Optional)</label>
                                        <input type="time" name="eep_end_time" x-model="endTimeValue" value="<?php echo esc_attr((string) $prefill_end_time); ?>" @input="validateDates" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5">Capacity (Optional)</label>
                                        <input type="number" name="eep_capacity" min="0" value="<?php echo esc_attr((string) ($prefill['eep_capacity'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                    </div>
                                </div>
                                <p class="text-xs text-red-500 font-medium" x-show="dateError" x-text="dateError" x-cloak></p>

                                <div class="border border-gray-200 rounded-2xl p-4 sm:p-5 bg-gray-50/40" x-data="{ ticketEnabled: <?php echo ((string) ($prefill['eep_ticket_sales_enabled'] ?? '0') === '1') ? 'true' : 'false'; ?> }">
                                    <input type="hidden" name="eep_ticket_sales_enabled" :value="ticketEnabled ? '1' : '0'">
                                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
                                        <div>
                                            <h4 class="text-base sm:text-lg font-bold text-gray-900"><?php esc_html_e('Ticket Sales', 'nexdirectory'); ?></h4>
                                            <p class="text-xs text-gray-500"><?php esc_html_e('Enable ticket checkout for this event. Set price to 0 for free tickets.', 'nexdirectory'); ?></p>
                                        </div>
                                        <label class="inline-flex items-center gap-2 text-sm font-semibold text-gray-700 cursor-pointer">
                                            <input type="checkbox" class="w-4 h-4 text-brand-600 border-gray-300 rounded focus:ring-brand-500" x-model="ticketEnabled">
                                            <?php esc_html_e('Enable', 'nexdirectory'); ?>
                                        </label>
                                    </div>
                                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4" x-show="ticketEnabled" x-cloak>
                                        <div>
                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Ticket Price', 'nexdirectory'); ?></label>
                                            <input type="number" name="eep_ticket_price" min="0" step="0.01" placeholder="0.00" value="<?php echo esc_attr((string) ($prefill['eep_ticket_price'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                        </div>
                                        <div>
                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Ticket Button Label (Optional)', 'nexdirectory'); ?></label>
                                            <input type="text" name="eep_ticket_button_label" maxlength="80" placeholder="<?php esc_attr_e('Buy Tickets', 'nexdirectory'); ?>" value="<?php echo esc_attr((string) ($prefill['eep_ticket_button_label'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if ($is_events_profile) : ?>
                                <div class="space-y-4 border border-gray-200 rounded-2xl p-4 sm:p-5 bg-gray-50/40">
                                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                                        <div>
                                            <h4 class="text-base sm:text-lg font-bold text-gray-900"><?php esc_html_e('Event Itinerary', 'nexdirectory'); ?></h4>
                                            <p class="text-xs text-gray-500"><?php esc_html_e('Add schedule rows with date/day, speaker, notes, and attachment links.', 'nexdirectory'); ?></p>
                                        </div>
                                    </div>

                                    <p class="text-xs text-gray-500" x-show="!sessions.length" x-cloak><?php esc_html_e('No itinerary rows yet. Add one below.', 'nexdirectory'); ?></p>

                                    <div class="relative" x-show="sessions.length" x-cloak>
                                        <template x-for="(session, index) in sessions" :key="'session-' + index">
                                            <div class="relative pl-10 pb-6 last:pb-0">
                                                <span class="absolute left-0 top-6 flex w-5 h-5 items-center justify-center rounded-full bg-brand-500 border-4 border-white shadow-sm"></span>
                                                <span class="absolute left-[9px] top-11 bottom-0 w-px bg-gradient-to-b from-brand-200 via-gray-200 to-gray-200" x-show="index < (sessions.length - 1)" x-cloak></span>

                                                <div class="bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-4">
                                                    <div class="flex items-center justify-between gap-3">
                                                        <h5 class="text-sm font-bold text-gray-900" x-text="'Session ' + (index + 1)"></h5>
                                                        <button type="button" @click="removeSession(index)" class="inline-flex items-center gap-1.5 px-3 py-1.5 border border-red-200 text-red-600 bg-red-50 hover:bg-red-100 rounded-lg text-xs font-semibold transition-colors active:scale-95">
                                                            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                                            <?php esc_html_e('Remove', 'nexdirectory'); ?>
                                                        </button>
                                                    </div>

                                                    <div class="space-y-3">
                                                        <div class="relative pl-7 pb-3">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <span class="absolute left-[4px] top-5 bottom-0 w-px bg-gray-200"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Session Name', 'nexdirectory'); ?></label>
                                                            <input type="text" x-model="sessions[index].title" placeholder="<?php esc_attr_e('Opening Ceremony', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7 pb-3">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <span class="absolute left-[4px] top-5 bottom-0 w-px bg-gray-200"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Start Time', 'nexdirectory'); ?></label>
                                                            <input type="datetime-local" x-model="sessions[index].start" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7 pb-3">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <span class="absolute left-[4px] top-5 bottom-0 w-px bg-gray-200"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('End Time', 'nexdirectory'); ?></label>
                                                            <input type="datetime-local" x-model="sessions[index].end" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7 pb-3">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <span class="absolute left-[4px] top-5 bottom-0 w-px bg-gray-200"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Location', 'nexdirectory'); ?></label>
                                                            <input type="text" x-model="sessions[index].location" placeholder="<?php esc_attr_e('Main Hall', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Speaker', 'nexdirectory'); ?></label>
                                                            <input type="text" x-model="sessions[index].speaker" placeholder="<?php esc_attr_e('Speaker Name', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Day Label (Optional)', 'nexdirectory'); ?></label>
                                                            <input type="text" x-model="sessions[index].day" placeholder="<?php esc_attr_e('Day 1 or Jun 9, 2026', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                        </div>

                                                        <div class="relative pl-7">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Notes (Optional)', 'nexdirectory'); ?></label>
                                                            <textarea x-model="sessions[index].notes" rows="3" placeholder="<?php esc_attr_e('Add session notes, reminders, or key points.', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all resize-y"></textarea>
                                                        </div>

                                                        <div class="relative pl-7">
                                                            <span class="absolute left-0 top-3 w-2.5 h-2.5 rounded-full bg-brand-400"></span>
                                                            <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Attachment URLs (Optional)', 'nexdirectory'); ?></label>
                                                            <textarea x-model="sessions[index].attachments" rows="3" placeholder="<?php esc_attr_e('One URL per line (file URL, image URL, or YouTube URL)', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all resize-y"></textarea>
                                                            <p class="mt-1.5 text-xs text-gray-500"><?php esc_html_e('Upload files, pick from media library, or paste direct links and YouTube URLs.', 'nexdirectory'); ?></p>
                                                            <div class="mt-2 flex flex-wrap gap-2">
                                                                <button type="button" @click="triggerSessionAttachmentInput(index)" class="inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-lg text-xs font-semibold transition-colors">
                                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1M8 12l4-4m0 0l4 4m-4-4v12"></path></svg>
                                                                    <?php esc_html_e('Upload File', 'nexdirectory'); ?>
                                                                </button>
                                                                <button type="button" @click="openSessionAttachmentMediaPicker(index)" class="inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-lg text-xs font-semibold transition-colors">
                                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7h18M3 12h18M3 17h18"></path></svg>
                                                                    <?php esc_html_e('Media Library', 'nexdirectory'); ?>
                                                                </button>
                                                            </div>
                                                            <input type="file" class="eep-session-attachment-upload" :id="'eep-session-attachment-upload-' + index" @change="handleSessionAttachmentUpload($event, index)" multiple accept="image/*,video/*,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.zip,.csv,.json,.rtf,.odt,.ods,.odp,.mp4,.mov,.webm,.m4v,.avi,.mkv" hidden>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </template>
                                    </div>

                                    <div class="pt-1 pl-0 sm:pl-10">
                                        <button type="button" @click="addSession()" class="inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-brand-50 hover:bg-brand-100 border border-brand-200 text-brand-700 text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                                            <?php esc_html_e('Add Itinerary Row', 'nexdirectory'); ?>
                                        </button>
                                    </div>
                                </div>

                                <div class="space-y-4 border border-gray-200 rounded-2xl p-4 sm:p-5 bg-gray-50/40">
                                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                                        <div>
                                            <h4 class="text-base sm:text-lg font-bold text-gray-900"><?php esc_html_e('Key Speakers', 'nexdirectory'); ?></h4>
                                            <p class="text-xs text-gray-500"><?php esc_html_e('Add featured speakers with their role, topic, and profile image.', 'nexdirectory'); ?></p>
                                        </div>
                                        <button type="button" @click="addKeySpeaker()" class="inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-brand-50 hover:bg-brand-100 border border-brand-200 text-brand-700 text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                                            <?php esc_html_e('Add Key Speaker', 'nexdirectory'); ?>
                                        </button>
                                    </div>

                                    <p class="text-xs text-gray-500" x-show="!keySpeakers.length" x-cloak><?php esc_html_e('No key speakers added yet.', 'nexdirectory'); ?></p>

                                    <div class="space-y-4" x-show="keySpeakers.length" x-cloak>
                                        <template x-for="(speaker, index) in keySpeakers" :key="'speaker-' + index">
                                            <div class="bg-white border border-gray-200 rounded-xl p-4 shadow-sm space-y-4">
                                                <div class="flex items-center justify-between gap-3">
                                                    <h5 class="text-sm font-bold text-gray-900" x-text="'Speaker ' + (index + 1)"></h5>
                                                    <button type="button" @click="removeKeySpeaker(index)" class="inline-flex items-center gap-1.5 px-3 py-1.5 border border-red-200 text-red-600 bg-red-50 hover:bg-red-100 rounded-lg text-xs font-semibold transition-colors active:scale-95">
                                                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                                        <?php esc_html_e('Remove', 'nexdirectory'); ?>
                                                    </button>
                                                </div>

                                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                                    <div>
                                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Name', 'nexdirectory'); ?></label>
                                                        <input type="text" x-model="keySpeakers[index].name" placeholder="<?php esc_attr_e('Jane Smith', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                    </div>
                                                    <div>
                                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Profession', 'nexdirectory'); ?></label>
                                                        <input type="text" x-model="keySpeakers[index].profession" placeholder="<?php esc_attr_e('Civil Engineer', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                    </div>
                                                    <div>
                                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Subject', 'nexdirectory'); ?></label>
                                                        <input type="text" x-model="keySpeakers[index].subject" placeholder="<?php esc_attr_e('Future of Infrastructure', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                                                    </div>
                                                    <div class="sm:col-span-2">
                                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Speaker Image', 'nexdirectory'); ?></label>
                                                        <input type="hidden" x-model="keySpeakers[index].image">
                                                        <input type="file" class="eep-speaker-image-upload" :id="'eep-speaker-image-upload-' + index" @change="handleSpeakerImageUpload($event, index)" accept="image/*" hidden>
                                                        <div class="border border-dashed border-gray-300 rounded-xl p-3 bg-gray-50">
                                                            <template x-if="keySpeakers[index].image">
                                                                <div class="mb-3">
                                                                    <img :src="keySpeakers[index].image" class="w-20 h-20 rounded-lg object-cover border border-gray-200 shadow-sm" alt="">
                                                                </div>
                                                            </template>
                                                            <div class="flex flex-wrap gap-2">
                                                                <button type="button" @click="triggerSpeakerImageInput(index)" class="inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-lg text-xs font-semibold transition-colors">
                                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1M8 12l4-4m0 0l4 4m-4-4v12"></path></svg>
                                                                    <?php esc_html_e('Upload Image', 'nexdirectory'); ?>
                                                                </button>
                                                                <button type="button" @click="openSpeakerImageMediaPicker(index)" class="inline-flex items-center gap-1.5 px-3 py-2 border border-gray-300 text-gray-700 bg-white hover:bg-gray-50 rounded-lg text-xs font-semibold transition-colors">
                                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7h18M3 12h18M3 17h18"></path></svg>
                                                                    <?php esc_html_e('Media Library', 'nexdirectory'); ?>
                                                                </button>
                                                                <button type="button" @click="removeSpeakerImage(index)" x-show="keySpeakers[index].image" x-cloak class="inline-flex items-center gap-1.5 px-3 py-2 border border-red-200 text-red-600 bg-red-50 hover:bg-red-100 rounded-lg text-xs font-semibold transition-colors">
                                                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                                                                    <?php esc_html_e('Remove', 'nexdirectory'); ?>
                                                                </button>
                                                            </div>
                                                            <p class="mt-2 text-xs text-gray-500"><?php esc_html_e('Upload a new image or pick one from your media library.', 'nexdirectory'); ?></p>
                                                        </div>
                                                    </div>
                                                    <div class="sm:col-span-2">
                                                        <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Details (Optional)', 'nexdirectory'); ?></label>
                                                        <textarea x-model="keySpeakers[index].details" rows="3" placeholder="<?php esc_attr_e('Short bio or speaking notes.', 'nexdirectory'); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all resize-y"></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Category (Optional)', 'nexdirectory'); ?></label>
                                <div class="relative">
                                    <?php
                                    wp_dropdown_categories([
                                        'taxonomy' => $this::TAX_TYPE ?? 'category',
                                        'name' => 'event_type',
                                        'show_option_none' => __('Select Category', 'nexdirectory'),
                                        'hide_empty' => false,
                                        'selected' => (int) ($prefill['event_type_term_id'] ?? 0),
                                        'class' => 'w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all appearance-none cursor-pointer',
                                    ]);
                                    ?>
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-semibold text-gray-900 mb-1.5"><?php esc_html_e('Tags (Optional)', 'nexdirectory'); ?></label>
                                <input type="text" name="event_tags" placeholder="Comma separated..." value="<?php echo esc_attr((string) ($prefill['event_tags'] ?? '')); ?>" class="w-full px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 shadow-sm outline-none transition-all">
                            </div>

                        </div>
                    </div>

                    <div class="fixed md:sticky bottom-[70px] md:bottom-0 left-0 right-0 z-30 bg-white/95 backdrop-blur-md border-t border-gray-200 p-4 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)] md:rounded-t-2xl mt-8 flex flex-col-reverse sm:flex-row items-center justify-between gap-4">
                        <span class="text-xs text-gray-500 font-medium" x-text="autosaveMessage"></span>
                        
                        <div class="flex items-center gap-3 w-full sm:w-auto">
                            <button type="submit" name="eep_intent" value="draft" class="flex-1 sm:flex-none px-6 py-3 bg-gray-100 hover:bg-gray-200 text-gray-800 text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95 border border-gray-200 text-center">
                                <?php esc_html_e('Save Draft', 'nexdirectory'); ?>
                            </button>
                            <button type="submit" name="eep_intent" value="preview" class="flex-1 sm:flex-none px-6 py-3 bg-white hover:bg-gray-50 text-gray-800 text-sm font-semibold rounded-xl transition-all shadow-sm active:scale-95 border border-gray-200 text-center">
                                <?php echo esc_html(sprintf(__('Preview %s', 'nexdirectory'), $singular_label)); ?>
                            </button>
                            <button type="submit" name="eep_intent" value="pending" :disabled="hasBlockingErrors()" :class="{ 'opacity-50 cursor-not-allowed': hasBlockingErrors() }" class="eep-force-accent-action flex-1 sm:flex-none px-6 py-3 bg-brand-600 hover:bg-brand-700 text-white text-sm font-bold rounded-xl transition-all shadow-sm active:scale-95 text-center">
                                <?php echo esc_html($submit_primary_cta); ?>
                            </button>
                        </div>
                    </div>

                </form>
            </div>

        </section>
        <?php endif; ?>
<?php
        // Inbox specific variables mapping
        $notifications_title = sanitize_text_field((string) ($notifications_title ?? __('Inbox', 'nexdirectory')));
        $notifications_description = sanitize_text_field((string) ($notifications_description ?? __('View and reply to inbox messages.', 'nexdirectory')));
        $threads = isset($threads) && is_array($threads) ? $threads : [];
        $active_thread_id = isset($active_thread_id) ? absint((int) $active_thread_id) : 0;
        $active_thread = isset($active_thread) && is_array($active_thread) ? $active_thread : [];
        $active_messages = isset($active_messages) && is_array($active_messages) ? $active_messages : [];
        $active_subject = sanitize_text_field((string) ($active_subject ?? ''));
        $active_event_title = sanitize_text_field((string) ($active_event_title ?? ''));
        $active_event_url = isset($active_event_url) ? esc_url((string) $active_event_url) : '';
        $active_other_name = sanitize_text_field((string) ($active_other_name ?? __('Member', 'nexdirectory')));
        $reply_action = isset($reply_action) ? esc_url((string) $reply_action) : esc_url(admin_url('admin-post.php'));
        $reply_nonce = sanitize_text_field((string) ($reply_nonce ?? ''));
        $reply_subject = sanitize_text_field((string) ($reply_subject ?? $active_subject));
        $unread_count = isset($unread_count) ? absint((int) $unread_count) : 0;
        
        // Alpine variable to determine mobile view state
        $has_active_thread = $active_thread_id > 0 ? 'true' : 'false';
        ?>
        <?php if ($show_inbox_tab) : ?>
        <section x-show="activeTab === 'inbox'" x-transition.opacity.duration.300ms x-cloak x-data="{ viewThread: <?php echo $has_active_thread; ?> }" @eep-inbox-open-thread.window="viewThread = true" data-eep-inbox-section="1">
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6">
                <div class="flex items-end justify-between">
                    <div>
                        <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php echo esc_html($notifications_title); ?></h2>
                        <p class="text-sm sm:text-base text-gray-500 max-w-2xl"><?php echo esc_html($notifications_description); ?></p>
                    </div>
                    <?php if ($unread_count > 0) : ?>
                        <span class="hidden sm:flex items-center gap-1.5 px-3 py-1 bg-brand-50 text-brand-700 rounded-full text-sm font-bold shadow-sm border border-brand-100">
                            <span class="relative flex h-2.5 w-2.5">
                                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
                                <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-brand-500"></span>
                            </span>
                            <?php echo esc_html(sprintf(_n('%d New', '%d New', $unread_count, 'nexdirectory'), $unread_count)); ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-100 bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden flex flex-col md:flex-row h-[650px] max-h-[75vh]" data-eep-inbox-shell="1">
                
                <div class="w-full md:w-1/3 md:min-w-[320px] border-r border-gray-100 flex flex-col h-full bg-gray-50/50" :class="viewThread ? 'hidden md:flex' : 'flex'">
                    <div class="p-4 border-b border-gray-100 bg-white shrink-0 flex items-center justify-between">
                        <h3 class="font-bold text-gray-900"><?php esc_html_e('Conversations', 'nexdirectory'); ?></h3>
                        <?php if ($unread_count > 0) : ?>
                            <span class="md:hidden flex items-center justify-center bg-brand-500 text-white text-[10px] font-bold h-5 w-5 rounded-full">
                                <?php echo esc_html($unread_count); ?>
                            </span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="flex-1 overflow-y-auto scrollbar-hide">
                        <?php if (!empty($threads)) : ?>
                            <div class="divide-y divide-gray-100" data-eep-inbox-thread-list="1">
                                <?php foreach ($threads as $thread_row) : ?>
                                    <?php
                                    $thread_row_id = absint((int) ($thread_row['thread_id'] ?? 0));
                                    $thread_subject = sanitize_text_field((string) ($thread_row['subject'] ?? ''));
                                    if ($thread_subject === '') $thread_subject = sanitize_text_field((string) ($thread_row['event_title'] ?? __('Conversation', 'nexdirectory')));
                                    $thread_url = esc_url((string) ($thread_row['thread_url'] ?? '#'));
                                    $other_name = sanitize_text_field((string) ($thread_row['other_name'] ?? __('Member', 'nexdirectory')));
                                    $last_body = sanitize_text_field((string) ($thread_row['last_body'] ?? ''));
                                    $last_time = sanitize_text_field((string) ($thread_row['last_time'] ?? ''));
                                    $unread = absint((int) ($thread_row['unread_count'] ?? 0));
                                    $is_active = $thread_row_id === $active_thread_id;
                                    ?>
                                    <a href="<?php echo $thread_url; ?>" data-eep-inbox-thread-link="1" data-eep-thread-id="<?php echo esc_attr((string) $thread_row_id); ?>" class="eep-inbox-thread-item block p-4 transition-colors relative <?php echo $is_active ? 'bg-white border-l-4 border-l-brand-500' : 'bg-transparent border-l-4 border-l-transparent hover:bg-white'; ?>">
                                        <div class="flex justify-between items-start mb-1">
                                            <h4 class="font-bold text-sm text-gray-900 truncate pr-2 <?php echo $unread > 0 ? 'text-black' : ''; ?>"><?php echo esc_html($other_name); ?></h4>
                                            <span class="text-[10px] text-gray-400 whitespace-nowrap shrink-0"><?php echo esc_html($last_time); ?></span>
                                        </div>
                                        <p class="text-xs font-semibold text-gray-800 truncate mb-0.5"><?php echo esc_html($thread_subject); ?></p>
                                        <p class="text-xs text-gray-500 truncate <?php echo $unread > 0 ? 'font-medium text-gray-700' : ''; ?>"><?php echo esc_html($last_body); ?></p>
                                        
                                        <?php if ($unread > 0) : ?>
                                            <div class="absolute right-4 bottom-4 h-2.5 w-2.5 bg-brand-500 rounded-full shadow-sm border border-white"></div>
                                        <?php endif; ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php else : ?>
                            <div class="p-8 text-center flex flex-col items-center justify-center h-full opacity-60">
                                <svg class="w-10 h-10 text-gray-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path></svg>
                                <p class="text-sm font-medium text-gray-500"><?php esc_html_e('No messages yet.', 'nexdirectory'); ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="flex-1 flex flex-col h-full bg-white relative" data-eep-inbox-panel="1" :class="viewThread ? 'flex' : 'hidden md:flex'">
                    
                    <?php if (!empty($active_thread)) : ?>
                        <div class="p-4 border-b border-gray-100 bg-white shadow-sm z-10 shrink-0 flex items-center gap-3">
                            <button @click="viewThread = false" class="md:hidden p-2 -ml-2 text-gray-500 hover:text-gray-900 bg-gray-50 rounded-full transition-colors active:scale-95">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                            </button>
                            <div class="flex-1 min-w-0">
                                <h3 class="font-bold text-gray-900 truncate"><?php echo esc_html($active_subject !== '' ? $active_subject : __('Conversation', 'nexdirectory')); ?></h3>
                                <div class="flex items-center gap-2 mt-0.5 text-xs">
                                    <span class="text-gray-500"><?php echo esc_html(sprintf(__('With %s', 'nexdirectory'), $active_other_name)); ?></span>
                                    <?php if ($active_event_title !== '' && $active_event_url !== '') : ?>
                                        <span class="text-gray-300">•</span>
                                        <a href="<?php echo esc_url($active_event_url); ?>" class="text-brand-600 hover:text-brand-700 font-medium truncate"><?php echo esc_html($active_event_title); ?></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <div class="flex-1 overflow-y-auto p-4 sm:p-6 space-y-5 bg-gray-50/30" id="eep-chat-scroll-area">
                            <?php foreach ($active_messages as $message_row) : ?>
                                <?php
                                $is_mine = !empty($message_row['is_mine']);
                                $sender_name = sanitize_text_field((string) ($message_row['sender_name'] ?? __('Member', 'nexdirectory')));
                                $body = eep_sanitize_textarea((string) ($message_row['body'] ?? ''));
                                $attachment_url = esc_url((string) ($message_row['attachment_url'] ?? ''));
                                $created_label = sanitize_text_field((string) ($message_row['created_label'] ?? ''));
                                ?>
                                <div class="flex flex-col <?php echo $is_mine ? 'items-end' : 'items-start'; ?>">
                                    <span class="text-[10px] font-medium text-gray-400 mb-1 px-1">
                                        <?php echo esc_html($is_mine ? __('You', 'nexdirectory') : $sender_name); ?> • <?php echo esc_html($created_label); ?>
                                    </span>
                                    <div class="relative max-w-[85%] sm:max-w-[75%] p-3.5 sm:p-4 text-sm shadow-sm <?php echo $is_mine ? 'bg-gray-900 text-white rounded-2xl rounded-tr-sm' : 'bg-white border border-gray-100 text-gray-800 rounded-2xl rounded-tl-sm'; ?>">
                                        <?php echo nl2br(esc_html($body)); ?>
                                        <?php if ($attachment_url !== '') : ?>
                                            <a href="<?php echo esc_url($attachment_url); ?>" target="_blank" rel="noopener noreferrer" class="mt-3 inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-2 rounded-lg bg-black/10 hover:bg-black/20 transition-colors <?php echo $is_mine ? 'text-white' : 'text-brand-700 bg-brand-50 hover:bg-brand-100'; ?>">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"></path></svg>
                                                <?php esc_html_e('View attachment', 'nexdirectory'); ?>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="p-4 border-t border-gray-100 bg-white shrink-0">
                            <form method="post" action="<?php echo $reply_action; ?>#inbox" class="flex flex-col sm:flex-row gap-3" data-eep-inbox-reply-form="1">
                                <input type="hidden" name="action" value="eep_inbox_reply">
                                <input type="hidden" name="thread_id" value="<?php echo esc_attr((string) $active_thread_id); ?>">
                                <input type="hidden" name="eep_inbox_reply_nonce" value="<?php echo esc_attr($reply_nonce); ?>">
                                <input type="hidden" name="subject" value="<?php echo esc_attr($reply_subject); ?>">
                                <input type="hidden" name="redirect_to" value="<?php echo esc_attr($this->build_inbox_thread_url($active_thread_id, 0)); ?>">
                                
                                <textarea name="message" rows="2" required placeholder="<?php esc_attr_e('Write your reply...', 'nexdirectory'); ?>" class="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:bg-white transition-all shadow-sm resize-none"></textarea>
                                <button type="submit" class="eep-force-accent-action sm:self-end w-full sm:w-auto bg-brand-600 hover:bg-brand-700 active:scale-95 text-white px-6 py-3 rounded-xl text-sm font-bold transition-all shadow-sm flex items-center justify-center gap-2" style="color:#ffffff !important; -webkit-text-fill-color:#ffffff !important;">
                                    <span><?php esc_html_e('Send', 'nexdirectory'); ?></span>
                                    <svg class="w-4 h-4 transform rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
                                </button>
                            </form>
                        </div>
                        
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                const chatArea = document.getElementById('eep-chat-scroll-area');
                                if (chatArea) { chatArea.scrollTop = chatArea.scrollHeight; }
                            });
                        </script>

                    <?php else : ?>
                        <div class="flex-1 flex flex-col items-center justify-center p-8 text-center bg-gray-50/50">
                            <div class="w-16 h-16 bg-white border border-gray-100 text-brand-300 rounded-full flex items-center justify-center mb-4 shadow-sm">
                                <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path></svg>
                            </div>
                            <h3 class="text-lg font-bold text-gray-900"><?php esc_html_e('No conversation selected', 'nexdirectory'); ?></h3>
                            <p class="text-sm text-gray-500 mt-1 max-w-xs"><?php esc_html_e('Choose a conversation from the left to read and reply to messages.', 'nexdirectory'); ?></p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>
<?php
        // My Tickets specific variables mapping
        $saved_rows = isset($saved_rows) && is_array($saved_rows) ? $saved_rows : [];
        $events_url = isset($events_url) ? (string) $events_url : $this->get_profile_route_default_url('events');
        $attending_title = sanitize_text_field((string) ($ui_labels['attending_title'] ?? __('Events I\'m Attending', 'nexdirectory')));
        $attending_description = sanitize_text_field((string) ($ui_labels['attending_description'] ?? __('Manage your event plans, personal itinerary, and notes in one place.', 'nexdirectory')));
        $attending_empty_heading = sanitize_text_field((string) ($ui_labels['attending_empty_heading'] ?? __('No listings yet', 'nexdirectory')));
        $attending_empty_description = sanitize_text_field((string) ($ui_labels['attending_empty_description'] ?? __('You have not saved any listings yet.', 'nexdirectory')));
        $attending_browse_cta = sanitize_text_field((string) ($ui_labels['attending_browse_cta'] ?? __('Browse Listings', 'nexdirectory')));
        $single_rsvp_cancel = sanitize_text_field((string) ($ui_labels['single_rsvp_cancel'] ?? __('Cancel RSVP', 'nexdirectory')));
        ?>
        <?php if ($show_saved_tab) : ?>
        <section x-show="activeTab === 'saved'" x-transition.opacity.duration.300ms x-cloak>
            
            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out mb-6 sm:mb-8">
                <h2 class="text-2xl sm:text-3xl font-bold text-gray-900 tracking-tight mb-2"><?php echo esc_html($attending_title); ?></h2>
                <p class="text-sm sm:text-base text-gray-500 max-w-2xl"><?php echo esc_html($attending_description); ?></p>
            </div>

            <div x-data="{ shown: false }" x-intersect.once="shown = true" :class="shown ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-8'" class="transition-all duration-700 ease-out delay-100">
                <?php if (!empty($saved_rows)) : ?>
                    <div class="space-y-4">
                        <?php foreach ($saved_rows as $row) : ?>
                            <?php 
                            $status_class = (string) ($row['status'] ?? '') === 'waitlist' ? 'bg-amber-50 text-amber-700 border-amber-200' : 'bg-green-50 text-green-700 border-green-200'; 
                            $row_post_id = absint((int) ($row['post_id'] ?? 0));
                            $row_sessions = isset($row['sessions']) && is_array($row['sessions']) ? array_values($row['sessions']) : [];
                            $row_map_link = esc_url((string) ($row['map_link'] ?? ''));
                            ?>
                            <div class="bg-white rounded-2xl border border-gray-100 p-5 shadow-sm hover:border-brand-200 transition-colors" x-data="{
                                open: false,
                                noteText: '',
                                savedSessions: [],
                                sessionNotes: {},
                                noteStorageKey: 'eep_attending_note_<?php echo esc_js((string) $row_post_id . '_u' . (string) get_current_user_id()); ?>',
                                sessionsStorageKey: 'eep_itinerary_list_<?php echo esc_js((string) $row_post_id . '_u' . (string) get_current_user_id()); ?>',
                                sessionNotesStorageKey: 'eep_itinerary_notes_<?php echo esc_js((string) $row_post_id . '_u' . (string) get_current_user_id()); ?>',
                                init() {
                                    try {
                                        this.noteText = String(window.localStorage.getItem(this.noteStorageKey) || '');
                                        const parsed = JSON.parse(window.localStorage.getItem(this.sessionsStorageKey) || '[]');
                                        this.savedSessions = Array.isArray(parsed) ? parsed.map((item) => String(item || '').trim()).filter((item) => item !== '') : [];
                                        const parsedNotes = JSON.parse(window.localStorage.getItem(this.sessionNotesStorageKey) || '{}');
                                        this.sessionNotes = parsedNotes && typeof parsedNotes === 'object' ? parsedNotes : {};
                                    } catch (e) {
                                        this.noteText = '';
                                        this.savedSessions = [];
                                        this.sessionNotes = {};
                                    }
                                },
                                saveNote() {
                                    try { window.localStorage.setItem(this.noteStorageKey, this.noteText || ''); } catch (e) {}
                                },
                                persistSessions() {
                                    try { window.localStorage.setItem(this.sessionsStorageKey, JSON.stringify(this.savedSessions)); } catch (e) {}
                                },
                                toggleSession(id) {
                                    const key = String(id || '').trim();
                                    if (!key) return;
                                    const currentItems = Array.isArray(this.savedSessions) ? this.savedSessions : [];
                                    if (currentItems.includes(key)) {
                                        this.savedSessions = currentItems.filter((item) => item !== key);
                                    } else {
                                        this.savedSessions = [...currentItems, key];
                                    }
                                    this.persistSessions();
                                },
                                isSavedSession(id) {
                                    const key = String(id || '').trim();
                                    return key !== '' && this.savedSessions.includes(key);
                                },
                                sessionNote(id) {
                                    const key = String(id || '').trim();
                                    if (!key || !this.sessionNotes || typeof this.sessionNotes !== 'object') return '';
                                    return String(this.sessionNotes[key] || '');
                                }
                            }">
                                
                                <div class="flex flex-col sm:flex-row gap-5 sm:items-center justify-between">
                                    <div class="flex-1 min-w-0">
                                        <div class="flex items-center gap-2 mb-1.5 flex-wrap">
                                            <h3 class="font-bold text-gray-900 text-lg truncate"><a href="<?php echo esc_url((string) ($row['url'] ?? '#')); ?>" class="hover:text-brand-600 transition-colors"><?php echo esc_html((string) ($row['title'] ?? '')); ?></a></h3>
                                            <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border <?php echo $status_class; ?>">
                                                <?php echo esc_html((string) ($row['status_label'] ?? '')); ?>
                                            </span>
                                            <?php if (!empty($row['event_status_label'])) : ?>
                                                <span class="px-2.5 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider bg-gray-100 text-gray-600 border border-gray-200">
                                                    <?php echo esc_html((string) $row['event_status_label']); ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>

                                        <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4 text-sm text-gray-500">
                                            <div class="flex items-center gap-1.5">
                                                <svg class="w-4 h-4 shrink-0 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                                                <span class="truncate"><?php echo esc_html((string) ($row['event_date_label'] ?? ($row['start_label'] ?? ''))); ?></span>
                                            </div>
                                            <div class="flex items-center gap-1.5">
                                                <svg class="w-4 h-4 shrink-0 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                                                <span class="truncate max-w-[240px]"><?php echo esc_html((string) ($row['location'] ?? '')); ?></span>
                                            </div>
                                        </div>

                                        <?php if (!empty($row['has_ticket_order'])) : ?>
                                            <div class="mt-2 flex flex-wrap items-center gap-2 text-xs">
                                                <?php if (!empty($row['ticket_uid'])) : ?>
                                                    <span class="inline-flex items-center px-2 py-1 rounded-md bg-gray-900 text-white font-semibold tracking-wide">
                                                        <?php echo esc_html((string) $row['ticket_uid']); ?>
                                                    </span>
                                                <?php endif; ?>
                                                <?php if (!empty($row['ticket_total_label'])) : ?>
                                                    <span class="inline-flex items-center px-2 py-1 rounded-md bg-brand-50 text-brand-700 border border-brand-100 font-semibold">
                                                        <?php echo esc_html((string) $row['ticket_total_label']); ?>
                                                    </span>
                                                <?php endif; ?>
                                                <?php if (!empty($row['ticket_payment_method'])) : ?>
                                                    <span class="inline-flex items-center px-2 py-1 rounded-md bg-gray-100 text-gray-700 border border-gray-200">
                                                        <?php echo esc_html((string) $row['ticket_payment_method']); ?>
                                                    </span>
                                                <?php endif; ?>
                                                <?php if (!empty($row['ticket_purchased_label'])) : ?>
                                                    <span class="inline-flex items-center px-2 py-1 rounded-md bg-gray-100 text-gray-700 border border-gray-200">
                                                        <?php echo esc_html((string) $row['ticket_purchased_label']); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-3 shrink-0">
                                        <button type="button" @click="open = !open" class="eep-account-action-btn w-full sm:w-36 active:scale-95">
                                            <span x-show="!open"><?php esc_html_e('View details', 'nexdirectory'); ?></span>
                                            <span x-show="open" style="display:none;"><?php esc_html_e('Hide details', 'nexdirectory'); ?></span>
                                        </button>
                                        <a href="<?php echo esc_url((string) ($row['url'] ?? '#')); ?>" class="eep-account-action-btn w-full sm:w-36 active:scale-95">
                                            <?php echo esc_html(sprintf(__('Open %s', 'nexdirectory'), $singular_label)); ?>
                                        </a>
                                        
                                        <?php if (!empty($row['can_cancel'])) : ?>
                                            <form method="post" action="<?php echo esc_url(eep_add_query_arg('eep_tab', 'saved', admin_url('admin-post.php'))); ?>#saved" class="w-full sm:w-36">
                                                <input type="hidden" name="action" value="eep_rsvp_event">
                                                <input type="hidden" name="post_id" value="<?php echo esc_attr((string) ($row['post_id'] ?? '0')); ?>">
                                                <input type="hidden" name="intent" value="leave">
                                                <input type="hidden" name="eep_rsvp_nonce" value="<?php echo esc_attr((string) ($row['rsvp_nonce'] ?? '')); ?>">
                                                <button type="submit" class="eep-account-action-btn eep-account-action-btn-danger w-full active:scale-95">
                                                    <?php echo esc_html($single_rsvp_cancel); ?>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div x-show="open" x-collapse class="mt-5 pt-5 border-t border-gray-100 space-y-4">
                                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                                        <div class="rounded-xl border border-gray-200 bg-gray-50 p-3">
                                            <p class="text-xs uppercase tracking-wide text-gray-500 font-semibold mb-1"><?php esc_html_e('Event Dates', 'nexdirectory'); ?></p>
                                            <p class="font-semibold text-gray-900"><?php echo esc_html((string) ($row['event_date_label'] ?? ($row['start_label'] ?? ''))); ?></p>
                                        </div>
                                        <div class="rounded-xl border border-gray-200 bg-gray-50 p-3">
                                            <p class="text-xs uppercase tracking-wide text-gray-500 font-semibold mb-1"><?php esc_html_e('Map', 'nexdirectory'); ?></p>
                                            <?php if ($row_map_link !== '') : ?>
                                                <a href="<?php echo esc_url($row_map_link); ?>" target="_blank" rel="noopener noreferrer nofollow ugc" class="font-semibold text-brand-700 hover:text-brand-800"><?php esc_html_e('Open location map', 'nexdirectory'); ?></a>
                                            <?php else : ?>
                                                <p class="text-gray-500"><?php esc_html_e('Map not available for this event.', 'nexdirectory'); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="rounded-xl border border-gray-200 bg-white p-4">
                                        <h4 class="font-bold text-gray-900 mb-3"><?php esc_html_e('Your Custom Itinerary', 'nexdirectory'); ?></h4>
                                        <?php if (!empty($row_sessions)) : ?>
                                            <div class="space-y-3">
                                                <?php foreach ($row_sessions as $session_index => $session_row) : ?>
                                                    <?php
                                                    $session_uid = sanitize_key((string) ($session_row['session_uid'] ?? ''));
                                                    if ($session_uid === '') {
                                                        $session_uid = sanitize_key('e' . (string) $row_post_id . '-s' . substr(md5((string) $row_post_id . '|' . (string) $session_index . '|' . (string) ($session_row['title'] ?? '') . '|' . (string) ($session_row['time'] ?? '')), 0, 24));
                                                    }
                                                    $session_title = sanitize_text_field((string) ($session_row['title'] ?? ''));
                                                    $session_time = sanitize_text_field((string) ($session_row['time'] ?? ''));
                                                    $session_day = sanitize_text_field((string) ($session_row['day_label'] ?? ''));
                                                    $session_speaker = sanitize_text_field((string) ($session_row['speaker'] ?? ''));
                                                    $session_location = sanitize_text_field((string) ($session_row['location'] ?? ''));
                                                    ?>
                                                    <article :class="isSavedSession('<?php echo esc_js($session_uid); ?>') ? 'border-l-4 border-l-green-500 border-green-100 bg-green-50/40' : 'border-gray-200 bg-gray-50'" class="rounded-lg border p-3">
                                                        <div class="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2">
                                                            <div class="min-w-0">
                                                                <p class="font-semibold text-gray-900"><?php echo esc_html($session_title !== '' ? $session_title : __('Session', 'nexdirectory')); ?></p>
                                                                <p class="text-xs text-gray-500"><?php echo esc_html(trim((string) implode(' • ', array_filter([$session_day, $session_time])))); ?></p>
                                                                <?php if ($session_speaker !== '') : ?>
                                                                    <p class="text-xs text-gray-500 mt-1"><?php echo esc_html(sprintf(__('Speaker: %s', 'nexdirectory'), $session_speaker)); ?></p>
                                                                <?php endif; ?>
                                                                <?php if ($session_location !== '') : ?>
                                                                    <p class="text-xs text-gray-500"><?php echo esc_html(sprintf(__('Location: %s', 'nexdirectory'), $session_location)); ?></p>
                                                                <?php endif; ?>
                                                            </div>
                                                            <button type="button" @click.prevent.stop="toggleSession('<?php echo esc_js($session_uid); ?>')" :class="isSavedSession('<?php echo esc_js($session_uid); ?>') ? 'bg-green-50 text-green-700 border-green-200' : 'bg-white text-gray-700 border-gray-300'" class="inline-flex items-center gap-1 px-3 py-1.5 rounded-md text-xs font-semibold border transition-colors">
                                                                <span x-show="!isSavedSession('<?php echo esc_js($session_uid); ?>')"><?php esc_html_e('Add to list', 'nexdirectory'); ?></span>
                                                                <span x-show="isSavedSession('<?php echo esc_js($session_uid); ?>')" style="display:none;"><?php esc_html_e('Saved', 'nexdirectory'); ?></span>
                                                            </button>
                                                        </div>
                                                        <template x-if="sessionNote('<?php echo esc_js($session_uid); ?>') !== ''">
                                                            <div class="mt-2 p-2.5 rounded-md border border-yellow-200 bg-yellow-50 text-xs text-yellow-900 whitespace-pre-wrap" x-text="sessionNote('<?php echo esc_js($session_uid); ?>')"></div>
                                                        </template>
                                                    </article>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php else : ?>
                                            <p class="text-sm text-gray-500"><?php esc_html_e('No itinerary has been published for this event yet.', 'nexdirectory'); ?></p>
                                        <?php endif; ?>
                                    </div>

                                    <div class="rounded-xl border border-gray-200 bg-white p-4">
                                        <h4 class="font-bold text-gray-900 mb-2"><?php esc_html_e('Personal Notes', 'nexdirectory'); ?></h4>
                                        <textarea x-model="noteText" @blur="saveNote()" rows="3" placeholder="<?php esc_attr_e('Add travel reminders, meetup plans, or your own checklist.', 'nexdirectory'); ?>" class="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-brand-500 focus:border-brand-500 outline-none resize-y"></textarea>
                                        <p class="mt-2 text-xs text-gray-500"><?php esc_html_e('Notes are saved in this browser for quick access.', 'nexdirectory'); ?></p>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else : ?>
                    <div class="bg-white rounded-2xl border border-gray-100 p-10 text-center shadow-sm flex flex-col items-center justify-center">
                        <div class="w-16 h-16 bg-brand-50 text-brand-500 rounded-full flex items-center justify-center mb-4 shadow-sm border border-brand-100">
                            <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"></path></svg>
                        </div>
                        <h3 class="text-lg font-bold text-gray-900"><?php echo esc_html($attending_empty_heading); ?></h3>
                        <p class="text-gray-500 text-sm mt-1 mb-5 max-w-sm"><?php echo esc_html($attending_empty_description); ?></p>
                        <a href="<?php echo esc_url($events_url); ?>" class="eep-force-accent-action inline-block bg-gray-900 hover:bg-black text-white px-6 py-2.5 rounded-xl text-sm font-semibold transition-all active:scale-95 shadow-sm">
                            <?php echo esc_html($attending_browse_cta); ?>
                        </a>
                    </div>
                <?php endif; ?>
            </div>

        </section>
        <?php endif; ?>
        </main>

    <nav class="md:hidden fixed bottom-0 w-full bg-white/90 backdrop-blur-md border-t border-gray-200 z-50 pb-safe shadow-[0_-10px_15px_-3px_rgba(0,0,0,0.05)]">
        <div class="flex justify-around items-center px-2">
            <?php if ($show_analytics_tab) : ?>
            <button type="button" @click="setTab('analytics')" class="flex flex-col items-center justify-center w-full py-3" :class="activeTab === 'analytics' ? 'text-brand-600' : 'text-gray-500 hover:text-gray-900'">
                <svg class="w-6 h-6 mb-1 transition-transform" :class="activeTab === 'analytics' ? 'scale-110' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path></svg>
                <span class="text-[10px] font-medium">Stats</span>
            </button>
            <?php endif; ?>
            <?php if ($show_listings_tab) : ?>
            <button type="button" @click="setTab('listings')" class="flex flex-col items-center justify-center w-full py-3" :class="activeTab === 'listings' ? 'text-brand-600' : 'text-gray-500 hover:text-gray-900'">
                <svg class="w-6 h-6 mb-1 transition-transform" :class="activeTab === 'listings' ? 'scale-110' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path></svg>
                <span class="text-[10px] font-medium">Listings</span>
            </button>
            <?php endif; ?>
            <?php if ($show_submit_tab) : ?>
            <div class="relative w-full flex justify-center pb-2">
                <button type="button" @click="setTab('submit')" class="absolute -top-5 flex items-center justify-center w-14 h-14 bg-brand-500 text-white rounded-full shadow-lg border-4 border-white active:scale-95 transition-transform" :class="activeTab === 'submit' ? 'bg-brand-600' : ''">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M12 4v16m8-8H4"></path></svg>
                </button>
            </div>
            <?php endif; ?>
            <?php if ($show_inbox_tab) : ?>
            <button type="button" @click="setTab('inbox')" class="flex flex-col items-center justify-center w-full py-3 relative" :class="activeTab === 'inbox' ? 'text-brand-600' : 'text-gray-500 hover:text-gray-900'">
                <svg class="w-6 h-6 mb-1 transition-transform" :class="activeTab === 'inbox' ? 'scale-110' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg>
                <span class="text-[10px] font-medium">Inbox</span>
            </button>
            <?php endif; ?>
            <?php if ($show_account_tab) : ?>
            <button type="button" @click="setTab('account')" class="flex flex-col items-center justify-center w-full py-3" :class="activeTab === 'account' ? 'text-brand-600' : 'text-gray-500 hover:text-gray-900'">
                <svg class="w-6 h-6 mb-1 transition-transform" :class="activeTab === 'account' ? 'scale-110' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                <span class="text-[10px] font-medium">Profile</span>
            </button>
            <?php endif; ?>
        </div>
    </nav>
</div>
