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

class VS_Dashboard {

    public static function init() {
        add_shortcode('vendor_dashboard', [__CLASS__, 'render_dashboard']);
        add_action('wp_ajax_vs_reset_onboarding', [__CLASS__, 'reset_onboarding_ajax']);
        add_action('wp_ajax_vs_get_products_page',  [__CLASS__, 'ajax_get_products_page']);
    }

    public static function reset_onboarding_ajax() {
        check_ajax_referer('vs_vars_nonce', 'security');
        $user_id = get_current_user_id();
        if (!$user_id) wp_send_json_error();

        update_user_meta($user_id, 'vs_vendor_status', '');
        update_user_meta($user_id, 'vs_vendor_onboarded', 0);

        wp_send_json_success();
    }

    private static function get_locale_label($locale) {
        $labels = [
            'en_US' => __('English', 'vendor-space'),
            'fr_FR' => __('French', 'vendor-space'),
            'ar'    => __('Arabic', 'vendor-space'),
        ];

        return $labels[$locale] ?? $locale;
    }

    private static function render_language_switcher() {
        $current = function_exists('vs_get_requested_locale') && vs_get_requested_locale() ? vs_get_requested_locale() : determine_locale();
        $locales = function_exists('vs_get_enabled_locales') ? vs_get_enabled_locales() : ['en_US', 'fr_FR', 'ar'];
        ?>
        <div class="vs-language-switcher">
            <label class="vs-language-label" for="vs-language-switcher"><?php echo esc_html__('Language', 'vendor-space'); ?></label>
            <select id="vs-language-switcher" class="vs-language-select" aria-label="<?php echo esc_attr__('Change language', 'vendor-space'); ?>">
                <?php foreach ($locales as $locale) : ?>
                    <option value="<?php echo esc_attr($locale); ?>" <?php selected($current, $locale); ?>>
                        <?php echo esc_html(self::get_locale_label($locale)); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php
    }

    private static function render_shared_dashboard_css() {
        ?>
        <style>
        .vs-action-btn {
            position: relative;
        }

        .vs-action-btn::after {
            content: attr(data-tooltip);
            position: absolute;
            top: -35px;
            left: 50%;
            transform: translateX(-50%);
            background: #1e293b;
            color: white;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 12px;
            opacity: 0;
            visibility: hidden;
            transition: 0.2s;
            white-space: nowrap;
        }

        .vs-action-btn:hover::after {
            opacity: 1;
            visibility: visible;
        }
        </style>
        <?php
    }

    public static function render_products_tab_content($user) {
        ob_start();
        ?>
        <div class="vs-tab" id="tab-my-products" style="display:none;">
            <h3><?php echo current_user_can('administrator') ? esc_html__('All Products', 'vendor-space') : esc_html__('My Products', 'vendor-space'); ?></h3>
            
            <div id="vs-products-pane"  data-empty-src="<?php echo esc_url(VS_URL . 'noproduct.png'); ?>">

          <?php
$args = [
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'post_status'    => ['publish', 'draft', 'pending', 'pending_vendor', 'trash', 'private'],
];

if (!current_user_can('administrator')) {
    $args['author'] = $user->ID;
}

// جميع المنتجات
$all_products = get_posts($args);

// جلب الـ vendors المحظورين
$blocked_vendor_ids = get_users([
    'fields'     => 'ID',
    'meta_key'   => 'vs_vendor_status',
    'meta_value' => 'deleted',
]);

//يحوله إلى مصفوفة أرقام صحيحة
$blocked_vendor_ids = !empty($blocked_vendor_ids) ? array_map('intval', $blocked_vendor_ids) : [];

// فلترة المنتجات
$products = array_filter($all_products, function($product) use ($blocked_vendor_ids) {
    return !in_array((int)$product->post_author, $blocked_vendor_ids, true);
});

// الآن $products تحتوي فقط على المنتجات الخاصة بالبائعين غير المحظورين
$total = $in_stock = $out_of_stock = $published = $draft = $pending = $trash = 0;

foreach ($products as $product_post) {

    $total++;

    $status = $product_post->post_status;

    switch ($status) {
        case 'publish':
            $published++;
            break;

        case 'draft':
            $draft++;
            break;

        case 'pending':
            $pending++;
            break;
            
        case 'pending_vendor':
            // we can count them under pending or a new variable
            $pending++; 
            break;

        case 'trash':
            $trash++;
            break;
    }

    $product = wc_get_product($product_post->ID);
    if (!$product) continue;

    if ($product->is_in_stock()) {
    $in_stock++;
} else {
    $out_of_stock++;
}
} 

            $data['products'] = [
                'total'     => $total,
                'in_stock'  => $in_stock,
                'published' => $published,
                'draft'     => $draft,
                'pending'   => $pending,
                'trash'     => $trash,
            ];
            // Pass pagination info to the table wrapper
            $vs_total_products_no_trash = $total - $trash;
            ?>
            <div class="vs-metrics-grid">
            <style>
            .vs-metrics-grid {
                display: grid;
                grid-template-columns: repeat(4, minmax(0, 1fr));
                gap: 10px;
                margin: 12px 14px;
            }
            </style>

                <div class="vs-metric-card vs-total">
                    <span class="dashicons dashicons-products"></span>
                    <div>
                        <small><?php echo esc_html__('Total Products', 'vendor-space'); ?></small>
                        <strong id="vs-metric-total-products"><?php echo esc_html($data['products']['total']); ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-published">
                    <span class="dashicons dashicons-yes-alt"></span>
                    <div>
                        <small><?php echo esc_html__('Published', 'vendor-space'); ?></small>
                        <strong id="vs-metric-published-products"><?php echo esc_html($data['products']['published']); ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-draft">
                    <span class="dashicons dashicons-edit"></span>
                    <div>
                        <small><?php echo esc_html__('Draft', 'vendor-space'); ?></small>
                        <strong id="vs-metric-draft-products"><?php echo esc_html($data['products']['draft']); ?></strong>
                    </div>
                </div>
<style>
    .vs-spin {
    display: inline-block;
    animation: vsSpin 1.5s linear infinite;
}

@keyframes vsSpin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
                <div class="vs-metric-card vs-pending">
                   <span class="dashicons dashicons-clock vs-spin"></span>
                    <div>
                        <small><?php echo esc_html__('Pending', 'vendor-space'); ?></small>
                        <strong id="vs-metric-pending-products"><?php echo esc_html($data['products']['pending']); ?></strong>
                    </div>
                </div>

                <div class="vs-metric-card vs-stock">
                    <span class="dashicons dashicons-archive"></span>
                    <div>
                        <small><?php echo esc_html__('In Stock', 'vendor-space'); ?></small>
                        <strong id="vs-metric-in-stock-products"><?php echo esc_html($data['products']['in_stock']); ?></strong>
                    </div>
                </div>

              
             

                <div class="vs-metric-card vs-trash" style="border-left: 4px solid #94a3b8; cursor:pointer;" data-vs-open-tab="restore-products">
                    <span class="dashicons dashicons-trash"></span>
                    <div>
                        <small><?php echo esc_html__('Trash', 'vendor-space'); ?></small>
                        <strong id="vs-metric-trash-products"><?php echo esc_html($data['products']['trash']); ?></strong>
                    </div>
                </div>

            </div>

                <!-- Search & Filter -->
                <div class="vs-table-tools" style="margin-bottom: 15px; display:flex; gap:10px; flex-wrap:wrap;">
                    <div class="vs-search-wrap" style="display:flex; flex-direction:column; flex:1; min-width:150px;">
                        <input type="text" id="vs-product-search" placeholder="<?php echo esc_attr__('Search by name or category...', 'vendor-space'); ?>" style="padding:15px; width:80%;">
                    </div>

                    <?php if (current_user_can('administrator')): ?>
    <div class="vs-field vs-vendor-filter-wrap">

        <?php
        $vendor_args = [
            'number'  => -1,
            'role__in' => ['vendor', 'administrator'],
            'orderby' => 'display_name',
            'order'   => 'ASC',
        ];
        $all_users = get_users($vendor_args);
        $filter_vendors = [];

        foreach ($all_users as $u) {
            $v_status = get_user_meta($u->ID, 'vs_vendor_status', true) ?: 'active';
            if ($v_status === 'deleted') continue;
            
            $filter_vendors[] = [
                'id'     => (int) $u->ID,
                'name'   => $u->display_name,
                'email'  => $u->user_email,
                'avatar' => strtoupper(mb_substr($u->display_name, 0, 1)),
                'status' => $v_status,
            ];
        }
        ?>

        <input type="hidden" id="vs-filter-vendor-id" value="all">

        <div class="vs-custom-select" id="vs-filter-vendor-dropdown">
            <div class="vs-select-trigger">
                <span class="vs-select-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
                </span>
                <input type="text" id="vs-filter-vendor-search" class="vs-select-search" placeholder="<?php echo esc_attr__('All Vendors', 'vendor-space'); ?>" autocomplete="off">
                <span class="vs-select-clear" id="vs-filter-vendor-clear" style="display:none;">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                </span>
                <span class="vs-select-chevron">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                </span>
            </div>

            <div class="vs-select-dropdown" id="vs-filter-vendor-listbox-wrap" style="display:none;">
                <ul class="vs-select-list" id="vs-filter-vendor-listbox">
                    </ul>
                <div class="vs-no-results" id="vs-filter-no-results" style="display:none;">
                    <?php echo esc_html__('No vendors found.', 'vendor-space'); ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
<script>
    (function () {
    const FILTER_VENDORS = <?php echo wp_json_encode($filter_vendors); ?>;
    const wrap        = document.getElementById('vs-filter-vendor-dropdown');
    const searchEl    = document.getElementById('vs-filter-vendor-search');
    const listEl      = document.getElementById('vs-filter-vendor-listbox');
    const listboxWrap = document.getElementById('vs-filter-vendor-listbox-wrap');
    const hiddenInput = document.getElementById('vs-filter-vendor-id');
    const clearBtn    = document.getElementById('vs-filter-vendor-clear');
    const noResults   = document.getElementById('vs-filter-no-results');

    let selectedId = 'all';

    function buildFilterOptions(query) {
        const q = (query || '').toLowerCase().trim();
        listEl.innerHTML = '';
        
        // "All Vendors" Option
        const allItem = document.createElement('li');
        allItem.className = 'vs-option' + (selectedId === 'all' ? ' is-selected' : '');
        allItem.innerHTML = `<span><strong><?php _e('All Vendors', 'vendor-space'); ?></strong></span>`;
        allItem.onclick = () => selectFilterVendor('all', '');
        listEl.appendChild(allItem);

        let matchCount = 0;
        FILTER_VENDORS.forEach(v => {
            if (q && !v.name.toLowerCase().includes(q) && !v.email.toLowerCase().includes(q)) return;
            matchCount++;

            const li = document.createElement('li');
            li.className = 'vs-option' + (selectedId == v.id ? ' is-selected' : '');
            
            const hl = (str) => q ? str.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'), '<mark class="vs-highlight">$1</mark>') : str;

            li.innerHTML = `
                <span class="vs-option-avatar">${v.avatar}</span>
                <span class="vs-option-info">
                    <span class="vs-option-name">${hl(v.name)}</span>
                    <span class="vs-option-email">${hl(v.email)}</span>
                </span>
                <span class="vs-option-status vs-status-${v.status}">${v.status}</span>
            `;
            li.onclick = () => selectFilterVendor(v.id, v.name);
            listEl.appendChild(li);
        });

        noResults.style.display = (q && matchCount === 0) ? '' : 'none';
    }

    function selectFilterVendor(id, label) {
        selectedId = id;
        hiddenInput.value = id;
        searchEl.value = label;
        searchEl.placeholder = (id === 'all') ? 'All Vendors' : '';
        clearBtn.style.display = (id === 'all') ? 'none' : '';
        
        // Trigger Table Update (IMPORTANT)
        // هنا نقوم بإرسال حدث لجدول المنتجات ليعيد التحميل بناءً على الـ ID الجديد
        hiddenInput.dispatchEvent(new Event('change')); 
        
        closeFilterDropdown();
    }

    function openFilterDropdown() {
        wrap.classList.add('is-open');
        listboxWrap.style.display = 'block';
        buildFilterOptions(searchEl.value);
    }

    function closeFilterDropdown() {
        wrap.classList.remove('is-open');
        listboxWrap.style.display = 'none';
    }

    searchEl.addEventListener('focus', openFilterDropdown);
    searchEl.addEventListener('input', () => buildFilterOptions(searchEl.value));
    
    clearBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        selectFilterVendor('all', '');
    });

    document.addEventListener('click', (e) => {
        if (!wrap.contains(e.target)) closeFilterDropdown();
    });

    buildFilterOptions('');
})();
</script>
                    <div style="display:flex; gap:10px; flex-wrap:wrap;">

                        <button id="vs-delete-selected" style="color:white; background:red; border:none; cursor:pointer; padding:5px 10px; border-radius:4px;">
                            <?php echo esc_html__('Delete selection', 'vendor-space'); ?>
                        </button>
                        <button id="vs-bulk-quick-edit" disabled style="color:white; background:#0ea5e9; border:none; cursor:pointer; padding:5px 10px; border-radius:4px;">
                            <?php echo esc_html__('Bulk Quick Edit', 'vendor-space'); ?>
                        </button>
                        <?php   $settings = get_option('vs_settings');
                        $can_export = $settings['vendors']['vendor_can_export_csv'] ?? 'no';

                        if ($can_export === 'yes' && VS_Modules::is_active('export_import')) :
                        ?>                       
                            <button id="vs-export-csv" style="padding:5px 10px; border-radius:4px; background:#27ae60; color:white; border:none; cursor:pointer;">
                                <?php echo esc_html__('Export', 'vendor-space'); ?>
                            </button>
                        <?php endif; ?>
                            <?php   $settings = get_option('vs_settings');
                        $can_import = $settings['vendors']['vendor_can_import_csv'] ?? 'no';

                        if ($can_import === 'yes' && VS_Modules::is_active('export_import')) :
                        ?>
                         <label style="padding:5px 10px; border-radius:4px; background:#f39c12; color:white; cursor:pointer;">
                            <?php echo esc_html__('Import CSV', 'vendor-space'); ?>
                            <input type="file" id="vs-import-csv" accept=".csv" style="display:none;">
                        </label>
                        <?php endif; ?>

                        <button id="add-product-btn-show" style="color:white; background:#2563eb; border:none; cursor:pointer; padding:5px 10px; border-radius:4px;">
                            <?php echo esc_html__('Add a product', 'vendor-space'); ?>
                        </button>


                    </div>
                    <input type="hidden" name="security" value="<?php echo wp_create_nonce('vs_delete_product_nonce'); ?>">
                </div>
<style>
    /* ====== Table Tools Wrapper ====== */
.vs-table-tools {
    background: #ffffff;
    padding: 18px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    align-items: flex-end;
}

/* ====== Search Box ====== */
.vs-search-wrap input {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.2s ease;
}

.vs-search-wrap input:focus {
    outline: none;
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}

/* ====== Select Dropdowns ====== */
.vs-table-tools select {
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    font-size: 14px;
    background: #fff;
    transition: 0.2s ease;
}

.vs-table-tools select:focus {
    outline: none;
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15);
}

/* ====== Buttons General Style ====== */
.vs-table-tools button,
.vs-table-tools label {
    font-size: 14px;
    font-weight: 500;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

/* Hover Effects */
.vs-table-tools button:hover,
.vs-table-tools label:hover {
    transform: translateY(-1px);
    opacity: 0.9;
}

/* Active Click Effect */
.vs-table-tools button:active {
    transform: scale(0.97);
}

/* ====== Specific Buttons ====== */

/* Delete */
#vs-delete-selected {
    background: #dc2626 !important;
}

#vs-delete-selected:hover {
    background: #b91c1c !important;
}

/* Export */
#vs-export-csv {
    background: #16a34a !important;
}

#vs-export-csv:hover {
    background: #15803d !important;
}

/* Import */
.vs-table-tools label {
    background: #f59e0b !important;
}

.vs-table-tools label:hover {
    background: #d97706 !important;
}

/* Add Product */
#add-product-btn-show {
    background: #2563eb !important;
}

#add-product-btn-show:hover {
    background: #1d4ed8 !important;
}

/* ====== Responsive ====== */
@media (max-width: 768px) {
    .vs-table-tools {
        flex-direction: column;
        align-items: stretch;
    }

    .vs-table-tools > div {
        width: 100%;
    }

    .vs-table-tools select,
    .vs-table-tools button,
    .vs-table-tools label {
        width: 100%;
    }
}
</style>
           
                   <div id="vs-edit-product-wrapper" class="vs-form-wrapper" style="display:none; margin-top:20px;">
                        <h3><?php echo esc_html__('Edit Product', 'vendor-space'); ?></h3>
                        <?php
                                    $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';
                                    if ($manual_approval) {
                                        echo '<div style="background:#fef3c7; border:1px solid #f59e0b; padding:10px; margin-bottom:10px; border-radius:4px; color:#92400e; font-size:0.9em;">';
                                        echo '<strong>⚠️ Approval Required:</strong> Products must be approved by an administrator before being visible to customers.';
                                        echo '</div>';
                                    }
                                    ?>
                        <form id="vs-edit-product-form" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="vs_edit_product">
                            <?php wp_nonce_field('vs_edit_product','vs_edit_product_nonce'); ?>
                            <input type="hidden" name="product_id" id="edit-product-id">

                            <div class="vs-grid">
                                <div class="vs-field full">
                                    <label class="vs-label-required"><?php echo esc_html__('Product Name', 'vendor-space'); ?></label>
                                    <input type="text" name="product_name" id="edit-product-name" required>
                                </div>

                               <div class="vs-field">
    <label class="vs-label-required"><?php echo esc_html__('Regular Price', 'vendor-space'); ?></label>
    
    <div class="vs-price-input">
        <span class="vs-currency-symbol">
            <?php echo esc_html( get_woocommerce_currency_symbol( get_woocommerce_currency() ) ); ?>
        </span>
        <input type="number" step="0.01" name="product_price" id="edit-product-price" required>
    </div>
</div>
<style>.vs-price-input {
    display: flex;
    align-items: center;
    gap: 10px;
}

.vs-currency-symbol {
    min-width: 40px;
    height: 42px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8fafc;
    border: 1px solid #d1d5db;
    border-radius: 10px;
    font-weight: 600;
    color: #334155;
    padding: 0 12px;
}</style>

                                <div class="vs-field">
    <label><?php echo esc_html__('Sale Price', 'vendor-space'); ?></label>

    <div class="vs-price-input">
        <span class="vs-currency-symbol">
            <?php echo esc_html( get_woocommerce_currency_symbol( get_woocommerce_currency() ) ); ?>
        </span>
        <input type="number" step="0.01" name="product_sale_price" id="edit-product-sale-price">
    </div>
</div>

                                <div class="vs-field">
                                    <label class="vs-label-required"><?php echo esc_html__('Stock Quantity', 'vendor-space'); ?></label>
                                    <input type="number" name="product_stock" id="edit-product-stock" required>
                                </div>

                                <div class="vs-field">
                                    <label><?php echo esc_html__('SKU', 'vendor-space'); ?></label>
                                    <input type="text" name="product_sku" id="edit-product-sku">
                                </div>

                                <div class="vs-field">
                                    <label><?php echo esc_html__('Product Type', 'vendor-space'); ?></label>
                                    <select name="product_type" id="edit-product-type" class="vs-product-type-select">
                                        <option value="simple"><?php echo esc_html__('Simple', 'vendor-space'); ?></option>
                                        <option value="variable"><?php echo esc_html__('Variable', 'vendor-space'); ?></option>
                                    </select>
                                </div>

                                <div class="vs-field full">
                                    <div class="vs-variable-product-panel" style="display:none; margin-top: 6px;">
                                        <h3><?php echo esc_html__('Attributes', 'vendor-space'); ?></h3>
                                        <div class="vs-attributes-wrapper"></div>
                                        <button type="button" class="vs-btn vs-add-attribute-btn"><?php echo esc_html__('+ Add Attribute', 'vendor-space'); ?></button>

                                        <hr>

                                        <h3><?php echo esc_html__('Bulk Actions', 'vendor-space'); ?></h3>
                                        <div class="vs-bulk-actions">
                                            <input type="number" class="vs-bulk-price" placeholder="<?php echo esc_attr__('Set price for all', 'vendor-space'); ?>">
                                            <input type="number" class="vs-bulk-stock" placeholder="<?php echo esc_attr__('Set stock for all', 'vendor-space'); ?>">
                                            <button type="button" class="vs-btn vs-apply-bulk-btn"><?php echo esc_html__('Apply', 'vendor-space'); ?></button>
                                        </div>

                                        <hr>

                                        <button type="button" class="vs-btn vs-btn-primary vs-generate-variations-btn"><?php echo esc_html__('Generate Variations', 'vendor-space'); ?></button>
                                        <h3><?php echo esc_html__('Variations', 'vendor-space'); ?></h3>
                                        <div class="vs-variations-container"></div>
                                    </div>
                                </div>

                                <div class="vs-field">
                                    <label><?php echo esc_html__('Status', 'vendor-space'); ?></label>
                                    
                                    <select name="product_status" id="edit-product-status">
                                        <option value="publish"><?php echo esc_html__('Publish', 'vendor-space'); ?></option>
                                        <option value="draft"><?php echo esc_html__('Draft', 'vendor-space'); ?></option>
                                        <option value="pending"><?php echo esc_html__('Pending', 'vendor-space'); ?></option>
                                    </select>
                                </div>

                                <div class="vs-field full vs-cat-select-wrap">
    <label for="vs-cat-search-edit">
        <?php echo esc_html__('Categories', 'vendor-space'); ?>
    </label>

    <?php
    // Fetch all product categories with hierarchy
    $raw_cats = get_terms([
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'orderby'    => 'name',
        'order'      => 'ASC',
    ]);

    // Build a map: id => term
    $cat_map = [];
    if (!is_wp_error($raw_cats)) {
        foreach ($raw_cats as $t) {
            $cat_map[$t->term_id] = $t;
        }
    }

    // Build flat list with computed depth/path
    $cats_json = [];
    if (!is_wp_error($raw_cats)) {
        foreach ($raw_cats as $t) {
            // Build breadcrumb path
            $path_parts = [$t->name];
            $parent_id  = $t->parent;
            while ($parent_id && isset($cat_map[$parent_id])) {
                array_unshift($path_parts, $cat_map[$parent_id]->name);
                $parent_id = $cat_map[$parent_id]->parent;
            }
            $depth = count($path_parts) - 1;

            $cats_json[] = [
                'id'        => (int) $t->term_id,
                'name'      => $t->name,
                'slug'      => $t->slug,
                'parent'    => (int) $t->parent,
                'count'     => (int) $t->count,
                'depth'     => $depth,
                'path'      => implode(' > ', $path_parts),
            ];
        }
    }

    // Current selected value (for edit pages)
    $current_cat = isset($_GET['product_cat']) ? (int) $_GET['product_cat'] : 0;
    $current_cat_label = '';
    if ($current_cat && isset($cat_map[$current_cat])) {
        $current_cat_label = $cat_map[$current_cat]->name;
    }
    ?>

    <!-- Hidden real input -->
    <!-- Category Source Select (Hidden, used as the value holder and for clones) -->
    <select name="product_cat" id="edit-product-cat" style="display:none;">
        <option value="0"><?php echo esc_html__('No category', 'vendor-space'); ?></option>
        <?php foreach ($cats_json as $cat): ?>
            <option value="<?php echo esc_attr($cat['id']); ?>" <?php selected($current_cat, $cat['id']); ?>>
                <?php echo esc_html($cat['path']); ?>
            </option>
        <?php endforeach; ?>
    </select>

    <div class="vs-custom-select vs-cat-dropdown" id="vs-cat-dropdown-edit"
         role="combobox" aria-expanded="false" aria-haspopup="listbox">

        <!-- Search / Trigger -->
        <div class="vs-select-trigger">
            
            <input
                type="text"
                id="vs-cat-search-edit"
                class="vs-select-search"
                placeholder="<?php echo esc_attr__('Search categories...', 'vendor-space'); ?>"
                autocomplete="off"
                aria-autocomplete="list"
                aria-controls="vs-cat-listbox-edit"
                value="<?php echo esc_attr($current_cat_label); ?>"
            >
            <span class="vs-select-clear" id="vs-cat-clear-edit" title="Clear"
                  style="display:<?php echo $current_cat ? 'flex' : 'none'; ?>;" aria-label="Clear selection">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                </svg>
            </span>
            <span class="vs-select-chevron">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="6 9 12 15 18 9"/>
                </svg>
            </span>
        </div>

        <!-- Listbox -->
        <div class="vs-select-dropdown" id="vs-cat-listbox-wrap-edit" style="display:none;">
            <div class="vs-select-count" id="vs-cat-count-edit"></div>
            <ul class="vs-select-list" id="vs-cat-listbox-edit" role="listbox" aria-label="Product Categories">
                <!-- Populated by JS -->
            </ul>
            <div class="vs-no-results" id="vs-cat-no-results-edit" style="display:none;">
                <?php echo esc_html__('No categories found.', 'vendor-space'); ?>
            </div>
        </div>
    </div>

    <!-- Total badge -->
    <span class="vs-total-badge" id="vs-cat-total-badge-edit">
        <?php
        $total = count($cats_json);
        printf(esc_html__('%d categor%s available', 'vendor-space'), $total, $total === 1 ? 'y' : 'ies');
        ?>
    </span>

    <!-- Action Buttons -->
    
</div>

<style>
/* ─── Unified Premium Custom Select Styles ─── */
:root {
    --vs-primary: #6366f1;
    --vs-primary-light: #eef2ff;
    --vs-secondary: #0ea5e9;
    --vs-secondary-light: #f0f9ff;
    --vs-text-main: #1e293b;
    --vs-text-muted: #64748b;
    --vs-border: #d1d5db;
    --vs-shadow-lg: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

.vs-cat-select-wrap, .vs-vendor-select-wrap {
    position: relative;
    margin-bottom: 5px;
}

.vs-custom-select {
    position: relative;
    width: 100%;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Trigger Box */
.vs-select-trigger {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    min-height: 44px;
    padding: 0 14px;
    background: #ffffff;
    border: 1.5px solid var(--vs-border);
    border-radius: 12px;
    cursor: text;
    transition: all 0.2s ease;
    box-sizing: border-box;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.vs-custom-select.is-open .vs-select-trigger,
.vs-select-trigger:focus-within {
    border-color: var(--vs-primary);
    box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.12);
    transform: translateY(-1px);
}

/* Colors for Category logic exclusively */
.vs-cat-select-wrap .vs-custom-select.is-open .vs-select-trigger,
.vs-cat-select-wrap .vs-select-trigger:focus-within {
    border-color: var(--vs-secondary);
    box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.12);
}

.vs-select-icon {
    color: var(--vs-text-muted);
    display: flex;
    align-items: center;
    transition: color 0.2s;
}

.vs-select-trigger:focus-within .vs-select-icon {
    color: var(--vs-primary);
}
.vs-cat-select-wrap .vs-select-trigger:focus-within .vs-select-icon {
    color: var(--vs-secondary);
}

.vs-select-search {
    flex: 1;
    border: none !important;
    outline: none !important;
    font-size: 14px;
    font-weight: 500;
    color: var(--vs-text-main);
    background: transparent;
    padding: 10px 0;
    min-width: 0;
}

.vs-select-search::placeholder {
    color: #94a3b8;
    font-weight: 400;
}

.vs-select-clear {
    cursor: pointer;
    color: #94a3b8;
    display: flex;
    align-items: center;
    padding: 4px;
    border-radius: 50%;
    transition: all 0.2s;
}
.vs-select-clear:hover {
    color: #ef4444;
    background: #fee2e2;
    transform: rotate(90deg);
}

.vs-select-chevron {
    color: #94a3b8;
    transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.vs-custom-select.is-open .vs-select-chevron {
    transform: rotate(180deg);
}

/* Dropdown Menu */
.vs-select-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    left: 0;
    right: 0;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 14px;
    box-shadow: var(--vs-shadow-lg);
    z-index: 9999;
    overflow: hidden;
    opacity: 0;
    transform: translateY(-10px) scale(0.98);
    pointer-events: none;
    transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.1);
}

.vs-custom-select.is-open .vs-select-dropdown {
    opacity: 1;
    transform: translateY(0) scale(1);
    pointer-events: auto;
}

.vs-select-count {
    font-size: 11px;
    font-weight: 700;
    color: var(--vs-text-muted);
    padding: 10px 16px;
    background: #f8fafc;
    border-bottom: 1px solid #f1f5f9;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}

.vs-select-list {
    list-style: none !important;
    margin: 0 !important;
    padding: 6px 0 !important;
    max-height: 280px;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #cbd5e1 transparent;
}

.vs-select-list::-webkit-scrollbar { width: 5px; }
.vs-select-list::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }

/* Options Container */
.vs-cat-option, .vs-option {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 16px;
    cursor: pointer;
    transition: all 0.15s ease;
    border-left: 3px solid transparent;
}

.vs-cat-option:hover, .vs-cat-option.is-focused,
.vs-option:hover, .vs-option.is-focused {
    background: var(--vs-primary-light);
    border-left-color: var(--vs-primary);
}

.vs-cat-select-wrap .vs-cat-option:hover, 
.vs-cat-select-wrap .vs-cat-option.is-focused {
    background: var(--vs-secondary-light);
    border-left-color: var(--vs-secondary);
}

.vs-cat-option.is-selected, .vs-option.is-selected {
    background: var(--vs-primary-light);
    border-left-color: var(--vs-primary);
}

.vs-cat-select-wrap .vs-cat-option.is-selected {
    background: var(--vs-secondary-light);
    border-left-color: var(--vs-secondary);
}

/* Icons & Visuals inside Options */
.vs-cat-icon-wrap {
    width: 32px;
    height: 32px;
    border-radius: 10px;
    background: linear-gradient(135deg, #f0f9ff, #e0f2fe);
    color: var(--vs-secondary);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: inset 0 0 0 1px rgba(14, 165, 233, 0.1);
}

.vs-option-avatar {
    width: 32px;
    height: 32px;
    border-radius: 10px;
    background: linear-gradient(135deg, var(--vs-primary), #818cf8);
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 13px;
    box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.2);
}

.vs-cat-info, .vs-option-info {
    display: flex;
    flex-direction: column;
    min-width: 0;
    flex: 1;
}

.vs-cat-name, .vs-option-name {
    font-size: 14px;
    font-weight: 600;
    color: var(--vs-text-main);
}

.vs-cat-path, .vs-option-email {
    font-size: 11px;
    color: var(--vs-text-muted);
}

.vs-cat-count-badge {
    padding: 2px 8px;
    border-radius: 20px;
    background: #f1f5f9;
    color: #64748b;
    font-size: 10px;
    font-weight: 700;
}

.vs-cat-check, .vs-option-check {
    color: var(--vs-primary);
    display: none;
    animation: vsCheckIn 0.2s ease;
}
.vs-cat-select-wrap .vs-cat-check { color: var(--vs-secondary); }

.vs-cat-option.is-selected .vs-cat-check,
.vs-option.is-selected .vs-option-check {
    display: block;
}

@keyframes vsCheckIn {
    from { transform: scale(0.5); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
}

/* Highlight */
mark.vs-highlight {
    background: #fef08a;
    color: #854d0e;
    padding: 0 1px;
    border-radius: 2px;
    font-weight: 700;
}

/* Total Badge Overlay */
.vs-total-badge {
    margin-top: 8px;
    padding: 4px 12px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 11px;
    font-weight: 600;
    color: var(--vs-text-muted);
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

/* Responsive fixes */
@media (max-width: 640px) {
    .vs-select-trigger { padding: 0 10px; gap: 8px; }
    .vs-select-search { font-size: 13px; }
}
</style>

<script>
(function () {
    const CATS = <?php echo wp_json_encode($cats_json); ?>;

    const wrap        = document.getElementById('vs-cat-dropdown-edit');
    const searchEl    = document.getElementById('vs-cat-search-edit');
    const listEl      = document.getElementById('vs-cat-listbox-edit');
    const listboxWrap = document.getElementById('vs-cat-listbox-wrap-edit');
    const hiddenInput = document.getElementById('edit-product-cat');
    const clearBtn    = document.getElementById('vs-cat-clear-edit');
    const countEl     = document.getElementById('vs-cat-count-edit');
    const noResults   = document.getElementById('vs-cat-no-results-edit');

    let selectedId     = <?php echo (int) $current_cat; ?>;
    let focusedIndex   = -1;
    let visibleOptions = [];

    // ── Helpers ───────────────────────────────────────
    function escHtml(str) {
        return String(str)
            .replace(/&/g,'&amp;').replace(/</g,'&lt;')
            .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }

    function highlight(str, q) {
        if (!q) return escHtml(str);
        return escHtml(str).replace(
            new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'),
            '<mark class="vs-highlight">$1</mark>'
        );
    }

   
    function checkIcon() {
        return '<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
    }

    function childArrow() {
        return '<svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';
    }

    // ── Build Options ─────────────────────────────────
    function buildOptions(query) {
        const q = (query || '').toLowerCase().trim();
        listEl.innerHTML = '';
        visibleOptions   = [];
        focusedIndex     = -1;

        // None option
        const noneEl = document.createElement('li');
        noneEl.className = 'vs-cat-option vs-cat-option-none' + (selectedId === 0 ? ' is-selected' : '');
        noneEl.setAttribute('role','option');
        noneEl.setAttribute('tabindex','-1');
        noneEl.setAttribute('data-value','0');
        noneEl.style.setProperty('--cat-depth','0');
        noneEl.innerHTML =
            '<span class="vs-cat-info"><span class="vs-cat-name">-- <?php echo esc_js(__('No category selected', 'vendor-space')); ?> --</span></span>' +
            '<span class="vs-cat-check">' + checkIcon() + '</span>';
        noneEl.addEventListener('click', () => selectCat(0, ''));
        noneEl.addEventListener('mouseenter', () => setFocus(visibleOptions.indexOf(noneEl)));
        listEl.appendChild(noneEl);
        if (!q) visibleOptions.push(noneEl);

        let matchCount = 0;

        CATS.forEach(cat => {
            const nameMatch = cat.name.toLowerCase().includes(q);
            const pathMatch = cat.path.toLowerCase().includes(q);
            if (q && !nameMatch && !pathMatch) return;

            matchCount++;
            const li = document.createElement('li');
            li.className = 'vs-cat-option' + (selectedId === cat.id ? ' is-selected' : '');
            li.setAttribute('role','option');
            li.setAttribute('tabindex','-1');
            li.setAttribute('data-value', String(cat.id));
            li.style.setProperty('--cat-depth', String(cat.depth));

            const countTxt = cat.count > 0
                ? cat.count + ' product' + (cat.count !== 1 ? 's' : '')
                : 'empty';

            const showPath = q && cat.depth > 0 && !nameMatch && pathMatch;
            const namePart = highlight(cat.name, nameMatch ? q : '');

            li.innerHTML =
                (cat.depth > 0 ? '<span class="vs-cat-child-indicator">' + childArrow() + '</span>' : '') +
                '<span class="vs-cat-info">' +
                    '<span class="vs-cat-name">' + namePart + '</span>' +
                    (showPath || (q && pathMatch && !nameMatch)
                        ? '<span class="vs-cat-path">' + highlight(cat.path, q) + '</span>'
                        : cat.depth > 0
                            ? '<span class="vs-cat-path">' + escHtml(cat.path) + '</span>'
                            : '') +
                '</span>' +
                '<span class="vs-cat-count-badge">' + escHtml(countTxt) + '</span>' +
                '<span class="vs-cat-check">' + checkIcon() + '</span>';

            li.addEventListener('click', () => selectCat(cat.id, cat.name));
            li.addEventListener('mouseenter', () => setFocus(visibleOptions.indexOf(li)));
            listEl.appendChild(li);
            visibleOptions.push(li);
        });

        // Count bar
        if (q) {
            countEl.textContent = matchCount + ' result' + (matchCount !== 1 ? 's' : '') + ' for "' + query + '"';
        } else {
            countEl.textContent = CATS.length + ' categor' + (CATS.length !== 1 ? 'ies' : 'y') + ' available';
        }

        noResults.style.display = (q && matchCount === 0) ? '' : 'none';
    }

    // ── Select ────────────────────────────────────────
    function selectCat(id, name) {
        selectedId         = id;
        hiddenInput.value  = id;
        searchEl.value     = id === 0 ? '' : name;
        clearBtn.style.display = id !== 0 ? 'flex' : 'none';
        closeDropdown();
    }

    // ── Open/Close ────────────────────────────────────
    function openDropdown() {
        if (wrap.classList.contains('is-open')) return;
        wrap.classList.add('is-open');
        wrap.setAttribute('aria-expanded','true');
        listboxWrap.style.display = '';
        buildOptions(searchEl.value);
    }

    function closeDropdown() {
        wrap.classList.remove('is-open');
        wrap.setAttribute('aria-expanded','false');
        listboxWrap.style.display = 'none';
        focusedIndex = -1;
    }

    // ── Keyboard focus ────────────────────────────────
    function setFocus(idx) {
        if (focusedIndex >= 0 && visibleOptions[focusedIndex]) {
            visibleOptions[focusedIndex].classList.remove('is-focused');
        }
        focusedIndex = idx;
        if (idx >= 0 && visibleOptions[idx]) {
            visibleOptions[idx].classList.add('is-focused');
            visibleOptions[idx].scrollIntoView({ block:'nearest' });
        }
    }

    // ── Events ────────────────────────────────────────
    searchEl.addEventListener('focus', openDropdown);
    searchEl.addEventListener('click', openDropdown);
    searchEl.addEventListener('input', () => { openDropdown(); buildOptions(searchEl.value); });

    searchEl.addEventListener('keydown', (e) => {
        if (!wrap.classList.contains('is-open')) {
            if (e.key === 'ArrowDown' || e.key === 'Enter') openDropdown();
            return;
        }
        switch(e.key) {
            case 'ArrowDown':
                e.preventDefault();
                setFocus(Math.min(focusedIndex + 1, visibleOptions.length - 1));
                break;
            case 'ArrowUp':
                e.preventDefault();
                setFocus(Math.max(focusedIndex - 1, 0));
                break;
            case 'Enter':
                e.preventDefault();
                if (focusedIndex >= 0 && visibleOptions[focusedIndex]) visibleOptions[focusedIndex].click();
                break;
            case 'Escape':
                closeDropdown();
                break;
        }
    });

    clearBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        selectCat(0, '');
        searchEl.focus();
        openDropdown();
    });

    document.addEventListener('click', (e) => {
        if (!wrap.contains(e.target) && e.target !== searchEl) closeDropdown();
    });

    buildOptions('');
})();
</script>


                                <div class="vs-field full">
                                    <label><?php echo esc_html__('Product Images', 'vendor-space'); ?></label>

                                    <!-- Featured Image -->
                                    <div class="vs-upload-box" id="vs-edit-featured-box">
                                        <span class="vs-plus">+</span>
                                        <input type="file" id="vs-edit-featured-input" name="featured_image" accept="image/*" hidden>
                                    </div>

                                    <!-- Gallery -->
                                    <hr>
                                    <label><?php echo esc_html__('Gallery', 'vendor-space'); ?></label>
                                    <div class="vs-gallery-wrapper">
                                        <div class="vs-gallery" id="vs-edit-gallery"></div>
                                        <div class="vs-gallery-add" id="vs-edit-gallery-add">
                                            <span class="vs-plus">+</span>
                                            <input type="file" id="vs-edit-gallery-input" name="product_images[]" accept="image/*" multiple hidden>
                                        </div>
                                    </div>
                                </div>

                                <div class="vs-field full">
                                    <label><?php echo esc_html__('Current Images', 'vendor-space'); ?></label>
                                    <div id="vs-edit-images" class="vs-edit-images"></div>
                                    <input type="hidden" name="remove_gallery_ids" id="vs-remove-gallery-ids" value="">
                                    <input type="hidden" name="remove_featured" id="vs-remove-featured" value="0">
                                </div>
                            </div>
 <div class="vs-field full">
                                    <label><?php echo esc_html__('Description', 'vendor-space'); ?></label>
                                    <?php
                                    wp_editor(
                                        '',
                                        'edit_product_desc',
                                        [
                                            'textarea_name'  => 'product_desc',
                                            'media_buttons'  => true,
                                            'teeny'          => false,
                                            'quicktags'      => false,
                                            'textarea_rows'  => 6,
                                            'default_editor' => 'tinymce',
                                        ]
                                    );
                                    ?>
                                </div>

                                <div class="vs-field full">
                                    <label><?php echo esc_html__('Product Short Description', 'vendor-space'); ?></label>
                                    <?php
                                    wp_editor(
                                        '',
                                        'edit_product_short_desc',
                                        [
                                            'textarea_name'  => 'product_short_desc',
                                            'media_buttons'  => true,
                                            'teeny'          => false,
                                            'quicktags'      => false,
                                            'textarea_rows'  => 6,
                                            'default_editor' => 'tinymce',
                                        ]
                                    );
                                    ?>
                                </div>

                            <div class="vs-form-actions">
                                <button type="submit" id="vs-save-edit" class="vs-btn vs-btn-primary"><?php echo esc_html__('Save', 'vendor-space'); ?></button>
                                <button type="button" id="vs-cancel-edit" class="vs-btn vs-btn-cancel"><?php echo esc_html__('Cancel', 'vendor-space'); ?></button>
                            </div>
                        </form>
                    </div>
                      <!-- Add Product Form  -->
                   <div id="add-product-form-wrapper" class="vs-form-wrapper" style="display:none;">
                        <h3><?php echo esc_html__('Add New Product', 'vendor-space'); ?></h3>
 <?php
                $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';
                if ($manual_approval) {
                    echo '<div class="full" style="background:#fef3c7; border:1px solid #f59e0b; padding:10px; margin-bottom:10px; border-radius:4px; color:#92400e; font-size:0.9em;">';
                    echo '<strong>⚠️ Approval Required:</strong> Products must be approved by an administrator before being visible to customers.';
                    echo '</div>';
                }
                ?>
    <form id="vs-add-product-form" method="post" enctype="multipart/form-data">

        <input type="hidden" name="action" value="vs_add_product">
        <?php wp_nonce_field('vs_add_product','vs_add_product_nonce'); ?>

        <div class="vs-grid">

            <div class="vs-field full">
                <label class="vs-label-required"><?php echo esc_html__('Product Name', 'vendor-space'); ?></label>
                <input type="text" name="product_name" required>
            </div>

          

                 <div class="vs-field">
    <label class="vs-label-required"><?php echo esc_html__('Regular Price', 'vendor-space'); ?></label>
    
    <div class="vs-price-input">
        <span class="vs-currency-symbol">
            <?php echo esc_html( get_woocommerce_currency_symbol( get_woocommerce_currency() ) ); ?>
        </span>
        <input type="number" step="0.01" name="product_price" id="edit-product-price" required>
    </div>
</div>

            <div class="vs-field">
    <label><?php echo esc_html__('Sale Price', 'vendor-space'); ?></label>

    <div class="vs-price-input">
        <span class="vs-currency-symbol">
            <?php echo esc_html( get_woocommerce_currency_symbol( get_woocommerce_currency() ) ); ?>
        </span>
        <input type="number" step="0.01" name="product_sale_price" id="edit-product-sale-price">
    </div>
</div>

            <div class="vs-field"  class="vs-label-required">
                <label class="vs-label-required"><?php echo esc_html__('Stock Quantity', 'vendor-space'); ?></label>
                <input type="number" name="product_stock" required>
            </div>

            <div class="vs-field">
                <label><?php echo esc_html__('SKU', 'vendor-space'); ?></label>
                <input type="text" name="product_sku">
            </div>

            <div class="vs-field">
                <label><?php echo esc_html__('Product Type', 'vendor-space'); ?></label>
                <select name="product_type" id="add-product-type" class="vs-product-type-select">
                    <option value="simple"><?php echo esc_html__('Simple', 'vendor-space'); ?></option>
                    <option value="variable"><?php echo esc_html__('Variable', 'vendor-space'); ?></option>
                </select>
            </div>

            <div class="vs-field full">
                <div class="vs-variable-product-panel" style="display:none; margin-top: 6px;">
                    <h3><?php echo esc_html__('Attributes', 'vendor-space'); ?></h3>
                    <div class="vs-attributes-wrapper"></div>
                    <button type="button" class="vs-btn vs-add-attribute-btn"><?php echo esc_html__('+ Add Attribute', 'vendor-space'); ?></button>

                    <hr>

                    <h3><?php echo esc_html__('Bulk Actions', 'vendor-space'); ?></h3>
                    <div class="vs-bulk-actions">
                        <input type="number" class="vs-bulk-price" placeholder="<?php echo esc_attr__('Set price for all', 'vendor-space'); ?>">
                        <input type="number" class="vs-bulk-stock" placeholder="<?php echo esc_attr__('Set stock for all', 'vendor-space'); ?>">
                        <button type="button" class="vs-btn vs-apply-bulk-btn"><?php echo esc_html__('Apply', 'vendor-space'); ?></button>
                    </div>

                    <hr>

                    <button type="button" class="vs-btn vs-btn-primary vs-generate-variations-btn"><?php echo esc_html__('Generate Variations', 'vendor-space'); ?></button>
                    <h3><?php echo esc_html__('Variations', 'vendor-space'); ?></h3>
                    <div class="vs-variations-container"></div>
                </div>
            </div>

            <div class="vs-field">
                <label><?php echo esc_html__('Status', 'vendor-space'); ?></label>
               
                <select name="product_status">
                    <option value="publish"><?php echo esc_html__('Publish', 'vendor-space'); ?></option>
                    <option value="draft"><?php echo esc_html__('Draft', 'vendor-space'); ?></option>
                    <option value="pending"><?php echo esc_html__('Pending', 'vendor-space'); ?></option>
                </select>
            </div>

            <?php if (current_user_can('administrator')): ?>
            <div class="vs-field vs-vendor-select-wrap">
                <label for="vs-vendor-search">
                    <?php echo esc_html__('Assign To Vendor', 'vendor-space'); ?>
                </label>

                <?php
                $vendor_args = [
                    'number'  => -1,
                    'orderby' => 'display_name',
                    'order'   => 'ASC',
                ];
                $all_users        = get_users($vendor_args);
                $available_vendors = [];

                foreach ($all_users as $u) {
                    $uid             = (int) $u->ID;
                    if (user_can($uid, 'manage_options')) continue;
                    $is_vendor_role  = in_array('vendor', (array) $u->roles, true);
                    $can_edit        = user_can($uid, 'edit_products');
                    if (!$is_vendor_role && !$can_edit) continue;
                    $v_status = get_user_meta($uid, 'vs_vendor_status', true) ?: 'active';
                    if ($v_status === 'deleted') continue;
                    $available_vendors[] = $u;
                }

                $vendors_json = [];
                foreach ($available_vendors as $v) {
                    $vendors_json[] = [
                        'id'     => (int) $v->ID,
                        'name'   => $v->display_name,
                        'email'  => $v->user_email,
                        'avatar' => strtoupper(mb_substr($v->display_name, 0, 1)),
                        'status' => get_user_meta((int) $v->ID, 'vs_vendor_status', true) ?: 'active',
                    ];
                }
                ?>

                <!-- Hidden real input sent with form -->
                <input type="hidden" name="product_vendor" id="add-product-vendor" value="0">

                <div class="vs-custom-select" id="vs-vendor-dropdown" role="combobox" aria-expanded="false" aria-haspopup="listbox">
                    <div class="vs-select-trigger">
                        <span class="vs-select-icon">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"
                                 stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                            </svg>
                        </span>
                        <input
                            type="text"
                            id="vs-vendor-search"
                            class="vs-select-search"
                            placeholder="<?php echo esc_attr__('Search by name or email...', 'vendor-space'); ?>"
                            autocomplete="off"
                            aria-autocomplete="list"
                            aria-controls="vs-vendor-listbox"
                        >
                        <span class="vs-select-clear" id="vs-vendor-clear" title="Clear" style="display:none;" aria-label="Clear selection">
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
                                 stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                            </svg>
                        </span>
                        <span class="vs-select-chevron">
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
                                 stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="6 9 12 15 18 9"/>
                            </svg>
                        </span>
                    </div>

                    <div class="vs-select-dropdown" id="vs-vendor-listbox-wrap" style="display:none;">
                        <div class="vs-select-count" id="vs-vendor-count"></div>
                        <ul class="vs-select-list" id="vs-vendor-listbox" role="listbox" aria-label="Vendors">
                            <li class="vs-option vs-option-none" data-value="0" role="option">
                                <span class="vs-option-placeholder-text">
                                    <?php echo esc_html__('-- No vendor assigned --', 'vendor-space'); ?>
                                </span>
                            </li>
                        </ul>
                        <div class="vs-no-results" id="vs-no-results" style="display:none;">
                            <?php echo esc_html__('No vendors found.', 'vendor-space'); ?>
                        </div>
                    </div>
                </div>

                <span class="vs-total-badge">
                    <?php printf(esc_html__('%d vendor(s) available', 'vendor-space'), count($available_vendors)); ?>
                </span>
            </div>
            <?php endif; ?>

<style>
/* ───────── Unified Custom Select Styles ───────── */
.vs-vendor-select-wrap, .vs-category-select-wrap {
    position: relative;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.vs-vendor-select-wrap label, .vs-category-select-wrap label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 6px;
}

.vs-custom-select {
    position: relative;
    width: 100%;
}

.vs-select-trigger {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
    min-height: 42px;
    padding: 0 12px;
    background: #fff;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    cursor: text;
    transition: all 0.2s ease;
}

.vs-custom-select.is-open .vs-select-trigger,
.vs-select-trigger:focus-within {
    border-color: #4f46e5;
    box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.vs-select-search {
    flex: 1;
    border: none;
    outline: none;
    font-size: 14px;
    background: transparent;
}

.vs-select-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    left: 0;
    right: 0;
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);
    z-index: 9999;
    overflow: hidden;
}

.vs-select-list {
    list-style: none;
    margin: 0;
    padding: 4px 0;
    max-height: 240px;
    overflow-y: auto;
}

.vs-option {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 12px;
    cursor: pointer;
    transition: background 0.15s;
}

.vs-option:hover, .vs-option.is-focused {
    background: #f5f3ff;
}

.vs-option.is-selected {
    background: #eef2ff;
    color: #4f46e5;
}

/* Avatar */
.vs-option-avatar {
    height: 30px;
    border-radius: 50%;
    background: linear-gradient(135deg, #6366f1, #8b5cf6);
    color: #fff;
    font-size: 12px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    letter-spacing: 0;
}

.vs-option-info {
    display: flex;
    flex-direction: column;
    min-width: 0;
    flex: 1;
}

.vs-option-name {
    font-size: 13.5px;
    color: #1e293b;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.vs-option-email {
    font-size: 11.5px;
    color: #6b7280;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.vs-option-check {
    margin-left: auto;
    color: #6366f1;
    flex-shrink: 0;
    display: none;
}
.vs-option.is-selected .vs-option-check { display: flex; }

/* Status badge */
.vs-option-status {
    font-size: 10px;
    font-weight: 600;
    padding: 2px 6px;
    border-radius: 20px;
    text-transform: capitalize;
    flex-shrink: 0;
}
.vs-status-active   { background: #dcfce7; color: #166534; }
.vs-status-pending  { background: #fef9c3; color: #854d0e; }
.vs-status-inactive { background: #f1f5f9; color: #64748b; }

/* No results */
.vs-no-results {
    padding: 18px 12px;
    text-align: center;
    color: #9ca3af;
    font-size: 13px;
}

/* Total badge */
.vs-total-badge {
    display: inline-block;
    margin-top: 6px;
    font-size: 11px;
    color: #6b7280;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 2px 8px;
    font-weight: 500;
}

/* Highlight match */
.vs-highlight {
    background: #fef08a;
    border-radius: 2px;
    padding: 0 1px;
    color: #92400e;
    font-weight: 700;
}
</style>

<script>
(function () {
    const VENDORS = <?php echo wp_json_encode($vendors_json); ?>;

    const wrap       = document.getElementById('vs-vendor-dropdown');
    const searchEl   = document.getElementById('vs-vendor-search');
    const listEl     = document.getElementById('vs-vendor-listbox');
    const listboxWrap= document.getElementById('vs-vendor-listbox-wrap');
    const hiddenInput= document.getElementById('add-product-vendor');
    const clearBtn   = document.getElementById('vs-vendor-clear');
    const countEl    = document.getElementById('vs-vendor-count');
    const noResults  = document.getElementById('vs-no-results');

    let selectedId   = 0;
    let focusedIndex = -1;
    let visibleOptions = [];

    // ── Build options ────────────────────────────────
    function buildOptions(query) {
        const q = (query || '').toLowerCase().trim();
        listEl.innerHTML = '';
        visibleOptions   = [];
        focusedIndex     = -1;

        // "None" option
        const noneItem = document.createElement('li');
        noneItem.className = 'vs-option vs-option-none' + (selectedId === 0 ? ' is-selected' : '');
        noneItem.setAttribute('role', 'option');
        noneItem.setAttribute('data-value', '0');
        noneItem.setAttribute('tabindex', '-1');
        noneItem.innerHTML = '<span class="vs-option-placeholder-text">-- No vendor assigned --</span>'
            + '<span class="vs-option-check"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>';
        noneItem.addEventListener('click', () => selectVendor(0, ''));
        listEl.appendChild(noneItem);
        if (!q) visibleOptions.push(noneItem);

        let matchCount = 0;

        VENDORS.forEach(v => {
            const nameMatch  = v.name.toLowerCase().includes(q);
            const emailMatch = v.email.toLowerCase().includes(q);
            if (q && !nameMatch && !emailMatch) return;

            matchCount++;
            const li = document.createElement('li');
            li.className = 'vs-option' + (selectedId === v.id ? ' is-selected' : '');
            li.setAttribute('role', 'option');
            li.setAttribute('data-value', String(v.id));
            li.setAttribute('tabindex', '-1');

            const statusClass = ['active','pending','inactive'].includes(v.status) ? v.status : 'active';
            const hl = (str) => q ? str.replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'), '<mark class="vs-highlight">$1</mark>') : str;

            li.innerHTML =
                '<span class="vs-option-avatar">' + escHtml(v.avatar) + '</span>' +
                '<span class="vs-option-info">' +
                    '<span class="vs-option-name">'  + hl(escHtml(v.name))  + '</span>' +
                    '<span class="vs-option-email">' + hl(escHtml(v.email)) + '</span>' +
                '</span>' +
                '<span class="vs-option-status vs-status-' + statusClass + '">' + escHtml(statusClass) + '</span>' +
                '<span class="vs-option-check"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg></span>';

            li.addEventListener('click', () => selectVendor(v.id, v.name + ' (' + v.email + ')'));
            li.addEventListener('mouseenter', () => setFocus(visibleOptions.indexOf(li)));

            listEl.appendChild(li);
            visibleOptions.push(li);
        });

        // Count bar
        if (q) {
            countEl.textContent = matchCount + ' result' + (matchCount !== 1 ? 's' : '') + ' for "' + query + '"';
        } else {
            countEl.textContent = VENDORS.length + ' vendor' + (VENDORS.length !== 1 ? 's' : '') + ' available';
        }

        noResults.style.display = (q && matchCount === 0) ? '' : 'none';
    }

    // ── Select vendor ─────────────────────────────────
    function selectVendor(id, label) {
        selectedId          = id;
        hiddenInput.value   = id;
        searchEl.value      = id === 0 ? '' : label;
        searchEl.placeholder = id === 0 ? 'Search by name or email...' : '';
        clearBtn.style.display = id !== 0 ? '' : 'none';
        closeDropdown();
    }

    // ── Open / Close ──────────────────────────────────
    function openDropdown() {
        if (wrap.classList.contains('is-open')) return;
        wrap.classList.add('is-open');
        wrap.setAttribute('aria-expanded', 'true');
        listboxWrap.style.display = '';
        buildOptions(searchEl.value);
    }

    function closeDropdown() {
        wrap.classList.remove('is-open');
        wrap.setAttribute('aria-expanded', 'false');
        listboxWrap.style.display = 'none';
        focusedIndex = -1;
    }

    // ── Keyboard focus ────────────────────────────────
    function setFocus(idx) {
        if (focusedIndex >= 0 && visibleOptions[focusedIndex]) {
            visibleOptions[focusedIndex].classList.remove('is-focused');
        }
        focusedIndex = idx;
        if (idx >= 0 && visibleOptions[idx]) {
            visibleOptions[idx].classList.add('is-focused');
            visibleOptions[idx].scrollIntoView({ block: 'nearest' });
        }
    }

    // ── Events ────────────────────────────────────────
    searchEl.addEventListener('focus', openDropdown);
    searchEl.addEventListener('click', openDropdown);

    searchEl.addEventListener('input', () => {
        openDropdown();
        buildOptions(searchEl.value);
    });

    searchEl.addEventListener('keydown', (e) => {
        if (!wrap.classList.contains('is-open')) {
            if (e.key === 'ArrowDown' || e.key === 'Enter') openDropdown();
            return;
        }
        switch (e.key) {
            case 'ArrowDown':
                e.preventDefault();
                setFocus(Math.min(focusedIndex + 1, visibleOptions.length - 1));
                break;
            case 'ArrowUp':
                e.preventDefault();
                setFocus(Math.max(focusedIndex - 1, 0));
                break;
            case 'Enter':
                e.preventDefault();
                if (focusedIndex >= 0 && visibleOptions[focusedIndex]) {
                    visibleOptions[focusedIndex].click();
                }
                break;
            case 'Escape':
                closeDropdown();
                break;
        }
    });

    clearBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        selectVendor(0, '');
        searchEl.focus();
        openDropdown();
    });

    document.addEventListener('click', (e) => {
        if (!wrap.contains(e.target) && e.target !== searchEl) {
            closeDropdown();
        }
    });

    // ── Utility ───────────────────────────────────────
    function escHtml(str) {
        return String(str)
            .replace(/&/g,'&amp;')
            .replace(/</g,'&lt;')
            .replace(/>/g,'&gt;')
            .replace(/"/g,'&quot;');
    }

    // Init
    buildOptions('');
})();
</script>


            <div class="vs-field full vs-cat-select-wrap">
    <label for="vs-cat-search-add">
        <?php echo esc_html__('Categories', 'vendor-space'); ?>
    </label>
 
    <?php
    // Fetch all product categories with hierarchy
    $raw_cats = get_terms([
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'orderby'    => 'name',
        'order'      => 'ASC',
    ]);
 
    // Build a map: id => term
    $cat_map = [];
    if (!is_wp_error($raw_cats)) {
        foreach ($raw_cats as $t) {
            $cat_map[$t->term_id] = $t;
        }
    }
 
    // Build flat list with computed depth/path
    $cats_json = [];
    if (!is_wp_error($raw_cats)) {
        foreach ($raw_cats as $t) {
            // Build breadcrumb path
            $path_parts = [$t->name];
            $parent_id  = $t->parent;
            while ($parent_id && isset($cat_map[$parent_id])) {
                array_unshift($path_parts, $cat_map[$parent_id]->name);
                $parent_id = $cat_map[$parent_id]->parent;
            }
            $depth = count($path_parts) - 1;
 
            $cats_json[] = [
                'id'        => (int) $t->term_id,
                'name'      => $t->name,
                'slug'      => $t->slug,
                'parent'    => (int) $t->parent,
                'count'     => (int) $t->count,
                'depth'     => $depth,
                'path'      => implode(' > ', $path_parts),
            ];
        }
    }
 
    // Current selected value (always 0 for add product)
    $current_cat = 0;
    $current_cat_label = '';
    ?>
 
    <!-- Hidden real input -->
    <!-- Category Source Select (Hidden, used as the value holder and for clones) -->
    <select name="product_cat" id="add-product-cat" style="display:none;">
        <option value="0" selected><?php echo esc_html__('No category', 'vendor-space'); ?></option>
        <?php foreach ($cats_json as $cat): ?>
            <option value="<?php echo esc_attr($cat['id']); ?>"><?php echo esc_html($cat['path']); ?></option>
        <?php endforeach; ?>
    </select>
 
    <div class="vs-custom-select vs-cat-dropdown" id="vs-cat-dropdown-add"
         role="combobox" aria-expanded="false" aria-haspopup="listbox">
 
        <!-- Search / Trigger -->
        <div class="vs-select-trigger">
            <span class="vs-select-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M20 7H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2z"/>
                    <path d="M16 3l-4 4-4-4"/>
                </svg>
            </span>
            <input
                type="text"
                id="vs-cat-search-add"
                class="vs-select-search"
                placeholder="<?php echo esc_attr__('Search categories...', 'vendor-space'); ?>"
                autocomplete="off"
                aria-autocomplete="list"
                aria-controls="vs-cat-listbox-add"
                value="<?php echo esc_attr($current_cat_label); ?>"
            >
            <span class="vs-select-clear" id="vs-cat-clear-add" title="Clear"
                  style="display:none;" aria-label="Clear selection">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                </svg>
            </span>
            <span class="vs-select-chevron">
                <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24"
                     fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="6 9 12 15 18 9"/>
                </svg>
            </span>
        </div>
 
        <!-- Listbox -->
        <div class="vs-select-dropdown" id="vs-cat-listbox-wrap-add" style="display:none;">
            <div class="vs-select-count" id="vs-cat-count-add"></div>
            <ul class="vs-select-list" id="vs-cat-listbox-add" role="listbox" aria-label="Product Categories">
                <!-- Populated by JS -->
            </ul>
            <div class="vs-no-results" id="vs-cat-no-results-add" style="display:none;">
                <?php echo esc_html__('No categories found.', 'vendor-space'); ?>
            </div>
        </div>
    </div>
 
    <!-- Total badge -->
    <span class="vs-total-badge" id="vs-cat-total-badge-add">
        <?php
        $total = count($cats_json);
        printf(esc_html__('%d categor%s available', 'vendor-space'), $total, $total === 1 ? 'y' : 'ies');
        ?>
    </span>
 
    
</div>

<script>
(function () {
    const CATS = <?php echo wp_json_encode($cats_json); ?>;

    const wrap        = document.getElementById('vs-cat-dropdown-add');
    const searchEl    = document.getElementById('vs-cat-search-add');
    const listEl      = document.getElementById('vs-cat-listbox-add');
    const listboxWrap = document.getElementById('vs-cat-listbox-wrap-add');
    const hiddenInput = document.getElementById('add-product-cat');
    const clearBtn    = document.getElementById('vs-cat-clear-add');
    const countEl     = document.getElementById('vs-cat-count-add');
    const noResults   = document.getElementById('vs-cat-no-results-add');

    let selectedId     = 0;
    let focusedIndex   = -1;
    let visibleOptions = [];

    function escHtml(str) {
        return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
    function highlight(str, q) {
        if (!q) return escHtml(str);
        return escHtml(str).replace(new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + ')', 'gi'), '<mark class="vs-highlight">$1</mark>');
    }

    function checkIcon() { return '<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'; }
    function childArrow() { return '<svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>'; }

    function buildOptions(query) {
        const q = (query || '').toLowerCase().trim();
        listEl.innerHTML = '';
        visibleOptions = [];
        focusedIndex = -1;

        const noneEl = document.createElement('li');
        noneEl.className = 'vs-cat-option vs-cat-option-none' + (selectedId === 0 ? ' is-selected' : '');
        noneEl.innerHTML = '<span class="vs-cat-info"><span class="vs-cat-name">-- <?php echo esc_js(__('No category selected', 'vendor-space')); ?> --</span></span>' + '<span class="vs-cat-check">' + checkIcon() + '</span>';
        noneEl.addEventListener('click', () => selectCat(0, ''));
        listEl.appendChild(noneEl);
        if (!q) visibleOptions.push(noneEl);

        let matchCount = 0;
        CATS.forEach(cat => {
            if (q && !cat.name.toLowerCase().includes(q) && !cat.path.toLowerCase().includes(q)) return;
            matchCount++;
            const li = document.createElement('li');
            li.className = 'vs-cat-option' + (selectedId === cat.id ? ' is-selected' : '');
            li.style.setProperty('--cat-depth', String(cat.depth));
            li.innerHTML = (cat.depth > 0 ? '<span class="vs-cat-child-indicator">' + childArrow() + '</span>' : '') + '<span class="vs-cat-info">' + '<span class="vs-cat-name">' + highlight(cat.name, q) + '</span>' + (cat.path && q && cat.path.toLowerCase().includes(q) ? '<span class="vs-cat-path">' + highlight(cat.path, q) + '</span>' : '') + '</span>' + '<span class="vs-cat-count-badge">' + cat.count + '</span>' + '<span class="vs-cat-check">' + checkIcon() + '</span>';
            li.addEventListener('click', () => selectCat(cat.id, cat.name));
            listEl.appendChild(li);
            visibleOptions.push(li);
        });
        countEl.textContent = q ? matchCount + ' results for "' + query + '"' : CATS.length + ' categories available';
        noResults.style.display = (q && matchCount === 0) ? '' : 'none';
    }

    function selectCat(id, name) {
        selectedId = id; hiddenInput.value = id; searchEl.value = id === 0 ? '' : name;
        clearBtn.style.display = id !== 0 ? 'flex' : 'none';
        closeDropdown();
    }
    function openDropdown() { if (wrap.classList.contains('is-open')) return; wrap.classList.add('is-open'); listboxWrap.style.display = ''; buildOptions(searchEl.value); }
    function closeDropdown() { wrap.classList.remove('is-open'); listboxWrap.style.display = 'none'; }

    searchEl.addEventListener('focus', openDropdown);
    searchEl.addEventListener('input', () => { openDropdown(); buildOptions(searchEl.value); });
    clearBtn.addEventListener('click', (e) => { e.stopPropagation(); selectCat(0, ''); searchEl.focus(); });
    document.addEventListener('click', (e) => { if (!wrap.contains(e.target) && e.target !== searchEl) closeDropdown(); });

    buildOptions('');
})();
</script>
 

 <div class="vs-field full">
    <label><?php echo esc_html__('Product Images', 'vendor-space'); ?></label>

    <!-- Featured Image -->
    <div class="vs-upload-box" id="vs-featured-box">
        <span class="vs-plus">+</span>
        <input type="file" id="vs-featured-input" name="featured_image" accept="image/*" hidden>
    </div>

    <!-- Gallery -->
     <hr>
    <label><?php echo esc_html__('Gallery', 'vendor-space'); ?></label>

    <div class="vs-gallery-wrapper">

        <div class="vs-gallery" id="vs-gallery"></div>

        <!-- Small + -->
        <div class="vs-gallery-add" id="vs-gallery-add">
            <span class="vs-plus">+</span>
            <input type="file" id="vs-gallery-input" name="product_images[]" accept="image/*" multiple hidden>
        </div>
    </div>
</div>


              <div class="vs-field full">
                <label><?php echo esc_html__('Description', 'vendor-space'); ?></label>


    <?php
    wp_editor(
        '',
        'product_desc',
        [
            'textarea_name'  => 'product_desc',
        'media_buttons'  => true,
        'teeny'          => false,
        'quicktags'      => false, 
        'textarea_rows'  => 6,
        'default_editor' => 'tinymce',
        ]
    );
    ?>
</div>
            <div class="vs-field full">
    <label><?php echo esc_html__('Product Short Description', 'vendor-space'); ?></label>

    <?php

    wp_editor(
    '',
    'product_short_desc',
    [
        'textarea_name'  => 'product_short_desc',
        'media_buttons'  => true,
        'teeny'          => false,
        'quicktags'      => false,   // Ù†Ø®Ù„ÙŠÙ‡Ø§ ÙƒÙŠÙ…Ø§ Woo
        'textarea_rows'  => 6,
        'default_editor' => 'tinymce', // â­ Ù‡Ø°Ø§ Ù‡Ùˆ Ø§Ù„Ù…Ù‡Ù…
    ]
);

    ?>
</div>
  <div class="vs-form-actions">
            <button type="submit" class="vs-btn vs-btn-primary"><?php echo esc_html__('Add Product', 'vendor-space'); ?></button>
            <button type="button" id="vs-cancel-add" class="vs-btn vs-btn-cancel" style=" background: #fff;
    color: #2271b1;"><?php echo esc_html__('Cancel', 'vendor-space'); ?></button>
        </div>
        </div>

      

    </form>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {

  const featuredBox   = document.getElementById('vs-featured-box');
  const featuredInput = document.getElementById('vs-featured-input');

  const galleryAdd    = document.getElementById('vs-gallery-add');
  const galleryInput  = document.getElementById('vs-gallery-input');
  const gallery       = document.getElementById('vs-gallery');
  const galleryDT     = (typeof DataTransfer !== 'undefined') ? new DataTransfer() : null;

  const editFeaturedBox   = document.getElementById('vs-edit-featured-box');
  const editFeaturedInput = document.getElementById('vs-edit-featured-input');

  const editGalleryAdd    = document.getElementById('vs-edit-gallery-add');
  const editGalleryInput  = document.getElementById('vs-edit-gallery-input');
  const editGallery       = document.getElementById('vs-edit-gallery');
  const editGalleryDT     = (typeof DataTransfer !== 'undefined') ? new DataTransfer() : null;

  /* =========================
     FEATURED IMAGE
  ========================= */
  if (featuredBox && featuredInput) {
    featuredBox.addEventListener('click', () => {
      featuredInput.click();
    });

    featuredInput.addEventListener('change', () => {
      const file = featuredInput.files[0];
      if (!file) return;

      const oldPreview = featuredBox.querySelector('img');
      if (oldPreview) oldPreview.remove();

      const img = document.createElement('img');
      img.src = URL.createObjectURL(file);

      featuredBox.appendChild(img);
    });
  }

  if (editFeaturedBox && editFeaturedInput) {
    editFeaturedBox.addEventListener('click', () => {
      editFeaturedInput.click();
    });

    editFeaturedInput.addEventListener('change', () => {
      const file = editFeaturedInput.files[0];
      if (!file) return;

      const oldPreview = editFeaturedBox.querySelector('img');
      if (oldPreview) oldPreview.remove();

      const img = document.createElement('img');
      img.src = URL.createObjectURL(file);

      editFeaturedBox.appendChild(img);
    });
  }

  /* =========================
     GALLERY (+ SMALL)
  ========================= */
  if (galleryAdd && galleryInput && gallery) {
    galleryAdd.addEventListener('click', () => {
      galleryInput.click();
    });

    galleryInput.addEventListener('change', () => {
      const files = Array.from(galleryInput.files || []);
      if (!files.length) return;

      files.forEach(file => {
        if (galleryDT) galleryDT.items.add(file);

        const item = document.createElement('div');
        item.className = 'vs-gallery-item';

        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);

        item.appendChild(img);
        gallery.appendChild(item);
      });

      // Ensure the actual file input stays in sync with the DataTransfer list (so the form submits the selected files)
      if (galleryDT) galleryInput.files = galleryDT.files;
    });
  }

  if (editGalleryAdd && editGalleryInput && editGallery) {
    editGalleryAdd.addEventListener('click', () => {
      editGalleryInput.click();
    });

    editGalleryInput.addEventListener('change', () => {
      const files = Array.from(editGalleryInput.files || []);
      if (!files.length) return;

      files.forEach(file => {
        if (editGalleryDT) editGalleryDT.items.add(file);

        const item = document.createElement('div');
        item.className = 'vs-gallery-item';

        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);

        item.appendChild(img);
        editGallery.appendChild(item);
      });

      // Ensure the actual file input stays in sync with the DataTransfer list (so the form submits the selected files)
      if (editGalleryDT) editGalleryInput.files = editGalleryDT.files;
    });
  }

});
</script>


                <?php if ($products): ?>
                    <table class="vs-products-table" data-product-count="<?php echo esc_attr($vs_total_products_no_trash); ?>" data-total-pages="<?php echo esc_attr($total_pages); ?>" style="background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05);">
                        <thead>
                        <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                                <th style="padding: 15px 20px; font-weight: 600; background-color: #f8fafc;"> <input type="checkbox" id="vs-select-all"></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Image', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Name', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Categories', 'vendor-space'); ?></th>
         <?php if ( current_user_can('administrator') ) : ?>                         
            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Vendor', 'vendor-space'); ?></th>
         <?php else : ?>
                                            <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Price', 'vendor-space'); ?></th>

  <?php endif; ?>
                         <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Stock', 'vendor-space'); ?></th>
 
                               <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Status', 'vendor-space'); ?></th>
                                <th data-export="skip" style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="vs-products-tbody">
                            <?php foreach($products as $p):
                                if ($p->post_status === 'trash') continue;
                                
                                $price = get_post_meta($p->ID, '_price', true);
                                $regular_price = get_post_meta($p->ID, '_regular_price', true);
                                $sale_price = get_post_meta($p->ID, '_sale_price', true);
                                $stock = get_post_meta($p->ID, '_stock', true);
                                $sku = get_post_meta($p->ID, '_sku', true);
                                $type_terms = wp_get_post_terms($p->ID, 'product_type', ['fields' => 'slugs']);
                                $product_type = !empty($type_terms) ? $type_terms[0] : 'simple';
                                if ($product_type === 'variable') {
                                    $variation_ids = get_posts([
                                        'post_type' => 'product_variation',
                                        'post_parent' => (int) $p->ID,
                                        'post_status' => ['publish', 'private', 'draft'],
                                        'numberposts' => -1,
                                        'fields' => 'ids',
                                    ]);
                                    $sum_stock = 0;
                                    foreach ($variation_ids as $vid) {
                                        $vs = get_post_meta((int) $vid, '_stock', true);
                                        if ($vs === '' || $vs === null) continue;
                                        $sum_stock += (int) $vs;
                                    }
                                    $stock = $sum_stock;
                                }
                                $cat_terms = wp_get_post_terms($p->ID, 'product_cat', ['fields' => 'ids']);
                                $product_cat = !empty($cat_terms) ? $cat_terms[0] : '';
                                $short_desc = $p->post_excerpt;
                                $featured_id = get_post_thumbnail_id($p->ID);
                                $featured_url = $featured_id ? wp_get_attachment_image_url($featured_id, 'thumbnail') : '';
                                $gallery_meta = get_post_meta($p->ID, '_product_image_gallery', true);
                                $gallery_ids = $gallery_meta ? array_filter(array_map('intval', explode(',', $gallery_meta))) : [];
                                $gallery_urls = [];
                                foreach ($gallery_ids as $gid) {
                                    $gurl = wp_get_attachment_image_url($gid, 'thumbnail');
                                    if ($gurl) $gallery_urls[] = $gurl;
                                }
                            $img = get_the_post_thumbnail($p->ID, [50, 50]) ?: '<span class="dashicons dashicons-format-image" style="font-size:40px; color:#ccc;"></span>';
                            ?>
                            <tr id="product-row-<?php echo $p->ID; ?>" data-vendor-id="<?php echo $p->post_author; ?>">
                                                               <td class="product-desc"><?php 
                                    $cats = wp_get_post_terms($p->ID, 'product_cat', ['fields' => 'names']);
                                    echo !empty($cats) && !is_wp_error($cats) ? esc_html(implode(', ', $cats)) : '—';
                                ?></td>
                           <?php if (current_user_can('administrator')) : ?>

<?php
$stores_directory_url = home_url('/stores/');

if (class_exists('VS_Stores') && method_exists('VS_Stores', 'get_stores_directory_url')) {
    $stores_directory_url = (string) VS_Stores::get_stores_directory_url();
}

$vendor_user = get_userdata($p->post_author);

$location = '';
$vendor_email = 'Unknown';
$store_details_url = $stores_directory_url;

if ($vendor_user && is_object($vendor_user)) {

    $location = (string) get_user_meta($vendor_user->ID, 'vs_store_location', true);
    $vendor_email = $vendor_user->user_email;

    $store_details_url = add_query_arg(
        'store_id',
        $vendor_user->ID,
        $stores_directory_url
    );
}
?>

<style>
    td{
        color:black !important;
    }
    </style>
    <td class="product-vendor" style="color:black;"><?php echo esc_html($vendor_email); ?>
                               <div style="font-size:12px; color:#94a3b8; margin-top:4px;">
                                <?php echo esc_html__('Store:', 'vendor-space'); ?>
                                <a href="<?php echo esc_url($store_details_url); ?>" style="color:#2563eb; text-decoration:none; font-weight:600;">
                                    <?php echo esc_html($store_name); ?>
                                </a>
                                <?php if ($location): ?> | <?php echo esc_html($location); ?><?php endif; ?>
                                </div>

</td>
<?php else : ?>
<td class="product-price">
    <?php echo wc_price($price); ?>
</td><?php endif; ?>
<td class="product-stock">
    <?php 
    if (!$stock || $stock == 0) {
        echo '<span class="vs-status-badge rejected">' . esc_html__('OOS', 'vendor-space') . '</span>';
    } else {
        echo esc_html($stock);
    }
    ?>
</td>                                <td class="product-status">
                                    <?php 
                                    $is_rejected = get_post_meta($p->ID, '_vs_rejected', true);
                                    if ($is_rejected) {
                                        echo '<span class="vs-status-badge rejected">' . esc_html__('Rejected', 'vendor-space') . '</span>';
                                    } elseif ($p->post_status === 'pending') {
                                        echo '<span class="vs-status-badge pending">' . esc_html__('Pending Approval', 'vendor-space') . '</span>';
                                    } elseif ($p->post_status === 'pending_vendor') {
                                        echo '<span class="vs-status-badge pending" style="background:#bfdbfe; color:#1e40af;">' . esc_html__('Pending Your Approval', 'vendor-space') . '</span>';
                                    } elseif ($p->post_status === 'publish') {
                                        echo '<span class="vs-status-badge published">' . esc_html__('Published', 'vendor-space') . '</span>';
                                    } else {
                                        echo '<span class="vs-status-badge draft">' . esc_html__('Draft', 'vendor-space') . '</span>';
                                    }
                                    ?>
                                </td>
<td style="min-width:5%;" data-export="skip">
   <div class="vs-action-buttons" style="display:flex; gap:5px; flex-wrap:nowrap; justify-content:flex-start;">

<?php if ($p->post_status === 'trash'): ?>

<button class="vs-action-btn vs-restore-btn"
data-tooltip="<?php echo esc_attr__('Restore', 'vendor-space'); ?>"
data-product-id="<?php echo $p->ID; ?>"
style="background:#f59e0b; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;">
<i class="fas fa-undo"></i>
</button>

<button class="vs-action-btn vs-delete-btn"
data-tooltip="<?php echo esc_attr__('Delete Permanently', 'vendor-space'); ?>"
data-product-id="<?php echo $p->ID; ?>"
data-mode="permanent"
style="background:#e74c3c; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;">
<i class="fas fa-trash-alt"></i>
</button>

<?php else: ?>

<button class="vs-action-btn vs-delete-btn"
data-tooltip="<?php echo esc_attr__('Delete', 'vendor-space'); ?>"
data-product-id="<?php echo $p->ID; ?>"
style="background:#e74c3c; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;">
<i class="fas fa-trash"></i>
</button>

<?php endif; 
?>
<button class="vs-action-btn vs-edit-btn"
data-tooltip="<?php echo esc_attr__('Edit', 'vendor-space'); ?>"
data-product-id="<?php echo esc_attr($p->ID); ?>"
data-product-name="<?php echo esc_attr($p->post_title); ?>"
data-product-desc="<?php echo esc_attr($p->post_content); ?>"
data-product-short-desc="<?php echo esc_attr($short_desc); ?>"
data-product-price="<?php echo esc_attr($price); ?>"
data-product-regular-price="<?php echo esc_attr($regular_price); ?>"
data-product-sale-price="<?php echo esc_attr($sale_price); ?>"
data-product-stock="<?php echo esc_attr($stock); ?>"
data-product-sku="<?php echo esc_attr($sku); ?>"
data-product-type="<?php echo esc_attr($product_type); ?>"
data-product-status="<?php echo esc_attr($p->post_status); ?>"
data-product-cat="<?php echo esc_attr($product_cat); ?>"
data-product-featured-id="<?php echo esc_attr($featured_id); ?>"
data-product-featured-url="<?php echo esc_attr($featured_url); ?>"
data-product-gallery-ids="<?php echo esc_attr(wp_json_encode($gallery_ids)); ?>"
data-product-gallery-urls="<?php echo esc_attr(wp_json_encode($gallery_urls)); ?>"
style="background:#3498db; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;">
<i class="fas fa-pen"></i>
</button>

<button class="vs-action-btn vs-quick-edit-btn"
data-tooltip="<?php echo esc_attr__('Quick Edit', 'vendor-space'); ?>"
data-product-id="<?php echo $p->ID; ?>"
style="background:#0ea5e9; color:white; border:none; padding:5px 10px; border-radius:4px; cursor:pointer;">
<i class="fas fa-bolt"></i>
</button>
<?php if($p->post_status === 'publish'){?>

<a href="<?php echo get_permalink($p->ID); ?>" target="_blank"
class="vs-action-btn vs-view-btn"
data-tooltip="<?php echo esc_attr__('View', 'vendor-space'); ?>"
style="background:#2ecc71; color:white; text-decoration:none; padding:5px 10px; border-radius:4px; display:flex; align-items:center; justify-content:center;">
<i class="fas fa-eye"></i>
</a>
<?php } ?>

    </div>

                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    <div class="vs-products-pagination" id="vs-products-pagination"
                         data-total="<?php echo esc_attr($vs_total_products_no_trash); ?>"
                         data-per-page="<?php echo esc_attr($VS_PRODUCTS_PER_PAGE); ?>"
                         data-total-pages="<?php echo esc_attr($total_pages); ?>"
                         style="margin-top:15px; display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap;">
                    </div>
                <?php else: ?>
                   
                <?php endif; ?>




            </div>
        </div>
 <style>
    /* =========================
   Bulk Quick Edit Modal
========================= */

.swal2-popup.vs-bulk-modal {
  border-radius: 24px !important;
  padding: 22px !important;
  background: #ffffff !important;
  box-shadow: 0 30px 80px rgba(15, 23, 42, 0.18) !important;
}

.swal2-popup.vs-bulk-modal .swal2-title {
  font-size: 22px !important;
  font-weight: 800 !important;
  color: #0f172a !important;
  margin-bottom: 8px !important;
  letter-spacing: -0.02em;
}

.swal2-popup.vs-bulk-modal .swal2-html-container {
  margin: 0 !important;
  padding: 8px 0 0 !important;
}

.vs-bulk-modal-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
  text-align: left;
  font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

.vs-bulk-modal-card {
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 18px;
  padding: 14px;
  box-shadow: inset 0 1px 0 rgba(255,255,255,.85);
}

.vs-bulk-modal-label {
  display: block;
  margin-bottom: 10px;
  font-size: 12px;
  font-weight: 800;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: #64748b;
}

.vs-bulk-modal-control {
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 14px;
  padding: 4px;
  min-height: 54px;
  display: flex;
  align-items: center;
}

/* unified styling for cloned selects / inputs */
.vs-bulk-quick-field,
.vs-bulk-modal-control select,
.vs-bulk-modal-control input,
.vs-bulk-modal-control textarea {
  width: 100% !important;
  height: 46px !important;
  border: 1px solid transparent !important;
  border-radius: 12px !important;
  background: #ffffff !important;
  color: #111827 !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  padding: 0 14px !important;
  outline: none !important;
  box-shadow: none !important;
  transition: all .2s ease !important;
}

/* for textarea if ever used */
.vs-bulk-modal-control textarea.vs-bulk-quick-field {
  min-height: 110px !important;
  height: auto !important;
  padding: 12px 14px !important;
  resize: vertical;
}

.vs-bulk-quick-field:focus,
.vs-bulk-modal-control select:focus,
.vs-bulk-modal-control input:focus,
.vs-bulk-modal-control textarea:focus {
  border-color: #2563eb !important;
  box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.12) !important;
}

/* select arrow spacing */
.vs-bulk-modal-control select.vs-bulk-quick-field,
.vs-bulk-modal-control select {
  appearance: auto;
  cursor: pointer;
}

/* fix if cloned select has tiny default WP style */
.vs-bulk-modal-control .vs-bulk-quick-field.button,
.vs-bulk-modal-control .vs-bulk-quick-field.regular-text {
  height: 46px !important;
  min-height: 46px !important;
}

/* note box */
.vs-bulk-modal-note {
  border: 1px solid #dbeafe;
  background: linear-gradient(180deg, #eff6ff 0%, #f8fbff 100%);
  color: #475569;
  border-radius: 14px;
  padding: 12px 14px;
  font-size: 12px;
  line-height: 1.6;
}

/* SweetAlert buttons */
.swal2-popup.vs-bulk-modal .swal2-actions {
  width: 100%;
  gap: 10px;
  margin-top: 18px !important;
}

.swal2-popup.vs-bulk-modal .swal2-confirm,
.swal2-popup.vs-bulk-modal .swal2-cancel {
  margin: 0 !important;
  border-radius: 14px !important;
  padding: 12px 18px !important;
  font-size: 14px !important;
  font-weight: 700 !important;
  box-shadow: none !important;
}

.swal2-popup.vs-bulk-modal .swal2-confirm {
  background: linear-gradient(135deg, #2563eb, #1d4ed8) !important;
}

.swal2-popup.vs-bulk-modal .swal2-confirm:hover {
  transform: translateY(-1px);
  box-shadow: 0 12px 24px rgba(37, 99, 235, 0.22) !important;
}

.swal2-popup.vs-bulk-modal .swal2-cancel {
  background: #f8fafc !important;
  color: #334155 !important;
  border: 1px solid #e2e8f0 !important;
}

/* mobile */
@media (max-width: 640px) {
  .swal2-popup.vs-bulk-modal {
    width: calc(100% - 24px) !important;
    padding: 18px !important;
    border-radius: 20px !important;
  }

  .swal2-popup.vs-bulk-modal .swal2-title {
    font-size: 19px !important;
  }

  .vs-bulk-modal-card {
    padding: 12px;
    border-radius: 16px;
  }
}
 </style>
        <?php
        return ob_get_clean();
    }

    

    public static function render_dashboard() {

    /* ===============================
       1) NOT LOGGED IN
    ================================ */
    if (!is_user_logged_in()) {
        ob_start();
        self::render_shared_dashboard_css();
        ?>

    
      <div class="vs-landing">

    <!-- Hero Section -->
    <div class="vs-hero">
        <h1><?php echo esc_html__('Find Great Products on Our Marketplace', 'vendor-space'); ?></h1>
        <p>
            <?php echo esc_html__('Browse top sellers, discover new items, and shop with confidence.', 'vendor-space'); ?>
        </p>

        <div class="vs-hero-buttons">
            <a href="<?php echo esc_url(wc_get_page_permalink('myaccount')); ?>" class="vs-btn-primary">
                <?php echo esc_html__('Login', 'vendor-space'); ?>
            </a>


            <a href="<?php echo esc_url(home_url('/shop')); ?>" class="vs-btn-secondary">
                <?php echo esc_html__('Start Shopping', 'vendor-space'); ?>
            </a>
        </div>
    </div>


  <!-- Features -->
<div class="vs-features">

    <div class=" vs-feature-card reveal">
        <div class="vs-feature-icon">
            <i class="fas fa-th-large"></i>
        </div>
        <h3><?php echo esc_html__('Wide Selection', 'vendor-space'); ?></h3>
        <p><?php echo esc_html__('Discover products from top brands and trusted sellers.', 'vendor-space'); ?></p>
    </div>

    <div class=" vs-feature-card reveal">
        <div class="vs-feature-icon">
            <i class="fas fa-lock"></i>
        </div>
        <h3><?php echo esc_html__('Secure Checkout', 'vendor-space'); ?></h3>
        <p><?php echo esc_html__('Pay securely with multiple trusted payment options.', 'vendor-space'); ?></p>
    </div>

    <div class=" vs-feature-card reveal">
        <div class="vs-feature-icon">
            <i class="fas fa-truck"></i>
        </div>
        <h3><?php echo esc_html__('Fast Delivery', 'vendor-space'); ?></h3>
        <p><?php echo esc_html__('Get your orders quickly with reliable shipping.', 'vendor-space'); ?></p>
    </div>

    <div class=" vs-feature-card reveal">
        <div class="vs-feature-icon">
            <i class="fas fa-headset"></i>
        </div>
        <h3><?php echo esc_html__('24/7 Support', 'vendor-space'); ?></h3>
        <p><?php echo esc_html__('We’re here to help whenever you need us.', 'vendor-space'); ?></p>
    </div>

</div>
    <!-- How it works -->
    <div class="vs-steps">

        <h2><?php echo esc_html__('How It Works', 'vendor-space'); ?></h2>

        <div class="vs-steps-grid">

            <div class="vs-step  reveal">
                <span>1</span>
                <h4><?php echo esc_html__('Create an Account', 'vendor-space'); ?></h4>
                <p><?php echo esc_html__('Sign up quickly and start shopping immediately.', 'vendor-space'); ?></p>
            </div>

            <div class="vs-step reveal">
                <span>2</span>
                <h4><?php echo esc_html__('Add to Cart', 'vendor-space'); ?></h4>
                <p><?php echo esc_html__('Find great products and add them to your cart.', 'vendor-space'); ?></p>
            </div>

            <div class="vs-step reveal">
                <span>3</span>
                <h4><?php echo esc_html__('Checkout & Track', 'vendor-space'); ?></h4>
                <p><?php echo esc_html__('Complete your order and track delivery in real time.', 'vendor-space'); ?></p>
            </div>

        </div>

    </div>


    <!-- Final CTA -->
    <div class="vs-final-cta">
        <h2><?php echo esc_html__('Ready to Start Shopping?', 'vendor-space'); ?></h2>
        <a href="<?php echo esc_url(home_url('/shop')); ?>" class="vs-btn-primary">
            <?php echo esc_html__('Shop Now', 'vendor-space'); ?>
        </a>
    </div>

</div>
<script>
function reveal() {

let reveals = document.querySelectorAll(".reveal");

for (let i = 0; i < reveals.length; i++) {

let windowHeight = window.innerHeight;
let elementTop = reveals[i].getBoundingClientRect().top;
let elementVisible = 100;

if (elementTop < windowHeight - elementVisible) {
reveals[i].classList.add("active");
}

}
}

window.addEventListener("scroll", reveal);
reveal();
</script>
<style>
/* Landing page wrapper */
.vs-landing {
  width: 100%;
  max-width: 1100px;
  margin: 0 auto;
  padding: 40px 20px;
  box-sizing: border-box;
  font-family: Arial, sans-serif;
}

/* Hero */
.vs-hero {
  text-align: center;
  margin-bottom: 80px;
  padding: 80px 20px;
  border-radius: 20px;
  background: linear-gradient(135deg,#2563eb,#7c3aed);
  color: #fff;
  position: relative;
  overflow: hidden;
}

.vs-hero h1 {
  font-size: 42px;
  margin-bottom: 15px;
  line-height: 1.1;
}

.vs-hero p {
  color: #e0e7ff;
  font-size: 17px;
  max-width: 600px;
  margin: 0 auto;
}

.vs-hero-buttons {
  margin-top: 25px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 12px;
}

/* Buttons */
.vs-btn-primary,
.vs-btn-secondary {
  padding: 12px 25px;
  border-radius: 8px;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
}

.vs-btn-primary {
  background: #2563eb;
  color: #fff;
}

.vs-btn-primary:hover {
  background: #1e40af;
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.vs-btn-secondary {
  background: #f3f4f6;
  color: #333;
}

.vs-btn-secondary:hover {
  background: #e5e7eb;
  transform: translateY(-2px);
}

/* Features */
.vs-features {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 70px;
}

.vs-feature-card {
  position: relative;
  overflow: hidden;
  padding: 25px;
  border-radius: 16px;
  border: 1px solid #eef2ff;
  box-shadow: 0 5px 15px rgba(0,0,0,0.05);
  text-align: center;
  transition: all 0.3s ease;
}

.vs-feature-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg,#2563eb,#7c3aed);
  opacity: 0;
  transition: 0.3s;
}

.vs-feature-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 20px 40px rgba(0,0,0,0.08);
}

.vs-feature-card:hover::before {
  opacity: 1;
}

.vs-feature-icon {
  font-size: 38px;
  color: #2563eb;
  margin-bottom: 12px;
  transition: transform 0.3s ease;
}

.vs-feature-card:hover .vs-feature-icon {
  transform: scale(1.2) rotate(5deg);
}

/* How it works */
.vs-steps {
  text-align: center;
  margin-bottom: 60px;
   
}

.vs-steps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-top: 30px;
  }

.vs-step {
  padding: 25px;
  border-radius: 10px;
  border: 1px solid #eef2ff;
  box-shadow: 0 5px 15px rgba(0,0,0,0.05);
}

.vs-step span {
  display: inline-block;
  background: #2563eb;
  color: #fff;
  width: 35px;
  height: 35px;
  line-height: 35px;
  border-radius: 50%;
  margin-bottom: 10px;
}

/* Final CTA */
.vs-final-cta {
  text-align: center;
  background: #2563eb;
  color: #fff;
  padding: 40px;
  border-radius: 12px;
}

.vs-final-cta h2 {
  margin-bottom: 15px;
}

/* Animation */
@keyframes fadeUp {
  from { opacity: 0; transform: translateY(30px); }
  to { opacity: 1; transform: translateY(0); }
}

.vs-hero,
.vs-feature-card,
.vs-step,
.vs-final-cta {
  animation: fadeUp 0.8s ease forwards;
}

.vs-feature-card:nth-child(1) { animation-delay: 0.1s; }
.vs-feature-card:nth-child(2) { animation-delay: 0.2s; }
.vs-feature-card:nth-child(3) { animation-delay: 0.3s; }
.vs-feature-card:nth-child(4) { animation-delay: 0.4s; }

.vs-step:nth-child(1) { animation-delay: 0.2s; }
.vs-step:nth-child(2) { animation-delay: 0.4s; }
.vs-step:nth-child(3) { animation-delay: 0.6s; }

@keyframes float {
  0% { transform: translateY(0); }
  50% { transform: translateY(-25px); }
  100% { transform: translateY(0); }
}

.vs-hero::before {
  content: "";
  position: absolute;
  top: -100px;
  left: -100px;
  width: 300px;
  height: 300px;
  background: rgba(255,255,255,0.1);
  border-radius: 50%;
  animation: float 6s infinite ease-in-out;
}

.vs-hero::after {
  content: "";
  position: absolute;
  bottom: -120px;
  right: -120px;
  width: 350px;
  height: 350px;
  background: rgba(255,255,255,0.08);
  border-radius: 50%;
  animation: float 8s infinite ease-in-out;
}

/* Responsive tweaks */
@media (max-width: 768px) {
  .vs-landing { padding: 30px 16px; }
  .vs-hero { padding: 60px 18px; }
  .vs-hero h1 { font-size: 32px; }
  .vs-hero p { font-size: 15px; }
  .vs-hero-buttons { gap: 10px; }
  .vs-hero-buttons a { width: 100%; max-width: 320px; }
  .vs-final-cta { padding: 32px 20px; }
}
</style>


        <?php
        return ob_get_clean();
    }

    $user = wp_get_current_user();

    /* ===============================
       2) LOGGED IN BUT NOT SELLER
    ================================ */
    if (!current_user_can('edit_products') && !current_user_can('administrator')) {
        $vendor_status = get_user_meta(get_current_user_id(), 'vs_vendor_status', true);
        
        if ($vendor_status === 'pending') {
            ob_start();
            self::render_shared_dashboard_css();
            ?>
            <div class="vs-pending-approval-wrapper" style="max-width: 800px; margin: 100px auto; text-align: center; font-family: sans-serif; background: #fff; padding: 60px; border-radius: 24px; box-shadow: 0 20px 50px rgba(0,0,0,0.08); border: 1px solid #eef2ff;">
                <div style="width: 100px; height: 100px; background: #fffbeb; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 30px; color: #f59e0b; font-size: 40px;">
                    <i class="fas fa-user-clock"></i>
                </div>
                <h1 style="font-size: 32px; color: #0f172a; margin-bottom: 20px; font-weight: 800;"><?php echo esc_html__('Application Pending Approval', 'vendor-space'); ?></h1>
                <p style="font-size: 18px; color: #475569; line-height: 1.8; margin-bottom: 35px; max-width: 600px; margin-left: auto; margin-right: auto;">
                    <?php echo esc_html__('Great news! Your vendor application has been received. Our administrators are currently reviewing your information to ensure the best quality for our marketplace.', 'vendor-space'); ?>
                </p>
                <div style="background: #f8fafc; border-radius: 16px; padding: 25px; margin-bottom: 40px; display: inline-block; text-align: left; border: 1px solid #f1f5f9;">
                    <div style="display: flex; align-items: center; gap: 15px; color: #1e293b; font-weight: 600; margin-bottom: 8px;">
                        <i class="fas fa-envelope-open-text" style="color: #2563eb;"></i>
                        <span><?php echo esc_html__('What happens next?', 'vendor-space'); ?></span>
                    </div>
                    <p style="color: #64748b; margin: 0; font-size: 15px;">
                        <?php echo esc_html__('We will send a confirmation email to your registered address once a decision is made.', 'vendor-space'); ?>
                    </p>
                </div>
                <div>
                    <a href="<?php echo esc_url(home_url()); ?>" style="text-decoration: none; background: #2563eb; color: #fff; padding: 14px 30px; border-radius: 12px; font-weight: 600; display: inline-flex; align-items: center; gap: 10px; transition: all 0.3s; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);">
                        <i class="fas fa-home"></i> <?php echo esc_html__('Back to Marketplace', 'vendor-space'); ?>
                    </a>
                </div>
            </div>
            <?php
            return ob_get_clean();
        }

        if ($vendor_status === 'rejected') {
            $reason = get_user_meta(get_current_user_id(), 'vs_rejection_reason', true) ?: __('No specific reason provided.', 'vendor-space');
            ob_start();
            self::render_shared_dashboard_css();
            ?>
            <div class="vs-rejected-wrapper" style="max-width: 800px; margin: 100px auto; text-align: center; font-family: sans-serif; background: #fff; padding: 60px; border-radius: 24px; box-shadow: 0 20px 50px rgba(0,0,0,0.08); border: 1px solid #fef2f2;">
                <div style="width: 100px; height: 100px; background: #fef2f2; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 30px; color: #ef4444; font-size: 40px;">
                    <i class="fas fa-times-circle"></i>
                </div>
                <h1 style="font-size: 32px; color: #991b1b; margin-bottom: 20px; font-weight: 800;"><?php echo esc_html__('Application Declined', 'vendor-space'); ?></h1>
                <p style="font-size: 17px; color: #7f1d1d; margin-bottom: 30px;">
                    <?php echo esc_html__('We have reviewed your application and unfortunately we cannot approve it at this time.', 'vendor-space'); ?>
                </p>
                
                <div style="background: #fff; border: 2px dashed #fecaca; border-radius: 16px; padding: 30px; margin-bottom: 40px; text-align: left;">
                    <span style="display: block; font-size: 13px; font-weight: 700; color: #991b1b; text-transform: uppercase; margin-bottom: 12px; letter-spacing: 0.5px;">
                        <i class="fas fa-comment-dots"></i> <?php echo esc_html__('Feedback from Administrator:', 'vendor-space'); ?>
                    </span>
                    <p style="color: #4b5563; line-height: 1.6; font-style: italic; font-size: 16px; margin: 0;">
                        "<?php echo esc_html($reason); ?>"
                    </p>
                </div>

                <div style="display: flex; justify-content: center; gap: 15px;">
                    <button id="vs-retry-onboarding" style="border: none; background: #0f172a; color: #fff; padding: 14px 28px; border-radius: 12px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; transition: transform 0.2s;">
                        <i class="fas fa-redo"></i> <?php echo esc_html__('Update & Apply Again', 'vendor-space'); ?>
                    </button>
                </div>
                
                <script>
                document.getElementById('vs-retry-onboarding').addEventListener('click', function() {
                    this.disabled = true;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resetting...';
                    
                    jQuery.post(vs_vars.ajaxurl, {
                        action: 'vs_reset_onboarding',
                        security: vs_vars.nonce
                    }).done(function() {
                        window.location.reload();
                    });
                });
                </script>
            </div>
            <?php
            return ob_get_clean();
        }

        ob_start();
        ?>
        <div class="vs-onboard-wrapper">
            <div class="vs-onboard-card">
                <!-- Progress Header -->
                <div class="vs-onboard-header">
                    <div class="vs-onboard-progress">
                        <div class="vs-progress-bar" id="vs-progress-bar" style="width: 20%;"></div>
                    </div>
                    <div class="vs-onboard-steps-labels">
                        <div class="vs-step-label is-active" data-step="0">
                            <span class="vs-step-num"><i class="fas fa-rocket"></i></span>
                            <span class="vs-step-text"><?php echo esc_html__('Start', 'vendor-space'); ?></span>
                        </div>
                        <div class="vs-step-label" data-step="1">
                            <span class="vs-step-num"><i class="fas fa-store"></i></span>
                            <span class="vs-step-text"><?php echo esc_html__('Identity', 'vendor-space'); ?></span>
                        </div>
                        <div class="vs-step-label" data-step="2">
                            <span class="vs-step-num"><i class="fas fa-image"></i></span>
                            <span class="vs-step-text"><?php echo esc_html__('Branding', 'vendor-space'); ?></span>
                        </div>
                        <div class="vs-step-label" data-step="3">
                            <span class="vs-step-num"><i class="fas fa-share-alt"></i></span>
                            <span class="vs-step-text"><?php echo esc_html__('Social', 'vendor-space'); ?></span>
                        </div>
                        <div class="vs-step-label" data-step="4">
                            <span class="vs-step-num"><i class="fas fa-check-circle"></i></span>
                            <span class="vs-step-text"><?php echo esc_html__('Finish', 'vendor-space'); ?></span>
                        </div>
                    </div>
                </div>

                <div class="vs-onboard-panels">
                    <!-- Step 0: Initial Notice -->
                    <div class="vs-onboard-panel is-active" data-step="0">
                        <div class="vs-welcome-content">
                            <div class="vs-welcome-icon">
                                <i class="fas fa-store-alt"></i>
                            </div>
                            <h2><?php echo esc_html__('Join Our Marketplace!', 'vendor-space'); ?></h2>
                            <p><?php echo esc_html__('We\'re excited to help you start your business journey. Let\'s set up your showroom in just a few simple steps.', 'vendor-space'); ?></p>
                            
                            <div class="vs-onboard-alert-box">
                                <i class="fas fa-shield-alt"></i>
                                <span><?php echo esc_html__('This information helps us verify your brand and build trust with your future customers.', 'vendor-space'); ?></span>
                            </div>
                        </div>
                    </div>

                    <!-- Step 1: Store Setup -->
                    <div class="vs-onboard-panel" data-step="1">
                        <div class="vs-panel-header">
                            <h3><?php echo esc_html__('Shop Identity', 'vendor-space'); ?></h3>
                            <p><?php echo esc_html__('Tell us the basics about your business.', 'vendor-space'); ?></p>
                        </div>
                        
                        <div class="vs-onboard-form-grid">
                            <div class="vs-form-field">
                                <label for="vs-store-name"><?php echo esc_html__('Store Name', 'vendor-space'); ?> <span class="required">*</span></label>
                                <div class="vs-input-wrapper">
                                    <i class="fas fa-tag"></i>
                                    <input id="vs-store-name" type="text" placeholder="<?php echo esc_attr__('e.g. My Amazing Shop', 'vendor-space'); ?>" required>
                                </div>
                            </div>

                            <div class="vs-form-field">
                                <label for="vs-store-phone"><?php echo esc_html__('Phone Number', 'vendor-space'); ?></label>
                                <div class="vs-input-wrapper">
                                    <i class="fas fa-phone"></i>
                                    <input id="vs-store-phone" type="tel" placeholder="+1 (555) 000-0000">
                                </div>
                            </div>

                            <div class="vs-form-field full">
                                <label for="vs-store-location"><?php echo esc_html__(' Location', 'vendor-space'); ?> </label>
                                <div class="vs-input-wrapper">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <input id="vs-store-location" type="text" placeholder="<?php echo esc_attr__('City, Country', 'vendor-space'); ?>" >
                                </div>
                            </div>

                            <div class="vs-form-field full">
                                <label for="vs-store-desc"><?php echo esc_html__('About the Store', 'vendor-space'); ?></label>
                                <div class="vs-input-wrapper">
                                    <i class="fas fa-align-left"></i>
                                    <textarea id="vs-store-desc" rows="3" placeholder="<?php echo esc_attr__('What makes your products special?', 'vendor-space'); ?>"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Step 2: Branding -->
                    <div class="vs-onboard-panel" data-step="2">
                        <div class="vs-panel-header">
                            <h3><?php echo esc_html__('Visual Branding', 'vendor-space'); ?></h3>
                            <p><?php echo esc_html__('Add your Logo and a Banner photo to make your store stand out.', 'vendor-space'); ?></p>
                        </div>
                        
                        <div class="vs-branding-onboard-flex">
                            <div class="vs-branding-onboard-item">
                                <label><?php echo esc_html__('Store Logo', 'vendor-space'); ?></label>
                                <div class="vs-onboard-upload-box" id="logo-upload-box">
                                    <input type="file" id="vs-onboard-logo" accept="image/*" style="display:none;">
                                    <div class="vs-onboard-upload-placeholder">
                                        <i class="fas fa-cloud-upload-alt"></i>
                                        <span><?php echo esc_html__('Upload Logo', 'vendor-space'); ?></span>
                                    </div>
                                    <img src="" class="vs-onboard-upload-preview" style="display:none;">
                                </div>
                            </div>

                            <div class="vs-branding-onboard-item full-width">
                                <label><?php echo esc_html__('Store Banner', 'vendor-space'); ?></label>
                                <div class="vs-onboard-upload-box banner" id="banner-upload-box">
                                    <input type="file" id="vs-onboard-banner" accept="image/*" style="display:none;">
                                    <div class="vs-onboard-upload-placeholder">
                                        <i class="fas fa-image"></i>
                                        <span><?php echo esc_html__('Upload Banner', 'vendor-space'); ?></span>
                                    </div>
                                    <img src="" class="vs-onboard-upload-preview" style="display:none;">
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Step 3: Social Presence -->
                    <div class="vs-onboard-panel" data-step="3">
                        <div class="vs-panel-header">
                            <h3><?php echo esc_html__('Connect with Customers', 'vendor-space'); ?></h3>
                            <p><?php echo esc_html__('Link your social media profiles to increase your reach.', 'vendor-space'); ?></p>
                        </div>
                        
                        <div class="vs-onboard-social-grid">
                            <div class="vs-form-field">
                                <label><i class="fab fa-facebook"></i> Facebook</label>
                                <input id="vs-soc-fb" type="url" placeholder="https://facebook.com/your-page">
                            </div>
                            <div class="vs-form-field">
                                <label><i class="fab fa-instagram"></i> Instagram</label>
                                <input id="vs-soc-ig" type="url" placeholder="https://instagram.com/your-username">
                            </div>
                            <div class="vs-form-field">
                                <label><i class="fab fa-twitter"></i> X / Twitter</label>
                                <input id="vs-soc-x" type="url" placeholder="https://x.com/your-username">
                            </div>
                            <div class="vs-form-field">
                                <label><i class="fab fa-linkedin"></i> LinkedIn</label>
                                <input id="vs-soc-li" type="url" placeholder="https://linkedin.com/your-name">
                            </div>

                            <div class="vs-form-field">
                                <label><i class="fab fa-youtube"></i> Youtube</label>
                                <input id="vs-soc-yt" type="url" placeholder="https://youtube.com/your-name">
                            </div>
                            
                        </div>
                    </div>

                    <!-- Step 4: Celebration -->
                    <div class="vs-onboard-panel" data-step="4">
                        <div class="vs-success-state">
                            <div class="vs-confetti-vandal">
                                <div class="vs-checkmark">
                                    <i class="fas fa-check"></i>
                                </div>
                            </div>
                            <h3><?php echo esc_html__('Your Shop is Ready!', 'vendor-space'); ?></h3>
                            <p><?php echo esc_html__('You are now a verified vendor. It\'s time to list your first product and start selling.', 'vendor-space'); ?></p>
                            <p class="vs-redirect-msg"><?php echo esc_html__('Preparing your personal dashboard...', 'vendor-space'); ?></p>
                            <div class="vs-loading-spinner"></div>
                        </div>
                    </div>
                </div>

                <!-- Footer Actions -->
                <div class="vs-onboard-footer">
                    <button type="button" class="vs-onboard-prev-btn" style="visibility: hidden;">
                        <i class="fas fa-arrow-left"></i> <?php echo esc_html__('Back', 'vendor-space'); ?>
                    </button>
                    <button type="button" class="vs-onboard-next-btn">
                        <span><?php echo esc_html__('Continue', 'vendor-space'); ?></span> <i class="fas fa-arrow-right"></i>
                    </button>
                </div>
            </div>
        </div>

        <script>
        jQuery(function($) {
            let currentStep = 0;
            const totalSteps = 5;
            const $panels = $('.vs-onboard-panel');
            const $labels = $('.vs-step-label');
            const $bar = $('#vs-progress-bar');
            const $nextBtn = $('.vs-onboard-next-btn');
            const $prevBtn = $('.vs-onboard-prev-btn');

            function updateStep(step) {
                $panels.removeClass('is-active');
                $labels.removeClass('is-active').removeClass('is-done');
                
                $panels.eq(step).addClass('is-active');
                
                $labels.each(function(index) {
                    if (index < step) $(this).addClass('is-done');
                    if (index === step) $(this).addClass('is-active');
                });

                $bar.css('width', ((step + 1) / totalSteps * 100) + '%');
                $prevBtn.css('visibility', step === 0 || step === totalSteps - 1 ? 'hidden' : 'visible');
                
                if (step === totalSteps - 1) {
                    $nextBtn.hide();
                } else if (step === totalSteps - 2) {
                    $nextBtn.find('span').text('<?php echo esc_js(__('Launch My Store', 'vendor-space')); ?>');
                    $nextBtn.find('i').attr('class', 'fas fa-rocket');
                } else {
                    $nextBtn.find('span').text('<?php echo esc_js(__('Continue', 'vendor-space')); ?>');
                    $nextBtn.find('i').attr('class', 'fas fa-arrow-right');
                }
            }

            // Image Preview logic
            function handleFileUpload(boxId, inputId) {
                const $box = $('#' + boxId);
                const $input = $('#' + inputId);
                const $preview = $box.find('.vs-onboard-upload-preview');
                const $placeholder = $box.find('.vs-onboard-upload-placeholder');

                // Prevent bubbling when clicking the input itself
                $input.on('click', (e) => e.stopPropagation());
                
                $box.on('click', (e) => {
                    e.preventDefault();
                    $input.trigger('click');
                });

                $input.on('change', function() {
                    const file = this.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = e => {
                            $preview.attr('src', e.target.result).show();
                            $placeholder.hide();
                            $box.addClass('has-image');
                        };
                        reader.readAsDataURL(file);
                    }
                });
            }

            handleFileUpload('logo-upload-box', 'vs-onboard-logo');
            handleFileUpload('banner-upload-box', 'vs-onboard-banner');

            $nextBtn.on('click', function() {
                if (currentStep === 1) {
                    // Check validation for Step 1
                    const storeName = $('#vs-store-name').val().trim();
                    const storeLocation = $('#vs-store-location').val().trim();
                    if (!storeName || !storeLocation) {
                        Swal.fire('<?php echo esc_js(__('Wait!', 'vendor-space')); ?>', '<?php echo esc_js(__('Store name and location are required.', 'vendor-space')); ?>', 'warning');
                        return;
                    }
                }

                if (currentStep === totalSteps - 2) {
                    // Final Submit Phase
                    const formData = new FormData();
                    formData.append('action', 'vs_become_vendor');
                    formData.append('security', vs_vars.nonce);
                    formData.append('store_name', $('#vs-store-name').val().trim());
                    formData.append('store_location', $('#vs-store-location').val().trim());
                    formData.append('store_phone', $('#vs-store-phone').val().trim());
                    formData.append('store_desc', $('#vs-store-desc').val().trim());
                    
                    // Social links
                    formData.append('social_facebook', $('#vs-soc-fb').val().trim());
                    formData.append('social_instagram', $('#vs-soc-ig').val().trim());
                    formData.append('social_x', $('#vs-soc-x').val().trim());
                    formData.append('social_linkedin', $('#vs-soc-li').val().trim());
                    formData.append('social_youtube', $('#vs-soc-yt').val().trim());

                    // Files
                    const logoFile = $('#vs-onboard-logo')[0].files[0];
                    const bannerFile = $('#vs-onboard-banner')[0].files[0];
                    if (logoFile) formData.append('store_logo', logoFile);
                    if (bannerFile) formData.append('store_banner', bannerFile);

                    $nextBtn.prop('disabled', true).html('<i class="fas fa-circle-notch fa-spin"></i>');

                    $.ajax({
                        url: vs_vars.ajaxurl,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(res) {
                            if (res && res.success) {
                                currentStep = totalSteps - 1;
                                updateStep(currentStep);
                                setTimeout(() => {
                                    window.location.reload();
                                }, 2500);
                            } else {
                                Swal.fire('Error', res.data || 'Process failed', 'error');
                                $nextBtn.prop('disabled', false).html('<span><?php echo esc_js(__('Launch My Store', 'vendor-space')); ?></span> <i class="fas fa-rocket"></i>');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Connection failed', 'error');
                            $nextBtn.prop('disabled', false).html('<span><?php echo esc_js(__('Launch My Store', 'vendor-space')); ?></span> <i class="fas fa-rocket"></i>');
                        }
                    });
                } else {
                    currentStep++;
                    updateStep(currentStep);
                }
            });

            $prevBtn.on('click', function() {
                if (currentStep > 0) {
                    currentStep--;
                    updateStep(currentStep);
                }
            });
        });
        </script>

        <style>
        .vs-onboard-wrapper {
            width: 100%;
            min-height: 400px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        }

        .vs-onboard-card {
            background: #fff;
            max-width: 600px;
            width: 100%;
            border-radius: 24px;
            box-shadow: 0 20px 50px rgba(0,0,0,0.08);
            overflow: hidden;
            border: 1px solid #f1f5f9;
        }

        .vs-onboard-header {
            background: #f8fafc;
            padding: 30px 40px;
            border-bottom: 1px solid #f1f5f9;
        }

        .vs-onboard-progress {
            height: 6px;
            background: #e2e8f0;
            border-radius: 10px;
            margin-bottom: 25px;
            overflow: hidden;
        }

        .vs-progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #4f46e5, #0ea5e9);
            transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .vs-onboard-steps-labels {
            display: flex;
            justify-content: space-between;
        }

        .vs-step-label {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            color: #94a3b8;
            transition: all 0.3s;
        }

        .vs-step-label.is-active {
            color: #4f46e5;
            font-weight: 700;
        }

        .vs-step-label.is-done {
            color: #10b981;
        }

        .vs-step-num {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid currentColor;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }

        .vs-step-text {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .vs-onboard-panels {
            padding: 40px;
            min-height: 300px;
        }

        .vs-onboard-panel {
            display: none;
            animation: vsFadeIn 0.5s ease-out;
        }

        .vs-onboard-panel.is-active {
            display: block;
        }

        @keyframes vsFadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .vs-welcome-content {
            text-align: center;
        }

        .vs-welcome-icon {
            font-size: 48px;
            color: #4f46e5;
            margin-bottom: 20px;
        }

        .vs-welcome-content h2 {
            font-size: 28px;
            color: #0f172a;
            margin-bottom: 12px;
        }

        .vs-welcome-content p {
            color: #64748b;
            line-height: 1.6;
            margin-bottom: 25px;
        }

        .vs-onboard-alert-box {
            background: #fffbeb;
            border: 1px solid #fef3c7;
            padding: 15px;
            border-radius: 12px;
            color: #92400e;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
            text-align: left;
        }

        .vs-panel-header h3 {
            font-size: 22px;
            color: #0f172a;
            margin-bottom: 8px;
        }

        .vs-panel-header p {
            color: #64748b;
            font-size: 14px;
            margin-bottom: 25px;
        }

        .vs-onboard-form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .vs-form-field.full {
            grid-column: span 2;
        }

        .vs-form-field label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 6px;
        }

        .vs-form-field .required {
            color: #ef4444;
        }

        .vs-input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
        }

        .vs-input-wrapper i {
            position: absolute;
            left: 14px;
            color: #94a3b8;
        }

        .vs-input-wrapper input,
        .vs-input-wrapper textarea {
            width: 100%;
            padding: 12px 12px 12px 40px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.2s;
            outline: none;
        }

        .vs-input-wrapper input:focus,
        .vs-input-wrapper textarea:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }

        .vs-onboard-footer {
            padding: 25px 40px;
            background: #fff;
            border-top: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .vs-onboard-prev-btn {
            background: transparent;
            border: none;
            color: #64748b;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }

        .vs-onboard-next-btn {
            background: #4f46e5;
            color: #fff;
            border: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
            transition: all 0.2s;
            font-size: 14px;
        }

        .vs-onboard-next-btn:hover {
            background: #4338ca;
            transform: translateY(-1px);
            box-shadow: 0 6px 15px rgba(79, 70, 229, 0.35);
        }

        .vs-onboard-next-btn:active {
            transform: translateY(0);
        }

        .vs-success-state {
            text-align: center;
            padding: 20px 0;
        }

        .vs-checkmark {
            width: 80px;
            height: 80px;
            background: #10b981;
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 40px;
            margin: 0 auto 20px;
            box-shadow: 0 10px 20px rgba(16, 185, 129, 0.2);
            animation: vsPopIn 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        /* ===== New Onboarding Styles ===== */
        .vs-branding-onboard-flex {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .vs-branding-onboard-item label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: #334155;
            margin-bottom: 8px;
        }
        .vs-onboard-upload-box {
            border: 2px dashed #cbd5e1;
            border-radius: 16px;
            padding: 24px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            background: #f8fafc;
            min-height: 140px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }
        .vs-onboard-upload-box:hover {
            border-color: #4f46e5;
            background: #f0f9ff;
            transform: translateY(-2px);
        }
        .vs-onboard-upload-box.banner {
            min-height: 180px;
        }
        .vs-onboard-upload-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
            color: #64748b;
        }
        .vs-onboard-upload-placeholder i {
            font-size: 32px;
            color: #4f46e5;
            opacity: 0.8;
        }
        .vs-onboard-upload-preview {
            max-width: 100%;
            max-height: 200px;
            border-radius: 12px;
            object-fit: cover;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .vs-onboard-social-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .vs-onboard-social-grid input {
            width: 100%;
            padding: 12px 16px;
            border: 1.5px solid #e2e8f0;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.2s;
            outline: none;
            background: #fff;
        }
        .vs-onboard-social-grid input:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1);
        }
        .vs-onboard-social-grid .vs-form-field label {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .vs-onboard-social-grid .fa-facebook { color: #1877F2; }
        .vs-onboard-social-grid .fa-instagram { color: #E4405F; }
        .vs-onboard-social-grid .fa-twitter { color: #1DA1F2; }
        .vs-onboard-social-grid .fa-linkedin { color: #0A66C2; }
        .vs-onboard-social-grid .fa-youtube { color: #FF0000; }

        .vs-onboard-upload-box.has-image {
            border-style: solid;
            border-color: #10b981;
            background: #f0fdf4;
        }

        @keyframes vsPopIn {
            0% { transform: scale(0); }
            80% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        .vs-success-state h3 {
            font-size: 26px;
            color: #0f172a;
            margin-bottom: 10px;
        }

        .vs-success-state p {
            color: #64748b;
            margin-bottom: 5px;
        }

        .vs-loading-spinner {
            width: 24px;
            height: 24px;
            border: 3px solid rgba(79,70,229,0.1);
            border-top: 3px solid #4f46e5;
            border-radius: 50%;
            margin: 20px auto 0;
            animation: vsSpin 1s linear infinite;
        }

        @keyframes vsSpin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 640px) {
            .vs-onboard-form-grid {
                grid-template-columns: 1fr;
            }
            .vs-form-field.full {
                grid-column: span 1;
            }
            .vs-onboard-header, .vs-onboard-panels, .vs-onboard-footer {
                padding: 20px;
            }
            .vs-welcome-content h2 { font-size: 22px; }
            .vs-step-text { display: none; }
        }
        </style>
        <?php
        return ob_get_clean();
    }

        ob_start();
        self::render_shared_dashboard_css();
        ?>

        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>



        <div class="vs-dashboard" style="display:flex;">
           <!-- Sidebar Toggle Button (Mobile & Desktop) -->
<div class="vs-sidebar">

    <!-- Toggle inside sidebar -->
    <div class="vs-sidebar-header">
        <button type="button" class="vs-sidebar-toggle" title="<?php echo esc_attr__('Toggle menu', 'vendor-space'); ?>">
            <i class="fas fa-bars"></i>
        </button>
    </div>

<?php 
$pending_requests_count = class_exists('VS_Admin_Moderation') ? VS_Admin_Moderation::get_pending_count() : 0;
$pending_cat_count      = class_exists('VS_Categories') ? VS_Categories::get_pending_count() : 0;
$pending_vendors_count  = class_exists('VS_Admin_Moderation') ? VS_Admin_Moderation::get_pending_vendors_count() : 0;
?>

<ul class="vs-sidebar-menu">
    <li>
        <a href="#" class="vs-tab-link active" data-tab="profile">
            <i class="fas fa-user"></i>
            <span class="vs-label"><?php echo esc_html__('Profile', 'vendor-space'); ?></span>
        </a>
    </li>

    
    <li class="vs-has-submenu">
        <a href="#" class="vs-parent-link" style="position:relative;">
            <i class="fas fa-box"></i>
            <span class="vs-label"><?php echo esc_html__('Products', 'vendor-space'); ?></span>
            <i class="fas fa-chevron-down vs-arrow"></i>
            <?php if (($pending_requests_count > 0 || $pending_cat_count > 0) && current_user_can('administrator')): ?>
    <span id="vs-products-badge" style = " position:absolute;top:4px;right:10px;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:#dc2626;color:#fff;font-size:10px;font-weight:700;line-height:18px;text-align:center; ">
        <?php echo esc_html($pending_requests_count + $pending_cat_count); ?>
    </span>
<?php endif; ?>
        </a>

        <ul class="vs-submenu">
            <li>
                <a href="#" class="vs-tab-link" data-tab="my-products">
                    <i class="fas fa-list"></i>
                    <span class="vs-label"><?php echo esc_html__('All Products', 'vendor-space'); ?></span>
                </a>
            </li>

            <li>
                <a href="#" id="add-product-btn-menu" class="vs-tab-link">
                    <i class="fas fa-plus-circle"></i>
                    <span class="vs-label"><?php echo esc_html__('Add Product', 'vendor-space'); ?></span>
                </a>
            </li>

            <li>
                <a href="#" class="vs-tab-link" data-tab="product-categories" style="position:relative;">
                    <i class="fas fa-tags"></i>
                    <span class="vs-label"><?php echo esc_html__('Categories', 'vendor-space'); ?></span>
                    <?php if ($pending_cat_count > 0 && current_user_can('administrator')): ?>
                        <span id="vs-category-requests-badge" style="position:absolute;top:4px;right:10px;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:#dc2626;color:#fff;font-size:10px;font-weight:700;line-height:18px;text-align:center;">
                            <?php echo esc_html($pending_cat_count); ?>
                        </span>
                    <?php endif; ?>
                </a>
            </li>

            <li>
                <a href="#" class="vs-tab-link" data-tab="restore-products">
                    <i class="fas fa-trash-restore"></i>
                    <span class="vs-label"><?php echo esc_html__('Restore', 'vendor-space'); ?></span>
                </a>
            </li>

            <?php if (current_user_can('administrator')): ?>
           <li>
    <a href="#" class="vs-tab-link" data-tab="publish-requests">
        
        <!-- ICON + BADGE -->
        <span style="position:relative; display:inline-flex; align-items:center; justify-content:center; min-width:20px;">
            <i class="fas fa-check-circle"></i>

            <?php if ($pending_requests_count > 0): ?>
                <span id="vs-publish-requests-badge"
                      style="position:absolute; top:-7px; right:-9px; min-width:18px; height:18px; padding:0 5px; border-radius:999px; background:#dc2626; color:#fff; font-size:10px; font-weight:700; line-height:18px; text-align:center;">
                    <?php echo esc_html($pending_requests_count); ?>
                </span>
            <?php endif; ?>
        </span>

        <span class="vs-label"><?php echo esc_html__('Publication Requests', 'vendor-space'); ?></span>
    </a>
</li>
            <?php else: ?>
            <?php 
                $vendor_pending_count = class_exists('VS_Admin_Moderation') ? VS_Admin_Moderation::get_vendor_pending_count(get_current_user_id()) : 0;
            ?>
            <li>
                <a href="#" class="vs-tab-link" data-tab="vendor-assign-requests" style="position:relative;">
                    <i class="fas fa-check-circle"></i>
                    <span class="vs-label"><?php echo esc_html__('Assign Requests', 'vendor-space'); ?></span>
                    <?php if ($vendor_pending_count > 0): ?>
                        <span id="vs-vendor-assign-requests-badge" style="position:absolute;top:4px;right:10px;min-width:18px;height:18px;padding:0 5px;border-radius:999px;background:#dc2626;color:#fff;font-size:10px;font-weight:700;line-height:18px;text-align:center;">
                            <?php echo esc_html($vendor_pending_count); ?>
                        </span>
                    <?php endif; ?>
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </li>
<?php 
if ( function_exists('is_plugin_active') && is_plugin_active('vendor space pro/vendor-space.php') ) :
if ( class_exists('VS_Pro_LiveChat') && VS_Modules::is_active('live_chat')  ) :
?>

    <li>
        <a href="#" class="vs-tab-link" data-tab="notifications">
            <span style="position:relative; display:inline-flex; align-items:center; justify-content:center; min-width:20px;">
                <i class="fas fa-comments"></i>
                <span id="vs-sidebar-notif-badge" style="display:none; position:absolute; top:-7px; right:-9px; min-width:18px; height:18px; padding:0 5px; border-radius:999px; background:#dc2626; color:#fff; font-size:10px; font-weight:700; line-height:18px; text-align:center;">0</span>
            </span>
            <span class="vs-label"><?php echo esc_html__('Messages', 'vendor-space'); ?></span>
        </a>
        
    </li>
<?php endif;endif;?>
    <li>
        <a href="#" class="vs-tab-link" data-tab="my-orders">
            <i class="fas fa-shopping-cart"></i>
            <span class="vs-label"><?php echo esc_html__('Orders', 'vendor-space'); ?></span>
        </a>
    </li>
   

           


    <li>
        <a href="#" class="vs-tab-link" data-tab="best-clients">
            <i class="fas fa-crown"></i>
            <span class="vs-label"><?php echo esc_html__('Best Clients', 'vendor-space'); ?></span>
        </a>
    </li>

    <li>
        <a href="#" class="vs-tab-link" data-tab="wallet">
            <i class="fas fa-wallet"></i>
            <span class="vs-label"><?php echo esc_html__('Wallet', 'vendor-space'); ?></span>
        </a>
    </li>

    <?php if ( class_exists('VS_Ads') && VS_Modules::is_active('vendor_ads') ) : ?>
     <li>
        <a href="#" class="vs-tab-link" data-tab="my-ads">
            <i class="fas fa-bullhorn"></i>
            <span class="vs-label">
                <?php echo current_user_can('administrator') ? esc_html__('Request Ads', 'vendor-space') : esc_html__('My Ads', 'vendor-space'); ?>
            </span>
        </a>
    </li>
    <?php endif; ?>
    <li class="vs-has-submenu">
        <a href="#" class="vs-parent-link">
            <i class="fas fa-chart-line"></i>
            <span class="vs-label"><?php echo esc_html__('Report', 'vendor-space'); ?></span>
            <i class="fas fa-chevron-down vs-arrow"></i>
        </a>
        <ul class="vs-submenu">
            <?php if ( class_exists('VS_Modules') && VS_Modules::is_active('vendor_ads') ) : ?><li>
                <a href="#" class="vs-tab-link" data-tab="ads-report">
                    <i class="fas fa-bullhorn"></i>
                    <span class="vs-label"><?php echo esc_html__('Ads', 'vendor-space'); ?></span>
                </a>
            </li><?php endif; ?>
            <?php if (current_user_can('administrator')): ?>
            <li>
                <a href="#" class="vs-tab-link" data-tab="reports-dashboard">
                    <i class="fas fa-chart-pie"></i>
                    <span class="vs-label"><?php echo esc_html__('Orders', 'vendor-space'); ?></span>
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </li>

   <?php if (current_user_can('administrator')): ?>
<li class="vs-has-submenu">
    <a href="#" class="vs-parent-link">
        
        <!-- ICON + BADGE نفس style -->
        <span style="position:relative; display:inline-flex; align-items:center; justify-content:center; min-width:20px;">
            <i class="fas fa-users"></i>

            <?php if ($pending_vendors_count > 0): ?>
                <span id="vs-users-badge"
                      style="position:absolute; top:-7px; right:-9px; min-width:18px; height:18px; padding:0 5px; border-radius:999px; background:#dc2626; color:#fff; font-size:10px; font-weight:700; line-height:18px; text-align:center;">
                    <?php echo esc_html($pending_vendors_count); ?>
                </span>
            <?php endif; ?>
        </span>

        <span class="vs-label"><?php echo esc_html__('Users', 'vendor-space'); ?></span>
        <i class="fas fa-chevron-down vs-arrow"></i>
    </a>

    <ul class="vs-submenu">
        <li>
            <a href="#" class="vs-tab-link" data-tab="vendors-management" data-filter="all_users">
                <i class="fas fa-list"></i>
                <span class="vs-label"><?php echo esc_html__('All Users', 'vendor-space'); ?></span>
            </a>
        </li>

        <li>
            <a href="#" class="vs-tab-link" data-tab="vendors-management" data-filter="vendors">
                <i class="fas fa-store"></i>
                <span class="vs-label"><?php echo esc_html__('Vendors', 'vendor-space'); ?></span>
            </a>
        </li>

        <li>
            <a href="#" class="vs-tab-link" data-tab="vendor-requests">
                
                <span style="position:relative; display:inline-flex; align-items:center; justify-content:center; min-width:20px;">
                    <i class="fas fa-user-plus"></i>

                    <?php if ($pending_vendors_count > 0): ?>
                        <span id="vs-vendor-requests-badge"
                              style="position:absolute; top:-7px; right:-9px; min-width:18px; height:18px; padding:0 5px; border-radius:999px; background:#dc2626; color:#fff; font-size:10px; font-weight:700; line-height:18px; text-align:center;">
                            <?php echo esc_html($pending_vendors_count); ?>
                        </span>
                    <?php endif; ?>
                </span>

                <span class="vs-label"><?php echo esc_html__('Account Requests', 'vendor-space'); ?></span>
            </a>
        </li>
    </ul>
</li>

 <?php if (current_user_can('administrator')): ?>

    <li>
        <a href="#" class="vs-tab-link" data-tab="modules">
            <i class="fas fa-puzzle-piece"></i>
            <span class="vs-label"><?php echo esc_html__('modules', 'vendor-space'); ?></span>
        </a>
    </li>
    <?php endif; ?>

    <li>
        <a href="#" class="vs-tab-link" data-tab="admin-settings">
            <i class="fas fa-cog"></i>
            <span class="vs-label"><?php echo esc_html__('Settings', 'vendor-space'); ?></span>
        </a>
    </li>
    <?php endif; ?>
</ul>

<div class="vs-sidebar-footer">
    <?php self::render_language_switcher(); ?>

    <a href="<?php echo esc_url(wp_logout_url()); ?>" class="vs-logout">
        <i class="fas fa-sign-out-alt"></i>
        <span class="vs-label"><?php echo esc_html__('Logout', 'vendor-space'); ?></span>
    </a>
</div>

</div>


<style>
/* Sidebar */
.vs-sidebar {
    width: 20%;
    background: #0f172a;
    border-radius: 14px;
    padding: 10px;
    display: inline-flex;
    flex-direction: column;
    gap: 8px;
    transition: width .3s ease;
    height: 100%;
}
/* ===== Responsive ===== */
@media(max-width:768px) {
    .vs-dashboard {
        flex-direction: column;
    }

    .vs-sidebar {
        width: 95% !important;
        margin-bottom: 15px;
    }

    .vs-products-table {
        width: 100%;
        table-layout: fixed;
    }

    .vs-products-table th:nth-child(2),
    .vs-products-table td:nth-child(2),
    .vs-products-table th:nth-child(4),
    .vs-products-table td:nth-child(4),
    .vs-products-table th:nth-child(5),
    .vs-products-table td:nth-child(5),
    .vs-products-table th:nth-child(6),
    .vs-products-table td:nth-child(6) {
        display: none;
    }

    .vs-products-table .vs-action-buttons {
        flex-direction: column !important;
        align-items: stretch !important;
        gap: 6px !important;
    }

.vs-products-table .vs-action-buttons button,
.vs-products-table .vs-action-buttons .vs-view-btn {
    width: 100%;
    display: block;          /* يجعل العرض فعلي 100% */
    box-sizing: border-box;  /* يمنع تغيّر الحجم بسبب padding */
    text-align: center;
    justify-content: center;
    margin: 0;               /* يمنع تغيّر العرض بسبب المسافات */
}
}
/* Header */
.vs-sidebar-header {
    display: flex;
    justify-content: flex-end;
}

/* Toggle */
.vs-sidebar-toggle {
    background: transparent;
    border: none;
    color: #cbd5f5;
    font-size: 18px;
    cursor: pointer;
    padding: 6px 8px;
    border-radius: 8px;
}

/* Menu */
.vs-sidebar-menu {
    list-style: none;
    padding: 0;
    margin: 0;
}

.vs-sidebar a {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 11px 14px;
    color: #cbd5f5;
    text-decoration: none;
    border-radius: 10px;
    transition: background .3s ease;
}

.vs-sidebar a:hover,
.vs-sidebar a.active {
    background: #2563eb;
    color: #fff;
}

/* Icons */
.vs-sidebar i {
    min-width: 20px;
    text-align: center;
}

/* Footer */
.vs-sidebar-footer {
    border-top: 1px solid rgba(255,255,255,.08);
    padding-top: 8px;
    display: grid;
    gap: 10px;
}

.vs-language-switcher {
    display: grid;
    gap: 6px;
}

.vs-language-label {
    color: rgba(255,255,255,.8);
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
}

.vs-language-select {
    width: 100%;
    background: rgba(255,255,255,.08);
    color: #fff;
    border: 1px solid rgba(255,255,255,.12);
    border-radius: 10px;
    padding: 10px 12px;
}

.vs-language-select option {
    color: #111827;
}

/* Logout */
.vs-logout {
    background: rgba(239,68,68,.12);
    color: #f87171;
}

/* =======================
   COLLAPSED STATE
======================= */

.vs-sidebar.collapsed {
    width: 68px;     
}

.vs-sidebar.collapsed .vs-label {
    display: none;             /* Ø¥Ø®ÙØ§Ø¡ Ø§Ù„Ù†Øµ */
}
.vs-label{
    color:#fff;
}

.vs-sidebar.collapsed a {
    justify-content: center;   /* ØªÙˆØ³ÙŠØ· Ø§Ù„Ø£ÙŠÙ‚ÙˆÙ†Ø§Øª */
    padding: 12px 0;
}

.vs-sidebar.collapsed .vs-sidebar-header {
    justify-content: center;
}
.vs-sidebar.collapsed .vs-language-label,
.vs-sidebar.collapsed .vs-language-select {
    display: none;
}

/* Mobile: remove black empty space when sidebar is collapsed */
@media (max-width: 768px) {
    .vs-sidebar.collapsed {
        width: 100% !important;
        min-height: 0 !important;
        height: auto !important;
        padding-top: 8px !important;
        padding-bottom: 8px !important;
    }
    .vs-sidebar.collapsed .vs-sidebar-menu,
    .vs-sidebar.collapsed .vs-sidebar-footer,
    .vs-sidebar.collapsed .vs-sidebar-header ~ * {
        display: none !important;
    }
    .vs-sidebar.collapsed .vs-sidebar-header {
        justify-content: flex-end;
    }
}

/* Submenu */
.vs-has-submenu .vs-submenu {
    list-style: none;
    padding-left: 15px;
    margin-top: 5px;
    display: none;
}

.vs-has-submenu .vs-submenu li a {
    font-size: 14px;
    padding: 8px 12px;
    background: rgba(255,255,255,0.03);
    border-radius: 8px;
}

.vs-has-submenu .vs-submenu li a:hover {
    background: #1e40af;
}

/* Arrow rotation */
.vs-arrow {
    margin-left: auto;
    transition: transform .3s ease;
}

.vs-has-submenu.open .vs-arrow {
    transform: rotate(180deg);
}

</style>

<script>
    
jQuery(function ($) {
    // Toggle Submenu
$(document).on('click', '.vs-parent-link', function (e) {
    e.preventDefault();

    const parent = $(this).closest('.vs-has-submenu');
    parent.toggleClass('open');
    parent.find('.vs-submenu').slideToggle(200);
    
});
    /* =============================
       Tab Active System
    ============================= */
    $(document).on('click', '.vs-tab-link', function (e) {
        e.preventDefault();

        // Get tab name
        const tab = $(this).data('tab');
        if (!tab) return;

        // Remove all active
        $('.vs-tab-link').removeClass('active');
        $('.vs-parent-link').removeClass('active');

        // Add active to clicked
        $(this).addClass('active');

        // Show tab content
        $('.vs-tab').hide();
        $('#tab-' + tab).show();

        // If inside submenu -> activate parent
        const parentMenu = $(this).closest('.vs-has-submenu');
        if (parentMenu.length) {
            parentMenu.addClass('open');
            parentMenu.children('.vs-submenu').show();
            parentMenu.children('.vs-parent-link').addClass('active');
        }
    });
    
    // Sidebar collapse toggle (show icons only when collapsed)
    $(document).on('click', '.vs-sidebar-toggle', function () {
        $(this).closest('.vs-sidebar').toggleClass('collapsed');
    });

    $(document).on('change', '#vs-language-switcher', function () {
        const locale = String($(this).val() || '').trim();
        if (!locale) {
            return;
        }

        $.post(vs_vars.ajaxurl, {
            action: 'vs_set_locale',
            locale: locale,
            security: vs_vars.nonce
        }).done(function (response) {
            if (response && response.success) {
                window.location.reload();
                return;
            }

            const message = response && response.data ? response.data : '<?php echo esc_js(__('Invalid language.', 'vendor-space')); ?>';
            if (typeof Swal === 'undefined') {
                window.alert(message);
                return;
            }
            Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', message, 'error');
        }).fail(function () {
            if (typeof Swal === 'undefined') {
                window.alert('<?php echo esc_js(__('Connection failed', 'vendor-space')); ?>');
                return;
            }
            Swal.fire('<?php echo esc_js(__('Error', 'vendor-space')); ?>', '<?php echo esc_js(__('Connection failed', 'vendor-space')); ?>', 'error');
        });
    });

    // Logout confirmation with SweetAlert
    $(document).on('click', '.vs-logout', function (e) {
        e.preventDefault();

        const logoutUrl = $(this).attr('href');
        if (!logoutUrl) {
            return;
        }

        if (typeof Swal === 'undefined') {
            if (window.confirm('<?php echo esc_js(__('Are you sure you want to log out?', 'vendor-space')); ?>')) {
                window.location.href = logoutUrl;
            }
            return;
        }

        Swal.fire({
            title: '<?php echo esc_js(__('Logout?', 'vendor-space')); ?>',
            text: '<?php echo esc_js(__('Do you want to log out now?', 'vendor-space')); ?>',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '<?php echo esc_js(__('Yes, log out', 'vendor-space')); ?>',
            cancelButtonText: '<?php echo esc_js(__('Cancel', 'vendor-space')); ?>',
            confirmButtonColor: '#ef4444'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = logoutUrl;
            }
        });
    });
});

</script>

            <!-- Content -->
            <div class="vs-content" style="flex:1;max-width:1500px;">
                <?php
                echo self::render_products_tab_content($user);
                echo VS_Categories::render($user);
                
                // Orders are separated in includes/class-vs-orders.php
                require_once VS_PATH . 'includes/class-vs-orders.php';
                require_once VS_PATH . 'includes/class-vs-wallet.php';
                $wallet = new VS_Wallet();

echo $wallet->render_wallet_stats();
                if ( function_exists('is_plugin_active') && is_plugin_active('vendor space pro/vendor-space.php') ) :
                if ( class_exists('VS_Modules') && VS_Modules::is_active('live_chat') && class_exists('VS_Pro_LiveChat') ) {
                    echo VS_Pro_LiveChat::render_vendor_notifications_tab($user);
                }

                if ( class_exists('VS_Modules') && VS_Modules::is_active('vendor_ads')&& class_exists('VS_Ads') ) {
                    echo VS_Ads::render_vendor_tab($user);
                }
                endif;
                echo VS_Orders::render($user);
                echo VS_Profile::render($user);
                echo VS_Restore::render($user);
                
                require_once VS_PATH . 'includes/class-vs-best-clients.php';
                echo VS_Best_Clients::render($user);

                // Ads tab — visible to both vendors and admins
               
                if (current_user_can('administrator')) {
                    echo VS_Vendors::render($user);
                    echo VS_Admin_Settings::render_front_settings_tab();
                    echo VS_Admin_Moderation::render_front_requests_tab();      // Products
                    echo VS_Admin_Moderation::render_front_vendor_requests_tab(); // Vendors
                    if (class_exists('VS_Reports')) {
                        echo VS_Reports::render_front_tab();
                    }
                    if (class_exists('VS_Modules')) {
                        echo VS_Modules::render_front_tab();
                    }
                } else {
                    echo VS_Admin_Moderation::render_vendor_requests_tab();
                }
                ?>

            </div>
        </div>

        
        <?php
        return ob_get_clean();
    }

    // ── AJAX: load a page of products from DB ────────────────
    public static function ajax_get_products_page() {
        check_ajax_referer('vs_nonce', 'security');

        $user_id    = get_current_user_id();
        if (!$user_id) wp_send_json_error(['message' => 'Not logged in']);

        $paged      = max(1, intval($_POST['paged']      ?? 1));
        $per_page   = 10;
        $search     = sanitize_text_field($_POST['search']      ?? '');
        $stock_f    = sanitize_text_field($_POST['stock_filter'] ?? '');
        $vendor_f   = intval($_POST['vendor_filter'] ?? 0);  // 0 = all
        $status_f   = sanitize_text_field($_POST['status_filter'] ?? '');

        // Blocked vendors
        $blocked_vendor_ids = get_users([
            'fields'     => 'ID',
            'meta_key'   => 'vs_vendor_status',
            'meta_value' => 'deleted',
        ]);
        $blocked_vendor_ids = !empty($blocked_vendor_ids) ? array_map('intval', $blocked_vendor_ids) : [];

        $args = [
            'post_type'      => 'product',
            'posts_per_page' => $per_page,
            'paged'          => $paged,
            'post_status'    => ['publish', 'draft', 'pending', 'pending_vendor', 'private'],
            'orderby'        => 'date',
            'order'          => 'DESC',
            'author__not_in' => $blocked_vendor_ids,
        ];

        if (!current_user_can('administrator')) {
            $args['author'] = $user_id;
            unset($args['author__not_in']);
        } elseif ($vendor_f > 0) {
            $args['author'] = $vendor_f;
            unset($args['author__not_in']);
        }

        if ($search !== '') {
            $args['s'] = $search;
        }

        if ($status_f !== '' && in_array($status_f, ['publish','draft','pending','pending_vendor','private'], true)) {
            $args['post_status'] = [$status_f];
        }

        // Stock filter via meta query
        if ($stock_f === 'in-stock') {
            $args['meta_query'] = [['key' => '_stock', 'value' => 0, 'compare' => '>', 'type' => 'NUMERIC']];
        } elseif ($stock_f === 'out-of-stock') {
            $args['meta_query'] = [['relation' => 'OR',
                ['key' => '_stock', 'value' => 0, 'compare' => '<=', 'type' => 'NUMERIC'],
                ['key' => '_stock', 'compare' => 'NOT EXISTS'],
            ]];
        }

        $query       = new WP_Query($args);
        $products    = $query->posts;
        $total_pages = max(1, $query->max_num_pages);
        $total_found = $query->found_posts;
        wp_reset_postdata();

        // Build HTML rows
        ob_start();
        if (empty($products)) {
    echo '<tr class="no-results">
            <td colspan="8" style="text-align:center;padding:40px;color:#94a3b8;">
                <div style="display:flex;flex-direction:column;align-items:center;gap:10px;">
                    <span class="dashicons dashicons-products" style="font-size:40px;width:40px;height:40px;color:#cbd5e1;"></span>
                    <div>' . esc_html__('No products found.', 'vendor-space') . '</div>
                </div>
            </td>
          </tr>';
} else {
            foreach ($products as $p) {
                echo self::render_product_row($p);
            }
        }
        $rows_html = ob_get_clean();

        wp_send_json_success([
            'rows'        => $rows_html,
            'total'       => $total_found,
            'total_pages' => $total_pages,
            'paged'       => $paged,
            'per_page'    => $per_page,
        ]);
    }

    // ── Helper: render a single <tr> for a product ───────────
    public static function render_product_row($p) {
        if (!$p || $p->post_status === 'trash') return '';

        $price         = get_post_meta($p->ID, '_price', true);
        $regular_price = get_post_meta($p->ID, '_regular_price', true);
        $sale_price    = get_post_meta($p->ID, '_sale_price', true);
        $stock         = get_post_meta($p->ID, '_stock', true);
        $sku           = get_post_meta($p->ID, '_sku', true);

        $type_terms    = wp_get_post_terms($p->ID, 'product_type', ['fields' => 'slugs']);
        $product_type  = !empty($type_terms) ? $type_terms[0] : 'simple';

        if ($product_type === 'variable') {
            $variation_ids = get_posts([
                'post_type'   => 'product_variation',
                'post_parent' => (int) $p->ID,
                'post_status' => ['publish', 'private', 'draft'],
                'numberposts' => -1,
                'fields'      => 'ids',
            ]);
            $sum_stock = 0;
            foreach ($variation_ids as $vid) {
                $vs = get_post_meta((int) $vid, '_stock', true);
                if ($vs === '' || $vs === null) continue;
                $sum_stock += (int) $vs;
            }
            $stock = $sum_stock;
        }

        $cat_terms    = wp_get_post_terms($p->ID, 'product_cat', ['fields' => 'ids']);
        $product_cat  = !empty($cat_terms) ? $cat_terms[0] : '';
        $short_desc   = $p->post_excerpt;
        $featured_id  = get_post_thumbnail_id($p->ID);
        $featured_url = $featured_id ? wp_get_attachment_image_url($featured_id, 'thumbnail') : '';
        $gallery_meta = get_post_meta($p->ID, '_product_image_gallery', true);
        $gallery_ids  = $gallery_meta ? array_filter(array_map('intval', explode(',', $gallery_meta))) : [];
        $gallery_urls = [];
        foreach ($gallery_ids as $gid) {
            $gurl = wp_get_attachment_image_url($gid, 'thumbnail');
            if ($gurl) $gallery_urls[] = $gurl;
        }
        $img = get_the_post_thumbnail($p->ID, [50, 50])
            ?: '<span class="dashicons dashicons-format-image" style="font-size:40px; color:#ccc;"></span>';

        $cats_names = wp_get_post_terms($p->ID, 'product_cat', ['fields' => 'names']);
        $cats_str   = (!empty($cats_names) && !is_wp_error($cats_names)) ? implode(', ', $cats_names) : '—';

        $is_rejected = get_post_meta($p->ID, '_vs_rejected', true);
        if ($is_rejected) {
            $status_badge = '<span class="vs-status-badge rejected">' . esc_html__('Rejected', 'vendor-space') . '</span>';
        } elseif ($p->post_status === 'pending') {
            $status_badge = '<span class="vs-status-badge pending">' . esc_html__('Pending Approval', 'vendor-space') . '</span>';
        } elseif ($p->post_status === 'pending_vendor') {
            $status_badge = '<span class="vs-status-badge pending" style="background:#bfdbfe; color:#1e40af;">' . esc_html__('Pending Your Approval', 'vendor-space') . '</span>';
        } elseif ($p->post_status === 'publish') {
            $status_badge = '<span class="vs-status-badge published">' . esc_html__('Published', 'vendor-space') . '</span>';
        } else {
            $status_badge = '<span class="vs-status-badge draft">' . esc_html__('Draft', 'vendor-space') . '</span>';
        }

        $stock_html = (!$stock || $stock == 0)
            ? '<span class="vs-status-badge rejected">' . esc_html__('OOS', 'vendor-space') . '</span>'
            : esc_html($stock);

        // Middle column: vendor (admin) or price (vendor)
        if (current_user_can('administrator')) {
            $vendor_user = get_userdata($p->post_author);
            $store_name  = get_user_meta($p->post_author, 'vs_store_name', true);
            $location    = (string) get_user_meta($p->post_author, 'vs_store_location', true);
            $vendor_email = $vendor_user ? esc_html($vendor_user->user_email) : 'Unknown';
            $stores_dir   = home_url('/stores/');
            if (class_exists('VS_Stores') && method_exists('VS_Stores', 'get_stores_directory_url')) {
                $stores_dir = (string) VS_Stores::get_stores_directory_url();
            }
            $store_url = add_query_arg('store_id', $p->post_author, $stores_dir);
            $mid_col = '<td class="product-vendor" style="color:black;">' . $vendor_email
                . '<div style="font-size:12px;color:#94a3b8;margin-top:4px;">'
                . esc_html__('Store:', 'vendor-space') . ' '
                . '<a href="' . esc_url($store_url) . '" style="color:#2563eb;text-decoration:none;font-weight:600;">' . esc_html($store_name) . '</a>'
                . ($location ? ' | ' . esc_html($location) : '')
                . '</div></td>';
        } else {
            $mid_col = '<td class="product-price">' . wc_price($price) . '</td>';
        }

        // Action buttons
        $actions = '<div class="vs-action-buttons" style="display:flex;gap:5px;flex-wrap:nowrap;justify-content:flex-start;">';
        if ($p->post_status === 'trash') {
            $actions .= '<button class="vs-action-btn vs-restore-btn" data-tooltip="' . esc_attr__('Restore', 'vendor-space') . '" data-product-id="' . $p->ID . '" style="background:#f59e0b;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;"><i class="fas fa-undo"></i></button>';
            $actions .= '<button class="vs-action-btn vs-delete-btn" data-tooltip="' . esc_attr__('Delete Permanently', 'vendor-space') . '" data-product-id="' . $p->ID . '" data-mode="permanent" style="background:#e74c3c;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;"><i class="fas fa-trash-alt"></i></button>';
        } else {
            $actions .= '<button class="vs-action-btn vs-delete-btn" data-tooltip="' . esc_attr__('Delete', 'vendor-space') . '" data-product-id="' . $p->ID . '" style="background:#e74c3c;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;"><i class="fas fa-trash"></i></button>';
        }
        $actions .= '<button class="vs-action-btn vs-edit-btn"'
            . ' data-tooltip="' . esc_attr__('Edit', 'vendor-space') . '"'
            . ' data-product-id="' . esc_attr($p->ID) . '"'
            . ' data-product-name="' . esc_attr($p->post_title) . '"'
            . ' data-product-desc="' . esc_attr($p->post_content) . '"'
            . ' data-product-short-desc="' . esc_attr($short_desc) . '"'
            . ' data-product-price="' . esc_attr($price) . '"'
            . ' data-product-regular-price="' . esc_attr($regular_price) . '"'
            . ' data-product-sale-price="' . esc_attr($sale_price) . '"'
            . ' data-product-stock="' . esc_attr($stock) . '"'
            . ' data-product-sku="' . esc_attr($sku) . '"'
            . ' data-product-type="' . esc_attr($product_type) . '"'
            . ' data-product-status="' . esc_attr($p->post_status) . '"'
            . ' data-product-cat="' . esc_attr($product_cat) . '"'
            . ' data-product-featured-id="' . esc_attr($featured_id) . '"'
            . ' data-product-featured-url="' . esc_attr($featured_url) . '"'
            . ' data-product-gallery-ids="' . esc_attr(wp_json_encode($gallery_ids)) . '"'
            . ' data-product-gallery-urls="' . esc_attr(wp_json_encode($gallery_urls)) . '"'
            . ' style="background:#3498db;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;">'
            . '<i class="fas fa-pen"></i></button>';
        $actions .= '<button class="vs-action-btn vs-quick-edit-btn" data-tooltip="' . esc_attr__('Quick Edit', 'vendor-space') . '" data-product-id="' . $p->ID . '" style="background:#0ea5e9;color:white;border:none;padding:5px 10px;border-radius:4px;cursor:pointer;"><i class="fas fa-bolt"></i></button>';
        if ($p->post_status === 'publish') {
            $actions .= '<a href="' . esc_url(get_permalink($p->ID)) . '" target="_blank" class="vs-action-btn vs-view-btn" data-tooltip="' . esc_attr__('View', 'vendor-space') . '" style="background:#2ecc71;color:white;text-decoration:none;padding:5px 10px;border-radius:4px;display:flex;align-items:center;justify-content:center;"><i class="fas fa-eye"></i></a>';
        }
        $actions .= '</div>';

        return '<tr id="product-row-' . $p->ID . '" data-vendor-id="' . esc_attr($p->post_author) . '">'
            . '<td><input type="checkbox" class="vs-select-product" value="' . $p->ID . '"></td>'
            . '<td class="product-image">' . $img . '</td>'
            . '<td class="product-name">' . esc_html($p->post_title) . '</td>'
            . '<td class="product-desc">' . esc_html($cats_str) . '</td>'
            . $mid_col
            . '<td class="product-stock">' . $stock_html . '</td>'
            . '<td class="product-status">' . $status_badge . '</td>'
            . '<td style="min-width:5%;" data-export="skip">' . $actions . '</td>'
            . '</tr>';
    }

}
