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

class VS_Profile {
    private const EMAIL_TOKEN_META = 'vs_email_verify_token';
    private const EMAIL_EXPIRY_META = 'vs_email_verify_expires';
    private const EMAIL_CHANGE_PENDING_META = 'vs_email_change_pending';
    private const EMAIL_CHANGE_OTP_META = 'vs_email_change_otp';
    private const EMAIL_CHANGE_OTP_EXPIRY_META = 'vs_email_change_otp_expires';

    public static function init() {
        add_action('wp_ajax_vs_profile_save_account', [__CLASS__, 'save_account_ajax']);
        add_action('wp_ajax_vs_profile_check_email', [__CLASS__, 'check_email_ajax']);
        add_action('wp_ajax_vs_profile_send_reset', [__CLASS__, 'send_reset_ajax']);
        add_action('wp_ajax_vs_profile_save_store', [__CLASS__, 'save_store_ajax']);
        add_action('wp_ajax_vs_profile_save_visibility', [__CLASS__, 'save_visibility_ajax']);
        add_action('wp_ajax_vs_profile_keepalive', [__CLASS__, 'keepalive_ajax']);
        add_action('init', [__CLASS__, 'handle_email_verification']);
        add_action('template_redirect', [__CLASS__, 'prevent_cache_dashboard']);
        add_action('wp_enqueue_scripts', [__CLASS__, 'enqueue_vendor_custom_css'], 25);
        add_action('woocommerce_single_product_summary', [__CLASS__, 'render_single_vendor_info'], 31);
    }

    public static function render($user) {
        if (!$user || !self::is_vendor_user($user->ID)) { // self car is_vendor_user static method in this class
            return '';
        }

        $data = self::build_profile_data($user->ID);
        $verify_notice = isset($_GET['vs_verify']) ? sanitize_text_field(wp_unslash($_GET['vs_verify'])) : '';
             // Register OTP Modal
        add_action('wp_footer', [__CLASS__, 'render_otp_modal']);

        $all_countries = function_exists('WC') ? WC()->countries->get_countries() : [];

        if (isset($_GET['vs_profile_updated']) && $_GET['vs_profile_updated'] === '1') {
            wc_add_notice(__('Profile updated successfully!', 'vendor-space'), 'success');
        }

        ob_start();
        ?>
        <style>
        .vs-otp-overlay{position:fixed;inset:0;background:rgba(15,23,42,.62);backdrop-filter:blur(3px);display:flex;align-items:center;justify-content:center;padding:18px;z-index:999999}
        .vs-otp-card{width:100%;max-width:460px;background:#fff;border-radius:24px;padding:28px;box-shadow:0 30px 80px rgba(15,23,42,.28);position:relative;text-align:center;border:1px solid rgba(148,163,184,.2)}
        .vs-otp-close{position:absolute;top:12px;right:14px;border:none;background:transparent;font-size:28px;line-height:1;color:#94a3b8;cursor:pointer}
        .vs-otp-badge{display:inline-flex;padding:8px 12px;border-radius:999px;background:#eff6ff;color:#1d4ed8;font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase}
        .vs-otp-card h2{margin:16px 0 10px;font-size:30px;line-height:1.2;color:#0f172a}
        .vs-otp-subtitle{margin:0;color:#475569;line-height:1.8}
        .vs-otp-inputs{display:flex;justify-content:center;gap:12px;margin:24px 0 18px}
        .vs-otp-digit{width:62px;height:68px;border:1px solid #cbd5e1;border-radius:18px;text-align:center;font-size:28px;font-weight:700;color:#0f172a;background:#f8fafc;transition:.2s}
        .vs-otp-digit:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,.15);background:#fff}
        .vs-otp-message{min-height:24px;font-size:14px;font-weight:600;color:#0f172a;margin-top:10px}
        .vs-otp-message.is-error{color:#dc2626}
        .vs-otp-message.is-success{color:#059669}
        .vs-otp-actions{display:flex;justify-content:center;align-items:center;gap:12px;margin-top:24px}
        .vs-otp-card.is-shaking{animation:vsOtpShake .35s linear}
        @keyframes vsOtpShake{0%,100%{transform:translateX(0)}25%{transform:translateX(-4px)}75%{transform:translateX(4px)}}
        @media (max-width: 520px){.vs-otp-card{padding:24px 18px;border-radius:20px}.vs-otp-digit{width:54px;height:60px;font-size:24px}}
        </style>
<style>
    .vs-profile-panel {
    margin-bottom: 12px;
    border: 1px solid #e2e8f0;
    border-radius: 14px;
    overflow: hidden;
    background: #ffffff;
    transition: all 0.3s ease;
}

.vs-profile-panel > summary {
    list-style: none;
    cursor: pointer;
    display: flex;
    gap: 10px;
    align-items: center;
    padding: 14px 16px;
    font-weight: 700;
    color: #0f172a;
    background: linear-gradient(135deg, #f8fafc, #eef2f7);
    position: relative;
    transition: all 0.3s ease;
}

.vs-profile-panel > summary:hover {
    background: linear-gradient(135deg, #e2e8f0, #dbeafe);
}

.vs-profile-panel > summary::-webkit-details-marker {
    display: none;
}

/* أيقونة الفتح والإغلاق */
.vs-toggle-icon {
    margin-left: auto;
    font-size: 14px;
    color: #64748b;
    transition: all 0.3s ease;
}

/* عند الفتح */
.vs-profile-panel[open] > summary .vs-toggle-icon {
    transform: rotate(180deg);
    color: #2563eb;
}

/* تأثير خفيف عند الفتح */
.vs-profile-panel[open] {
    border-color: #2563eb;
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.08);
}

</style>

        <div class="vs-tab" id="tab-profile" style="display:none;">
            <!-- Header Card -->
            <div class="vs-profile-header-card">
                <!-- User Profile Section -->
                <div class="vs-user-profile-section">
                    <?php if (!empty($data['store']['logo_url'])): ?>
    <img 
        class="vs-profile-avatar-preview"
        src="<?php echo esc_url($data['store']['logo_url']); ?>" 
        alt="Store Logo"
    >
<?php else: ?>
    <?php echo get_avatar($user->ID, 80, '', '', array('class' => 'vs-profile-avatar-preview')); ?>
<?php endif; ?>
                    <div class="vs-user-info">
                        <h2 class="vs-user-name"><?php echo esc_html($user->display_name ?: $data['account']['username']); ?></h2>
                        <p class="vs-user-email"><?php echo esc_html($data['account']['email']); ?></p>
                        
                    </div>
                </div>

                <!-- Store Info Section -->
                <div class="vs-store-profile-section">
                    <div class="vs-store-logo">
                        <?php if (!empty($data['store']['banner_url'])): ?>
                            <img src="<?php echo esc_url($data['store']['banner_url']); ?>" alt="Store Banner">
                        <?php else: ?>
                            <div class="vs-logo-placeholder">
                                <span class="dashicons dashicons-store"></span>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="vs-store-info">
                        <h3><?php echo esc_html($data['store']['name'] ?: __('Store Name', 'vendor-space')); ?></h3>
                        <p><?php echo esc_html($data['store']['location'] ?: __('Location not set', 'vendor-space')); ?></p>
                    </div>
                </div>
            </div>

            <!-- Tabs Navigation -->
<div class="vs-profile-tabs">
    <button class="vs-tab-btn active" data-tab="account">
        <span class="dashicons dashicons-admin-users"></span>
        <span><?php echo esc_html__('Account', 'vendor-space'); ?></span>
    </button>
    <button class="vs-tab-btn" data-tab="store-info">
        <span class="dashicons dashicons-store"></span>
        <span><?php echo esc_html__('Store Info', 'vendor-space'); ?></span>
    </button>

    <button class="vs-tab-btn" data-tab="branding">
        <span class="dashicons dashicons-art"></span>
        <span><?php echo esc_html__('Branding', 'vendor-space'); ?></span>
    </button>

    <button class="vs-tab-btn" data-tab="social-links">
        <span class="dashicons dashicons-share"></span>
        <span><?php echo esc_html__('Social Links', 'vendor-space'); ?></span>
    </button>

    <button class="vs-tab-btn" data-tab="security">
        <span class="dashicons dashicons-lock"></span>
        <span><?php echo esc_html__('Data Visibility', 'vendor-space'); ?></span>
    </button>
                        </div>
                        <style>
                            .vs-profile-tabs {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 24px;
    padding: 12px;
    background: linear-gradient(135deg, #f8fafc, #eef4ff);
    border: 1px solid #dbeafe;
    border-radius: 18px;
    box-shadow: 0 6px 20px rgba(37, 99, 235, 0.08);
}

.vs-profile-tabs .vs-tab-btn {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 12px 18px;
    border: 1px solid transparent;
    border-radius: 14px;
    background: #ffffff;
    color: #334155;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.28s ease;
    box-shadow: 0 3px 10px rgba(15, 23, 42, 0.04);
    position: relative;
    overflow: hidden;
}

.vs-profile-tabs .vs-tab-btn .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
    color: #3b82f6;
    transition: all 0.28s ease;
}

.vs-profile-tabs .vs-tab-btn:hover {
    transform: translateY(-2px);
    background: #eff6ff;
    color: #1d4ed8;
    border-color: #bfdbfe;
    box-shadow: 0 8px 18px rgba(59, 130, 246, 0.15);
}

.vs-profile-tabs .vs-tab-btn:hover .dashicons {
    color: #2563eb;
    transform: scale(1.08);
}

.vs-profile-tabs .vs-tab-btn.active {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #ffffff;
    border-color: #2563eb;
    box-shadow: 0 10px 24px rgba(37, 99, 235, 0.28);
}

.vs-profile-tabs .vs-tab-btn.active .dashicons {
    color: #ffffff;
}

.vs-profile-tabs .vs-tab-btn.active::after {
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 14px;
    box-shadow: inset 0 0 0 1px rgba(255,255,255,0.12);
    pointer-events: none;
}

/* Responsive */
@media (max-width: 768px) {
    .vs-profile-tabs {
        gap: 10px;
        padding: 10px;
    }

    .vs-profile-tabs .vs-tab-btn {
        flex: 1 1 calc(50% - 10px);
        justify-content: center;
        padding: 12px 14px;
        font-size: 13px;
    }
}

@media (max-width: 480px) {
    .vs-profile-tabs .vs-tab-btn {
        flex: 1 1 100%;
    }
}
                        </style>

            <!-- Tab Content -->
            <div class="vs-tab-content">
              <!-- Account Tab -->
<div id="tab-account" class="vs-tab-pane active">
    <div class="vs-profile-card">
        <div class="vs-card-header">
            <div class="vs-card-title-wrap">
                <span class="dashicons dashicons-admin-generic"></span>
                <h3><?php echo esc_html__('Account Settings', 'vendor-space'); ?></h3>
            </div>
            <p class="vs-card-subtitle"><?php echo esc_html__('Manage your login details, and password securely.', 'vendor-space'); ?></p>
        </div>

        <form id="vs-account-form" class="vs-profile-form">
            <div class="vs-form-grid">
                <div class="vs-field">
                    <label for="vs-account-username"><?php echo esc_html__('Username', 'vendor-space'); ?></label>
                    <input id="vs-account-username" type="text" name="username" value="<?php echo esc_attr($data['account']['username']); ?>" required>
                </div>

                <div class="vs-field">
                    <label for="vs-account-display-name"><?php echo esc_html__('Display Name', 'vendor-space'); ?></label>
                    <input id="vs-account-display-name" type="text" name="display_name" value="<?php echo esc_attr($data['account']['display_name']); ?>">
                </div>

                <div class="vs-field">
                    <label for="vs-account-email"><?php echo esc_html__('Email', 'vendor-space'); ?></label>
                    <input id="vs-account-email" type="email" name="email" value="<?php echo esc_attr($data['account']['email']); ?>" required>
                    <input id="vs-account-current-email" type="hidden" value="<?php echo esc_attr($data['account']['email']); ?>">
                    <small id="vs-account-email-status" class="vs-help-inline" style="display:none;"></small>
                </div>

                <div class="vs-field">
                    <label for="vs-account-first-name"><?php echo esc_html__('First Name', 'vendor-space'); ?></label>
                    <input id="vs-account-first-name" type="text" name="first_name" value="<?php echo esc_attr($data['account']['first_name']); ?>">
                </div>

                <div class="vs-field">
                    <label for="vs-account-last-name"><?php echo esc_html__('Last Name', 'vendor-space'); ?></label>
                    <input id="vs-account-last-name" type="text" name="last_name" value="<?php echo esc_attr($data['account']['last_name']); ?>">
                </div>

                <div class="vs-field vs-field-full">
                    <label for="vs-account-address"><?php echo esc_html__('Address', 'vendor-space'); ?></label>
                    <input id="vs-account-address" type="text" name="address" value="<?php echo esc_attr($data['account']['address']); ?>" placeholder="<?php echo esc_attr__('Street address', 'vendor-space'); ?>">
                </div>

                <div class="vs-field">
                    <label for="vs-account-country"><?php echo esc_html__('Country', 'vendor-space'); ?></label>
                    <select id="vs-account-country" name="country">
                        <option value=""><?php echo esc_html__('Select a country...', 'vendor-space'); ?></option>
                        <?php foreach ($all_countries as $code => $country_name): ?>
                            <option value="<?php echo esc_attr($code); ?>" <?php selected($data['account']['country'], $code); ?>>
                                <?php echo esc_html($country_name); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="vs-field">
                    <label for="vs-account-city"><?php echo esc_html__('City', 'vendor-space'); ?></label>
                    <input id="vs-account-city" type="text" name="city" value="<?php echo esc_attr($data['account']['city']); ?>">
                </div>

                <div class="vs-field vs-field-full" id="vs-account-email-otp-wrap" style="display:none;">
                    <label for="vs-account-email-otp"><?php echo esc_html__('Verification OTP Code', 'vendor-space'); ?></label>
                    <input id="vs-account-email-otp" type="text" name="email_otp" inputmode="numeric" pattern="[0-9]*" maxlength="6" autocomplete="one-time-code">
                    <small class="vs-help-inline"><?php echo esc_html__('Enter the 4-digit code sent to your email to confirm changes.', 'vendor-space'); ?></small>
                </div>

                <div class="vs-field" id="vs-password-otp-wrap" style="display:none;">
                    <label for="vs-password-otp"><?php echo esc_html__('Security Code', 'vendor-space'); ?></label>
                    <input id="vs-password-otp" type="text" name="otp" inputmode="numeric" pattern="[0-9]*" maxlength="4" autocomplete="one-time-code">
                </div>

<div class="vs-field">
    <label for="vs-account-password"><?php echo esc_html__('New Password', 'vendor-space'); ?></label>
    <div class="vs-password-wrap">
        <input id="vs-account-password" type="password" name="new_password" placeholder="new-password">
        <span class="vs-toggle-password dashicons dashicons-visibility" 
              data-target="vs-account-password"
              role="button"
              tabindex="0"
              aria-label="<?php echo esc_attr__('Show password', 'vendor-space'); ?>">
        </span>
    </div>
</div>

<div class="vs-field">
    <label for="vs-account-password-confirm"><?php echo esc_html__('Confirm Password', 'vendor-space'); ?></label>
    <div class="vs-password-wrap">
        <input id="vs-account-password-confirm" type="password" name="confirm_password" placeholder="confirm-password">
        <span class="vs-toggle-password dashicons dashicons-visibility" 
              data-target="vs-account-password-confirm"
              role="button"
              tabindex="0"
              aria-label="<?php echo esc_attr__('Show password', 'vendor-space'); ?>">
        </span>
    </div>
</div>
<style>
   .vs-password-wrap {
    position: relative;
}

.vs-password-wrap input {
    width: 100%;
    padding-right: 42px;
}

.vs-toggle-password {
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    color: #6b7280;
    font-size: 18px;
    width: 20px;
    height: 20px;
    line-height: 20px;
    user-select: none;
    transition: color 0.2s ease;
}

.vs-toggle-password:hover {
    color: #2563eb;
}

.vs-help-inline {
    font-size: 12px;
    margin-top: 4px;
    display: block;
}
</style>
<script> //show and hide
   jQuery(document).ready(function($) {
    $(document).on('click keypress', '.vs-toggle-password', function(e) {
        if (e.type === 'keypress' && e.which !== 13 && e.which !== 32) {
            return;
        }

        const $icon = $(this);
        const targetId = $icon.data('target');
        const $input = $('#' + targetId);

        if ($input.attr('type') === 'password') {
            $input.attr('type', 'text');
            $icon.removeClass('dashicons-visibility').addClass('dashicons-hidden');
            $icon.attr('aria-label', 'Hide password');
        } else {
            $input.attr('type', 'password');
            $icon.removeClass('dashicons-hidden').addClass('dashicons-visibility');
            $icon.attr('aria-label', 'Show password');
        }
    });
});

jQuery(document).ready(function($) {

    const profileAjaxUrl = window.vs_vars?.ajaxurl || ajaxurl;
    const profileNonce   = window.vs_vars?.nonce;

    const $emailInput   = $('#vs-account-email');
    const $emailStatus  = $('#vs-account-email-status');
    const $currentEmail = $('#vs-account-current-email');

    let emailCheckTimeout;

    function isEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    function checkEmailAvailability(email) {

        if (!email || !isEmail(email)) {
            $emailStatus.hide();
            return;
        }

        if (email.toLowerCase() === $currentEmail.val().toLowerCase()) {
            $emailStatus.hide();
            return;
        }

        $emailStatus.html('<span style="color:#64748b;">Checking...</span>').show();

        $.post(profileAjaxUrl, {
            action: 'vs_profile_check_email',
            security: profileNonce,
            email: email
        }, function(response) {

            // SUCCESS
            if (response.success && response.data && response.data.available) {
                $emailStatus.html('<span style="color:#059669;">✓ Available</span>').show();
            } 
            // ERROR (email exists)
            else {
                const msg = response.data?.message || 'Already registered';

                $emailStatus.html(
                    '<span style="color:#dc2626;">✗ ' + msg + '</span>'
                ).show();
            }

        }).fail(function() {
            $emailStatus.html('<span style="color:#dc2626;">✗ Server error</span>').show();
        });
    }

    $emailInput.on('input', function() {

        clearTimeout(emailCheckTimeout);

        const email = $(this).val().trim();

        emailCheckTimeout = setTimeout(function() {
            checkEmailAvailability(email);
        }, 500);
    });

    $emailInput.on('blur', function() {

        const email = $(this).val().trim();

        if (email && isEmail(email)) {
            checkEmailAvailability(email);
        }
    });

});

</script>


            </div>

            <div class="vs-form-actions">
                <button type="submit" class="vs-btn vs-btn-primary">
                    <span class="dashicons dashicons-saved"></span>
                    <span><?php echo esc_html__('Save Account', 'vendor-space'); ?></span>
                </button>
            </div>
        </form>
    </div>
</div>
<style>
    /* =========================
   TAB PANE ANIMATION
========================= */
.vs-tab-pane {
    display: none;
    animation: vsFadeUp 0.35s ease;
}

.vs-tab-pane.active {
    display: block;
}

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

/* =========================
   PROFILE CARD
========================= */
.vs-profile-card {
    background: linear-gradient(180deg, #ffffff 0%, #f8fbff 100%);
    border: 1px solid #dbeafe;
    border-radius: 22px;
    padding: 28px;
    box-shadow: 0 12px 35px rgba(15, 23, 42, 0.06);
    position: relative;
    overflow: hidden;
}

.vs-profile-card::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #2563eb, #3b82f6, #60a5fa);
}

/* =========================
   CARD HEADER
========================= */
.vs-card-header {
    margin-bottom: 24px;
    padding-bottom: 18px;
    border-bottom: 1px solid #e5e7eb;
}

.vs-card-title-wrap {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 6px;
}

.vs-card-title-wrap .dashicons {
    font-size: 22px;
    width: 22px;
    height: 22px;
    color: #2563eb;
}

.vs-profile-card h3 {
    margin: 0;
    font-size: 24px;
    line-height: 1.2;
    font-weight: 700;
    color: #0f172a;
}

.vs-card-subtitle {
    margin: 0;
    font-size: 14px;
    color: #64748b;
    line-height: 1.6;
}

/* إذا بقيت تستعمل h3 فقط بدون header */
.vs-profile-card > h3 {
    margin: 0 0 20px;
    font-size: 24px;
    font-weight: 700;
    color: #0f172a;
    padding-bottom: 14px;
    border-bottom: 1px solid #e5e7eb;
}

/* =========================
   FORM GRID
========================= */
.vs-profile-form {
    margin: 0;
}

.vs-form-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 20px;
}

.vs-field {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.vs-field.vs-field-full {
    grid-column: 1 / -1;
}

/* =========================
   LABELS
========================= */
.vs-field label {
    font-size: 14px;
    font-weight: 600;
    color: #1e293b;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* =========================
   INPUTS
========================= */
.vs-field input[type="text"],
.vs-field input[type="email"],
.vs-field input[type="password"],
.vs-field input[type="number"],
.vs-field input[type="tel"],
.vs-field textarea,
.vs-field select {
    width: 100%;
    min-height: 50px;
    padding: 13px 15px;
    border: 1px solid #cbd5e1;
    border-radius: 14px;
    background: #ffffff;
    color: #0f172a;
    font-size: 14px;
    font-weight: 500;
    outline: none;
    transition: all 0.25s ease;
    box-shadow: inset 0 1px 2px rgba(15, 23, 42, 0.03);
    box-sizing: border-box;
}

.vs-field textarea {
    min-height: 120px;
    resize: vertical;
}

.vs-field input::placeholder,
.vs-field textarea::placeholder {
    color: #94a3b8;
    font-weight: 400;
}

.vs-field input:hover,
.vs-field textarea:hover,
.vs-field select:hover {
    border-color: #93c5fd;
    background: #fefefe;
}

.vs-field input:focus,
.vs-field textarea:focus,
.vs-field select:focus {
    border-color: #3b82f6;
    background: #ffffff;
    box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.12);
}

/* =========================
   OTP FIELD SPECIAL STYLE
========================= */
#vs-account-email-otp-wrap {
    background: linear-gradient(135deg, #eff6ff, #f8fbff);
    border: 1px dashed #93c5fd;
    border-radius: 18px;
    padding: 16px;
}

#vs-account-email-otp {
    letter-spacing: 6px;
    text-align: center;
    font-size: 18px;
    font-weight: 700;
}

.vs-help-inline {
    display: block;
    margin-top: 6px;
    font-size: 12px;
    line-height: 1.6;
    color: #475569;
}

#vs-account-email-status.is-error {
    color: #dc2626;
}

#vs-account-email-status.is-info {
    color: #2563eb;
}

#vs-account-email.is-invalid {
    border-color: #ef4444;
    background: #fef2f2;
}

/* =========================
   ACTIONS
========================= */
.vs-form-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 26px;
    padding-top: 18px;
    border-top: 1px solid #e5e7eb;
}

/* =========================
   BUTTONS
========================= */
.vs-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    min-height: 50px;
    padding: 0 22px;
    border: none;
    border-radius: 14px;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    text-decoration: none;
    transition: all 0.25s ease;
}

.vs-btn .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
}

.vs-btn-primary {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #ffffff;
    box-shadow: 0 10px 24px rgba(37, 99, 235, 0.22);
}

.vs-btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 14px 28px rgba(37, 99, 235, 0.28);
    filter: brightness(1.03);
}

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

/* =========================
   RESPONSIVE
========================= */
@media (max-width: 768px) {
    .vs-profile-card {
        padding: 20px;
        border-radius: 18px;
    }

    .vs-form-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .vs-profile-card h3 {
        font-size: 20px;
    }

    .vs-form-actions {
        justify-content: stretch;
    }

    .vs-form-actions .vs-btn {
        width: 100%;
    }
}
.vs-profile-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
    padding: 30px;
    border: 1px solid #e1e1e1;
}

.vs-card-header {
    margin-bottom: 25px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 15px;
}

.vs-card-header h3 {
    margin: 0;
    color: #2c3338;
    font-size: 22px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.vs-subtitle {
    color: #666;
    font-size: 14px;
    margin-top: 5px;
}

.vs-form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr); /* حقلين في كل صف */
    gap: 20px;
}

.vs-field.full {
    grid-column: span 2; /* حقول تأخذ العرض الكامل */
}

.vs-field label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #444;
}

.vs-field input, .vs-field textarea {
    width: 100%;
    padding: 12px 15px;
    border: 1.5px solid #ddd;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.vs-field input:focus, .vs-field textarea:focus {
    border-color: #2271b1; /* لون أزرق ووردبريس */
    box-shadow: 0 0 0 2px rgba(34, 113, 177, 0.1);
    outline: none;
}

.vs-hours-highlight {
    background: #f8fbff;
    padding: 15px;
    border-radius: 8px;
    border: 1px dashed #2271b1;
}

.vs-btn-save {
    background: #2271b1;
    color: white;
    padding: 12px 25px;
    border: none;
    border-radius: 8px;
    font-weight: bold;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 10px;
    transition: background 0.2s;
}

.vs-btn-save:hover {
    background: #135e96;
}
</style>

<div id="tab-store-info" class="vs-tab-pane">
    <div class="vs-profile-card">
        <div class="vs-card-header">
            <h3><i class="dashicons dashicons-store"></i> <?php echo esc_html__('Store Settings', 'vendor-space'); ?></h3>
            <p class="vs-subtitle"><?php echo esc_html__('Manage your public store profile and contact information', 'vendor-space'); ?></p>
        </div>

        <form id="vs-store-form" class="vs-profile-form" enctype="multipart/form-data">
            <div class="vs-form-grid">
                
                <div class="vs-field">
                    <label for="vs-store-name-profile">
                        <i class="dashicons dashicons-id"></i> <?php echo esc_html__('Store Name', 'vendor-space'); ?>
                    </label>
                    <input id="vs-store-name-profile" type="text" name="store_name" value="<?php echo esc_attr($data['store']['name']); ?>" placeholder="Enter your business name" required>
                </div>

                <div class="vs-field">
                    <label for="vs-store-location-profile">
                        <i class="dashicons dashicons-location"></i> <?php echo esc_html__('Location', 'vendor-space'); ?>
                    </label>
                    <input id="vs-store-location-profile" type="text" name="location" value="<?php echo esc_attr($data['store']['location']); ?>" placeholder="e.g. Oran, Algeria">
                </div>

                
                <div class="vs-field">
                    <label for="vs-store-contact-phone">
                        <i class="dashicons dashicons-phone"></i> <?php echo esc_html__('Contact Phone', 'vendor-space'); ?>
                    </label>
                    <input id="vs-store-contact-phone" type="tel" name="contact_phone" value="<?php echo esc_attr($data['store']['contact_phone']); ?>" placeholder="+XXXXXXXXXX">
                </div>

                

                <div class="vs-field full vs-hours-highlight">
                    <label for="vs-store-hours">
                        <i class="dashicons dashicons-clock"></i> <?php echo esc_html__('Operating Hours', 'vendor-space'); ?>
                    </label>
                    <div class="vs-input-group">
                        <input id="vs-store-hours" 
                               type="text" 
                               name="operating_hours" 
                               value="<?php echo esc_attr($data['store']['operating_hours']); ?>" 
                               placeholder="e.g. Mon-Fri: 09:00 AM - 06:00 PM"
                               class="vs-styled-input">
                    </div>
                </div>

                <div class="vs-field full">
                    <label for="vs-store-description">
                        <i class="dashicons dashicons-editor-paragraph"></i> <?php echo esc_html__('Store Bio / Description', 'vendor-space'); ?>
                    </label>
                    <textarea id="vs-store-description" name="description" rows="5" placeholder="Tell your customers about your business..."><?php echo esc_textarea($data['store']['description']); ?></textarea>
                </div>
            </div>

            <div class="vs-form-actions">
                <button type="submit" class="vs-btn vs-btn-save">
                    <i class="dashicons dashicons-saved"></i> <?php echo esc_html__('Update Store Profile', 'vendor-space'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

                <!-- Branding Tab -->
                <div id="tab-branding" class="vs-tab-pane">
                    <!-- Live Preview Section -->
                    <div class="vs-live-preview-section">
                        <div class="vs-preview-header">
                            <h4><?php echo esc_html__('Live Preview', 'vendor-space'); ?></h4>
                            <span class="vs-preview-badge"><?php echo esc_html__('Real-time', 'vendor-space'); ?></span>
                        </div>
                        <div class="vs-banner-preview">
                            <div class="vs-banner-image" id="vs-banner-preview">
                                <?php if (!empty($data['store']['banner_url'])): ?>
                                    <img src="<?php echo esc_url($data['store']['banner_url']); ?>" alt="Store Banner">
                                <?php else: ?>
                                    <div class="vs-banner-placeholder">
                                        <span><?php echo esc_html__('Banner Preview', 'vendor-space'); ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div class="vs-profile-overlay" id="vs-profile-preview">
<?php if (!empty($data['store']['logo_url'])): ?>
    <img 
        class="vs-profile-avatar-preview"
        src="<?php echo esc_url($data['store']['logo_url']); ?>" 
        alt="Store Logo"
    >
<?php else: ?>
    <?php echo get_avatar($user->ID, 80, '', '', array('class' => 'vs-profile-avatar-preview')); ?>
<?php endif; ?>                                <div class="vs-profile-info-preview">
                                    <h5><?php echo esc_html($user->display_name); ?></h5>
                                    <p><?php echo esc_html($user->user_email); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="vs-profile-card">
                        <h3><?php echo esc_html__('Branding', 'vendor-space'); ?></h3>
                        <form id="vs-branding-form" class="vs-profile-form" enctype="multipart/form-data">
                            <input type="hidden" name="store_name" value="<?php echo esc_attr($data['store']['name'] ?? ''); ?>">
                            <div class="vs-form-grid">
                                <div class="vs-field">
                                    <label class="vs-upload-label"><?php echo esc_html__('Store Logo', 'vendor-space'); ?></label>
                                    <div class="vs-store-upload-box" data-placeholder="<?php echo esc_attr__('Click to upload Store Logo', 'vendor-space'); ?>">
                                        <input id="vs-store-logo" type="file" name="store_logo" accept="image/*">
                                        <input type="hidden" name="remove_store_logo" value="0">
                                        <button type="button" class="vs-store-upload-remove <?php echo empty($data['store']['logo_url']) ? 'is-hidden' : ''; ?>">x</button>
                                        <?php if (!empty($data['store']['logo_url'])): ?>
                                            <img class="vs-store-media-preview" src="<?php echo esc_url($data['store']['logo_url']); ?>">
                                        <?php else: ?>
                                            <span class="vs-store-upload-placeholder"><?php echo esc_html__('Click to upload Store Logo', 'vendor-space'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="vs-field">
                                    <label class="vs-upload-label"><?php echo esc_html__('Store Banner', 'vendor-space'); ?></label>
                                    <div class="vs-store-upload-box" data-placeholder="<?php echo esc_attr__('Click to upload Store Banner', 'vendor-space'); ?>">
                                        <input id="vs-store-banner" type="file" name="store_banner" accept="image/*">
                                        <input type="hidden" name="remove_store_banner" value="0">
                                        <button type="button" class="vs-store-upload-remove <?php echo empty($data['store']['banner_url']) ? 'is-hidden' : ''; ?>">x</button>
                                        <?php if (!empty($data['store']['banner_url'])): ?>
                                            <img class="vs-store-media-preview" src="<?php echo esc_url($data['store']['banner_url']); ?>">
                                        <?php else: ?>
                                            <span class="vs-store-upload-placeholder"><?php echo esc_html__('Click to upload Store Banner', 'vendor-space'); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                               
                            </div>
                            <div class="vs-form-actions">
                                <button type="submit" class="vs-btn vs-btn-primary"><?php echo esc_html__('Save Branding', 'vendor-space'); ?></button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Social Links Tab -->
                <div id="tab-social-links" class="vs-tab-pane">
                    <div class="vs-profile-card">
                        <h3><?php echo esc_html__('Social Media Links', 'vendor-space'); ?></h3>
                        <form id="vs-social-form" class="vs-profile-form">
                            <div class="vs-form-grid">
                                <div class="vs-field">
                                    <label for="vs-store-facebook"><?php echo esc_html__('Facebook URL', 'vendor-space'); ?></label>
                                    <input id="vs-store-facebook" type="url" name="social_facebook" value="<?php echo esc_attr($data['store']['social']['facebook']); ?>">
                                </div>
                                <div class="vs-field">
                                    <label for="vs-store-instagram"><?php echo esc_html__('Instagram URL', 'vendor-space'); ?></label>
                                    <input id="vs-store-instagram" type="url" name="social_instagram" value="<?php echo esc_attr($data['store']['social']['instagram']); ?>">
                                </div>
                                <div class="vs-field">
                                    <label for="vs-store-x"><?php echo esc_html__('X / Twitter URL', 'vendor-space'); ?></label>
                                    <input id="vs-store-x" type="url" name="social_x" value="<?php echo esc_attr($data['store']['social']['x']); ?>">
                                </div>
                                <div class="vs-field">
                                    <label for="vs-store-linkedin"><?php echo esc_html__('LinkedIn URL', 'vendor-space'); ?></label>
                                    <input id="vs-store-linkedin" type="url" name="social_linkedin" value="<?php echo esc_attr($data['store']['social']['linkedin']); ?>">
                                </div>
                                <div class="vs-field">
                                    <label for="vs-store-youtube"><?php echo esc_html__('YouTube URL', 'vendor-space'); ?></label>
                                    <input id="vs-store-youtube" type="url" name="social_youtube" value="<?php echo esc_attr($data['store']['social']['youtube']); ?>">
                                </div>
                            </div>
                            <div class="vs-form-actions">
                                <button type="submit" class="vs-btn vs-btn-primary"><?php echo esc_html__('Save Social Links', 'vendor-space'); ?></button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Security Tab -->
                <div id="tab-security" class="vs-tab-pane">
                    <div class="vs-profile-card">
                        <h3><?php echo esc_html__('Data Visibility', 'vendor-space'); ?></h3>
                        <form id="vs-visibility-form" class="vs-profile-form">
                            <div class="vs-visibility-grid">
                                <label><input type="checkbox" name="visible[]" value="contact_info" <?php checked($data['visibility']['contact_info']); ?>><?php echo esc_html__('Contact Info', 'vendor-space'); ?></label>
                                <label><input type="checkbox" name="visible[]" value="social_links" <?php checked($data['visibility']['social_links']); ?>><?php echo esc_html__('Social Media Links', 'vendor-space'); ?></label>
                                <label><input type="checkbox" name="visible[]" value="store_description" <?php checked($data['visibility']['store_description']); ?>><?php echo esc_html__('Store Description', 'vendor-space'); ?></label>
                                <label><input type="checkbox" name="visible[]" value="operating_hours" <?php checked($data['visibility']['operating_hours']); ?>><?php echo esc_html__('Operating Hours', 'vendor-space'); ?></label>
                            </div>
                            <div class="vs-form-actions">
                                <button type="submit" class="vs-btn vs-btn-primary"><?php echo esc_html__('Save Visibility', 'vendor-space'); ?></button>
                            </div>
                        </form>
                    </div>

                   
                    
                </div>
            </div>

            <?php if ($verify_notice === 'success'): ?>
                <div class="vs-profile-alert is-success"><?php echo esc_html__('Email verified successfully.', 'vendor-space'); ?></div>
            <?php elseif ($verify_notice === 'failed'): ?>
                <div class="vs-profile-alert is-error"><?php echo esc_html__('Verification link is invalid or expired.', 'vendor-space'); ?></div>
            <?php endif; ?>
        </div>
<style>
/* ===== HEADER CARD ===== */
.vs-profile-header-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 50%, #f1f5f9 100%);
    border: 1px solid #e2e8f0;
    border-radius: 24px;
    padding: 32px;
    margin-bottom: 32px;
    display: grid;
    grid-template-columns: 1fr 1fr auto;
    gap: 32px;
    align-items: center;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
    position: relative;
    overflow: hidden;
}

.vs-profile-header-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg, #2563eb, #3b82f6, #60a5fa);
}

/* ===== USER PROFILE SECTION ===== */
.vs-user-profile-section {
    display: flex;
    align-items: center;
    gap: 20px;
}

.vs-user-avatar {
    position: relative;
}

.vs-avatar-img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 4px solid #ffffff;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    transition: transform 0.3s ease;
}

.vs-avatar-img:hover {
    transform: scale(1.05);
}

.vs-user-info {
    flex: 1;
}

.vs-user-name {
    margin: 0 0 4px 0;
    font-size: 24px;
    font-weight: 700;
    color: #1e293b;
    background: linear-gradient(135deg, #1e293b, #334155);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.vs-user-email {
    margin: 0 0 8px 0;
    color: #64748b;
    font-size: 16px;
    font-weight: 500;
}

.vs-user-badges {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.vs-badge-pro {
    background: linear-gradient(135deg, #fbbf24, #f59e0b);
    color: #92400e;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    box-shadow: 0 2px 8px rgba(251, 191, 36, 0.3);
}

/* ===== STORE PROFILE SECTION ===== */
.vs-store-profile-section {
    display: flex;
    align-items: center;
    gap: 16px;
}

.vs-store-logo {
    position: relative;
}

.vs-store-logo img {
    width: 64px;
    height: 64px;
    border-radius: 16px;
    border: 3px solid #2563eb;
    box-shadow: 0 4px 16px rgba(37, 99, 235, 0.2);
    transition: transform 0.3s ease;
}

.vs-store-logo img:hover {
    transform: scale(1.05);
}

.vs-logo-placeholder {
    width: 64px;
    height: 64px;
    border-radius: 16px;
    background: linear-gradient(135deg, #e2e8f0, #cbd5e1);
    display: flex;
    align-items: center;
    justify-content: center;
    color: #64748b;
    font-size: 32px;
    border: 2px solid #94a3b8;
}

.vs-store-info h3 {
    margin: 0 0 4px 0;
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
}

.vs-store-info p {
    margin: 0;
    color: #64748b;
    font-size: 14px;
    font-weight: 500;
}

/* ===== HEADER ACTIONS ===== */
.vs-header-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: flex-end;
}

.vs-btn-sm {
    padding: 8px 16px;
    font-size: 13px;
    font-weight: 600;
    border-radius: 20px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.vs-btn-sm .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.vs-icon-btn {
    width: 44px;
    height: 44px;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
    color: #64748b;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.vs-icon-btn:hover {
    background: linear-gradient(135deg, #e2e8f0, #cbd5e1);
    color: #475569;
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* ===== BADGES ===== */
.vs-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.vs-badge.is-success {
    background: #dcfce7;
    color: #166534;
}

.vs-badge.is-warning {
    background: #fef3c7;
    color: #92400e;
}

.vs-badge.is-info {
    background: #dbeafe;
    color: #1e40af;
}

.is-hidden {
    display: none !important;
}

/* ===== RESPONSIVE ===== */
@media (max-width: 1024px) {
    .vs-profile-header-card {
        grid-template-columns: 1fr;
        gap: 24px;
        text-align: center;
    }

    .vs-header-actions {
        align-items: center;
        flex-direction: row;
        justify-content: center;
    }
}

@media (max-width: 768px) {
    .vs-profile-header-card {
        padding: 24px;
        margin-bottom: 24px;
    }

    .vs-user-profile-section,
    .vs-store-profile-section {
        flex-direction: column;
        gap: 16px;
    }

    .vs-user-name {
        font-size: 20px;
    }

    .vs-store-info h3 {
        font-size: 18px;
    }

    .vs-header-actions {
        flex-direction: column;
        gap: 8px;
    }

    .vs-btn-sm {
        width: 100%;
        justify-content: center;
    }
}

/* ===== TABS ===== */
.vs-profile-tabs {
    display: flex;
    background: linear-gradient(135deg, #ffffff, #f8fafc);
    border-radius: 20px;
    padding: 6px;
    margin-bottom: 32px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.8);
    border: 1px solid #e2e8f0;
    position: relative;
}

.vs-profile-tabs::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    border-radius: 20px;
    padding: 1px;
    background: linear-gradient(135deg, #e2e8f0, #cbd5e1);
    mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
    mask-composite: exclude;
    -webkit-mask-composite: xor;
}

.vs-tab-btn {
    flex: 1;
    padding: 14px 24px;
    border: none;
    background: transparent;
    color: #64748b;
    font-weight: 600;
    font-size: 14px;
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
    position: relative;
    z-index: 1;
}

.vs-tab-btn.active {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #ffffff;
    box-shadow: 0 4px 16px rgba(37, 99, 235, 0.3);
    transform: translateY(-1px);
}

.vs-tab-btn:hover:not(.active) {
    background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
    color: #475569;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* ===== TAB CONTENT ===== */
.vs-tab-content {
    display: flex;
    flex-direction: column;
    gap: 32px;
}

.vs-tab-pane {
    display: none;
    animation: fadeIn 0.3s ease-in-out;
}

.vs-tab-pane.active {
    display: block;
}

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

/* ===== PROFILE CARDS ===== */
.vs-profile-card {
    background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 32px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
}

.vs-profile-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #2563eb, #3b82f6, #60a5fa);
}

.vs-profile-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12), 0 4px 16px rgba(0, 0, 0, 0.08);
}

.vs-profile-card h3 {
    margin: 0 0 24px 0;
    font-size: 20px;
    font-weight: 700;
    color: #1e293b;
    border-bottom: 2px solid #2563eb;
    padding-bottom: 12px;
    position: relative;
}

.vs-profile-card h3::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: 60px;
    height: 2px;
    background: linear-gradient(90deg, #2563eb, #60a5fa);
}

/* ===== FORM ACTIONS ===== */
.vs-form-actions {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
}

/* ===== BUTTONS ===== */
.vs-btn {
    padding: 12px 24px;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 600;
    border: 1px solid transparent;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    position: relative;
    overflow: hidden;
}

.vs-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
}

.vs-btn:hover::before {
    left: 100%;
}

.vs-btn-primary {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #ffffff;
    box-shadow: 0 4px 16px rgba(37, 99, 235, 0.3);
}

.vs-btn-primary:hover {
    background: linear-gradient(135deg, #1d4ed8, #2563eb);
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(37, 99, 235, 0.4);
}

.vs-btn-outline {
    background: linear-gradient(135deg, #ffffff, #f8fafc);
    color: #2563eb;
    border-color: #2563eb;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.vs-btn-outline:hover {
    background: linear-gradient(135deg, #2563eb, #3b82f6);
    color: #ffffff;
    transform: translateY(-1px);
    box-shadow: 0 4px 16px rgba(37, 99, 235, 0.3);
}

/* ===== FORMS ===== */
.vs-form-group {
    margin-bottom: 24px;
}

.vs-form-group label {
    display: block;
    font-weight: 600;
    color: #374151;
    margin-bottom: 8px;
    font-size: 14px;
}

.vs-form-group input[type="text"],
.vs-form-group input[type="email"],
.vs-form-group input[type="password"],
.vs-form-group input[type="url"],
.vs-form-group textarea,
.vs-form-group select {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: linear-gradient(135deg, #ffffff, #f8fafc);
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
}

.vs-form-group input[type="text"]:focus,
.vs-form-group input[type="email"]:focus,
.vs-form-group input[type="password"]:focus,
.vs-form-group input[type="url"]:focus,
.vs-form-group textarea:focus,
.vs-form-group select:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1), inset 0 1px 3px rgba(0, 0, 0, 0.1);
    outline: none;
    background: #ffffff;
}

.vs-form-group textarea {
    resize: vertical;
    min-height: 100px;
}

.vs-form-group select {
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 12px center;
    background-repeat: no-repeat;
    background-size: 16px;
    padding-right: 40px;
}

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

.vs-form-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    padding-top: 16px;
    border-top: 1px solid #e5e7eb;
    margin-top: 24px;
}

/* ===== CARDS ===== */
.vs-card {
    background: linear-gradient(135deg, #ffffff, #f8fafc);
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.vs-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #2563eb, #3b82f6, #60a5fa);
}

.vs-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.06);
}

.vs-card-header {
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e5e7eb;
}

.vs-card-title {
    margin: 0;
    font-size: 18px;
    font-weight: 700;
    color: #1e293b;
    background: linear-gradient(135deg, #1e293b, #334155);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.vs-card-subtitle {
    margin: 4px 0 0 0;
    color: #64748b;
    font-size: 14px;
    font-weight: 500;
}

/* ===== ALERTS ===== */
.vs-alert {
    padding: 16px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    gap: 12px;
    border: 1px solid;
    position: relative;
    overflow: hidden;
}

.vs-alert::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: currentColor;
}

.vs-alert-success {
    background: linear-gradient(135deg, #f0fdf4, #dcfce7);
    color: #166534;
    border-color: #bbf7d0;
}

.vs-alert-error {
    background: linear-gradient(135deg, #fef2f2, #fee2e2);
    color: #991b1b;
    border-color: #fecaca;
}

.vs-alert-warning {
    background: linear-gradient(135deg, #fffbeb, #fef3c7);
    color: #92400e;
    border-color: #fde68a;
}

.vs-alert-info {
    background: linear-gradient(135deg, #eff6ff, #dbeafe);
    color: #1e40af;
    border-color: #bfdbfe;
}

.vs-alert-icon {
    flex-shrink: 0;
    margin-top: 2px;
    font-size: 18px;
}

.vs-alert-content {
    flex: 1;
}

.vs-alert-title {
    font-weight: 600;
    margin-bottom: 4px;
}

.vs-alert-message {
    font-size: 14px;
    line-height: 1.5;
}

/* ===== LOADING STATES ===== */
.vs-loading {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;
}

.vs-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid #e5e7eb;
    border-top: 2px solid #2563eb;
    border-radius: 50%;
    animation: vs-spin 1s linear infinite;
}

@keyframes vs-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.vs-loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 16px;
    z-index: 10;
}

/* ===== ANIMATIONS ===== */
@keyframes vs-fade-in {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.vs-fade-in {
    animation: vs-fade-in 0.3s ease-out;
}

@keyframes vs-slide-in {
    from {
        opacity: 0;
        transform: translateX(-20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

.vs-slide-in {
    animation: vs-slide-in 0.4s ease-out;
}

/* ===== UTILITIES ===== */
.vs-text-center { text-align: center; }
.vs-text-left { text-align: left; }
.vs-text-right { text-align: right; }

.vs-mb-0 { margin-bottom: 0; }
.vs-mb-1 { margin-bottom: 8px; }
.vs-mb-2 { margin-bottom: 16px; }
.vs-mb-3 { margin-bottom: 24px; }
.vs-mb-4 { margin-bottom: 32px; }

.vs-mt-0 { margin-top: 0; }
.vs-mt-1 { margin-top: 8px; }
.vs-mt-2 { margin-top: 16px; }
.vs-mt-3 { margin-top: 24px; }
.vs-mt-4 { margin-top: 32px; }

.vs-hidden { display: none !important; }
.vs-block { display: block; }
.vs-inline-block { display: inline-block; }
.vs-flex { display: flex; }
.vs-inline-flex { display: inline-flex; }

.vs-items-center { align-items: center; }
.vs-justify-center { justify-content: center; }
.vs-justify-between { justify-content: space-between; }
.vs-justify-end { justify-content: flex-end; }

.vs-gap-1 { gap: 8px; }
.vs-gap-2 { gap: 16px; }
.vs-gap-3 { gap: 24px; }

.vs-p-1 { padding: 8px; }
.vs-p-2 { padding: 16px; }
.vs-p-3 { padding: 24px; }

.vs-rounded { border-radius: 8px; }
.vs-rounded-lg { border-radius: 12px; }
.vs-rounded-xl { border-radius: 16px; }

.vs-shadow { box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); }
.vs-shadow-lg { box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08); }
.vs-shadow-xl { box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12); }

/* ===== LIVE PREVIEW ===== */
.vs-live-preview-section {
    margin-bottom: 32px;
}

.vs-preview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
}

.vs-preview-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    background: linear-gradient(135deg, #1e293b, #334155);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.vs-preview-badge {
    background: linear-gradient(135deg, #10b981, #059669);
    color: #ffffff;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 4px 8px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}

.vs-banner-preview {
    position: relative;
    width: 100%;
    height: 300px;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
    border: 2px solid #e2e8f0;
}

.vs-banner-preview::after {
    content: '👁️ <?php echo esc_html__('Preview', 'vendor-space'); ?>';
    position: absolute;
    top: 12px;
    right: 12px;
    background: rgba(0, 0, 0, 0.7);
    color: #ffffff;
    font-size: 11px;
    font-weight: 600;
    padding: 4px 8px;
    border-radius: 8px;
    z-index: 2;
    backdrop-filter: blur(4px);
}

.vs-banner-image {
    width: 100%;
    height: 100%;
    position: relative;
}

.vs-banner-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    transition: opacity 0.3s ease;
}

.vs-banner-image img.fade-in {
    opacity: 0;
    animation: vs-fade-in 0.3s ease forwards;
}

.vs-banner-placeholder {
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed #cbd5e1;
}

.vs-banner-placeholder span {
    color: #64748b;
    font-size: 18px;
    font-weight: 500;
}

.vs-profile-overlay {
    position: absolute;
    bottom: 20px;
    left: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 12px 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.vs-profile-avatar-preview {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 3px solid #ffffff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.vs-profile-info-preview {
    flex: 1;
}

.vs-profile-info-preview h5 {
    margin: 0 0 2px 0;
    font-size: 16px;
    font-weight: 700;
    color: #1e293b;
}

.vs-profile-info-preview p {
    margin: 0;
    font-size: 12px;
    color: #64748b;
    font-weight: 500;
}

/* ===== RESPONSIVE FOR PREVIEW ===== */
@media (max-width: 768px) {
    .vs-banner-preview {
        height: 200px;
    }

    .vs-profile-overlay {
        bottom: 12px;
        left: 12px;
        padding: 8px 12px;
        gap: 8px;
    }

    .vs-profile-avatar-preview {
        width: 40px;
        height: 40px;
    }

    .vs-profile-info-preview h5 {
        font-size: 14px;
    }

    .vs-profile-info-preview p {
        font-size: 11px;
    }
}

/* ===== RESPONSIVE ===== */
@media (max-width: 768px) {
    .vs-profile-header-card {
        flex-direction: column;
        text-align: center;
        gap: 16px;
    }

    .vs-header-actions {
        justify-content: center;
    }

    .vs-profile-tabs {
        flex-direction: column;
    }

    .vs-form-grid {
        grid-template-columns: 1fr;
    }
}

/* ===== EXISTING STYLES ===== */
.vs-upload-label {
    display: block;
    font-weight: 600;
    margin-bottom: 8px;
    color: #1e293b;
}

.vs-store-upload-box {
    position: relative;
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    background: #f8fafc;
    padding: 25px;
    text-align: center;
    cursor: pointer;
    transition: all 0.25s ease;
    overflow: hidden;
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.vs-store-upload-box:hover {
    border-color: #2563eb;
    background: #f1f5ff;
}

.vs-store-upload-box input[type="file"] {
    position: absolute;
    top: 0; left: 0; width: 100%; height: 100%;
    opacity: 0;
    cursor: pointer;
    z-index: 2;
}

.vs-store-upload-placeholder {
    color: #64748b;
    font-size: 14px;
    z-index: 1;
}

.vs-store-media-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 8px;
    z-index: 1;
}

.vs-store-upload-remove {
    position: absolute;
    top: 6px;
    right: 6px;
    width: 26px;
    height: 26px;
    border: none;
    border-radius: 50%;
    background: #dc2626;
    color: #fff;
    font-size: 18px;
    line-height: 1;
    cursor: pointer;
    z-index: 5;
    display: flex;
    align-items: center;
    justify-content: center;
}

.vs-store-upload-remove.is-hidden {
    display: none;
}

.vs-store-upload-remove:hover {
    background: #b91c1c;
}

.is-hidden {
    display: none;
}

/* ===== FORM STYLES ===== */
.vs-profile-form {
    padding: 0;
}

.vs-form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
}

.vs-field {
    display: flex;
    flex-direction: column;
}

.vs-field.full {
    grid-column: 1 / -1;
}

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

.vs-field input,
.vs-field textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #d1d5db;
    border-radius: 10px;
    font-size: 14px;
    background: #fff;
    transition: all 0.2s ease;
}

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

.vs-field textarea {
    resize: vertical;
    min-height: 80px;
}

/* ===== VISIBILITY GRID ===== */
.vs-visibility-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
}

.vs-visibility-grid label {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.vs-visibility-grid label:hover {
    background: #f1f5f9;
    border-color: #cbd5e1;
}

.vs-visibility-grid input[type="checkbox"] {
    margin: 0;
}

/* ===== METRICS ===== */
.vs-metrics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}

.vs-metric-card {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    padding: 16px;
    text-align: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.vs-metric-card small {
    display: block;
    color: #64748b;
    font-size: 12px;
    font-weight: 500;
    margin-bottom: 4px;
    text-transform: uppercase;
}

.vs-metric-card strong {
    display: block;
    color: #1e293b;
    font-size: 18px;
    font-weight: 700;
}

/* ===== TWO COLUMN ===== */
.vs-profile-two-col {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    margin-top: 24px;
}

.vs-profile-two-col h4 {
    margin: 0 0 16px 0;
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
}

/* ===== TABLE ===== */
.vs-profile-table {
    width: 100%;
    border-collapse: collapse;
    background: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.vs-profile-table th,
.vs-profile-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #e2e8f0;
}

.vs-profile-table th {
    background: #f8fafc;
    font-weight: 600;
    color: #475569;
    font-size: 13px;
    text-transform: uppercase;
}

.vs-profile-table tbody tr:hover {
    background: #f8fafc;
}

/* ===== SIMPLE LIST ===== */
.vs-simple-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.vs-simple-list li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #e2e8f0;
}

.vs-simple-list li:last-child {
    border-bottom: none;
}

.vs-simple-list li span {
    color: #475569;
}

.vs-simple-list li strong {
    color: #1e293b;
    font-weight: 600;
}

/* ===== ALERTS ===== */
.vs-profile-alert {
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;
    font-weight: 500;
}

.vs-profile-alert.is-success {
    background: #dcfce7;
    color: #166534;
    border: 1px solid #bbf7d0;
}

.vs-profile-alert.is-error {
    background: #fef2f2;
    color: #991b1b;
    border: 1px solid #fecaca;
}

/* Button spinner */
.vs-btn .vs-spinner {
    display: inline-block;
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255,255,255,0.2);
    border-top-color: #fff;
    border-radius: 50%;
    animation: vs-spin 0.8s linear infinite;
    vertical-align: middle;
    margin-left: 8px;
}

@keyframes vs-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

/* ===== HELP INLINE ===== */
.vs-help-inline {
    font-size: 12px;
    color: #64748b;
    margin-top: 4px;
}
</style>
<script>
(function(){
    const ajaxurl = (window.vs_vars && vs_vars.ajaxurl) ? vs_vars.ajaxurl : '<?php echo esc_url(admin_url("admin-ajax.php")); ?>';
    const vs_nonce = (window.vs_vars && vs_vars.nonce) ? vs_vars.nonce : '<?php echo wp_create_nonce("vs_nonce"); ?>';
    document.addEventListener('DOMContentLoaded', function() {
    const tabBtns = document.querySelectorAll('.vs-tab-btn');
    const tabPanes = document.querySelectorAll('.vs-tab-pane');

    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const tabName = btn.dataset.tab;

            // Remove active class from all buttons and panes
            tabBtns.forEach(b => b.classList.remove('active'));
            tabPanes.forEach(p => p.classList.remove('active'));

            // Add active class to clicked button and corresponding pane
            btn.classList.add('active');
            document.getElementById('tab-' + tabName).classList.add('active');
        });
    });

    // Form submissions
    const accountForm = document.getElementById('vs-account-form');
    const storeForm = document.getElementById('vs-store-form');
    const visibilityForm = document.getElementById('vs-visibility-form');

    // Buttons that may or may not exist on the page
    const sendResetBtn = document.getElementById('vs-send-reset-email');

    const useDashboardHandlers = !!window.vsDashboardProfileHandlers;

    if (accountForm && !useDashboardHandlers) {
        accountForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const newPassword = document.getElementById('vs-account-password').value;
            const passwordOtpWrap = document.getElementById('vs-password-otp-wrap');
            const passwordOtpInput = document.getElementById('vs-password-otp');
            
            if (newPassword && !passwordOtpWrap.classList.contains('vs-otp-sent')) {
                submitAjaxForm(this, 'vs_profile_save_account');
            } else if (newPassword && passwordOtpWrap.classList.contains('vs-otp-sent') && !passwordOtpInput.value) {
                alert('<?php echo esc_attr__('Please enter the OTP code sent to your email.', 'vendor-space'); ?>');
            } else {
                submitAjaxForm(this, 'vs_profile_save_account');
            }
        });
    }

    if (storeForm && !useDashboardHandlers) {
        storeForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitAjaxForm(this, 'vs_profile_save_store', true); // true for multipart
        });
    }

    if (visibilityForm && !useDashboardHandlers) {
        visibilityForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitAjaxForm(this, 'vs_profile_save_visibility');
        });
    }

    // Branding and Social Links forms (they use the same handler as store)
    const brandingForm = document.getElementById('vs-branding-form');
    const socialForm = document.getElementById('vs-social-form');

    if (brandingForm) {
        brandingForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitAjaxForm(this, 'vs_profile_save_store', true);
        });
    }

    if (socialForm) {
        socialForm.addEventListener('submit', function(e) {
            e.preventDefault();
            submitAjaxForm(this, 'vs_profile_save_store');
        });
    }

    function submitAjaxForm(form, action, isMultipart = false) {
        const formData = new FormData(form);
        formData.set('action', action);
        formData.set('security', vs_nonce);

        // Sync store_name from master info tab if not present or empty in current form
        if (!formData.get('store_name')) {
            const masterNameField = document.getElementById('vs-store-name-profile');
            if (masterNameField && masterNameField.value) {
                formData.set('store_name', masterNameField.value);
            }
        }

        // UI: find submit button and alert container
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalBtnHtml = submitBtn ? submitBtn.innerHTML : null; //نحفظ شكل الزر الأصلي
        let alertBox = form.querySelector('.vs-profile-alert');
        if (!alertBox) {
            alertBox = document.createElement('div');
            alertBox.className = 'vs-profile-alert';
            form.insertBefore(alertBox, form.querySelector('.vs-form-actions'));
        }

        const showAlert = (message, type = 'success') => {
            alertBox.textContent = message;
            alertBox.classList.remove('is-success', 'is-error');
            alertBox.classList.add(type === 'success' ? 'is-success' : 'is-error');
            alertBox.style.display = 'block';
        };

        const clearAlert = () => {
            alertBox.textContent = '';
            alertBox.style.display = 'none';
        };

        // Disable button + spinner
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.classList.add('vs-btn-disabled');
            submitBtn.innerHTML = (originalBtnHtml || '') + ' <span class="vs-spinner"></span>';
        }

        clearAlert();

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            return response.text().then(text => ({ status: response.status, ok: response.ok, text }));
        })
        .then(({ status, ok, text }) => {
            let parsed = null;
            try {
                parsed = text ? JSON.parse(text) : null;
            } catch (e) {
                parsed = null;
            }

            if (parsed && parsed.success) {
                const data = parsed.data;
                if (data && data.otp_required) {
                    // Handle OTP required (Email or Password)
                    if (data.otp_type === 'password') {
                        const pwWrap = document.getElementById('vs-password-otp-wrap');
                        if (pwWrap) {
                            pwWrap.classList.add('vs-otp-sent');
                            pwWrap.style.display = 'block';
                            const pwInput = document.getElementById('vs-password-otp');
                            if (pwInput) pwInput.focus();
                        }
                    } else {
                        // Email OTP
                        const emailWrap = document.getElementById('vs-account-email-otp-wrap');
                        if (emailWrap) {
                            emailWrap.style.display = 'block';
                            const emailInput = document.getElementById('vs-account-email-otp');
                            if (emailInput) emailInput.focus();
                        }
                    }
                    showAlert(data.message || '<?php echo esc_js(__('OTP code required', 'vendor-space')); ?>', 'success');
                } else {
                    showAlert(data && data.message ? data.message : '<?php echo esc_js(__('Saved successfully', 'vendor-space')); ?>', 'success');
                    
                    // Update UI dynamically without reload
                    if (action === 'vs_profile_save_account') {
                        // Update Header
                        const dnInput = document.getElementById('vs-account-display-name');
                        const emailInput = document.getElementById('vs-account-email');
                        const usernameInput = document.getElementById('vs-account-username');
                        
                        if (dnInput) {
                            const headerName = document.querySelector('.vs-profile-info h3');
                            if (headerName) headerName.textContent = dnInput.value || usernameInput.value;
                        }
                        if (emailInput) {
                            const headerEmail = document.querySelector('.vs-profile-info p');
                            if (headerEmail) headerEmail.textContent = emailInput.value;
                        }

                        // Hide OTP sections
                        const emailOtpWrap = document.getElementById('vs-account-email-otp-wrap');
                        const passwordOtpWrap = document.getElementById('vs-password-otp-wrap');
                        if (emailOtpWrap) emailOtpWrap.style.display = 'none';
                        if (passwordOtpWrap) {
                            passwordOtpWrap.style.display = 'none';
                            passwordOtpWrap.classList.remove('vs-otp-sent');
                        }
                        
                        // Clear password bits
                        const pwInput = document.getElementById('vs-account-password');
                        const pwConfirmInput = document.getElementById('vs-account-password-confirm');
                        if (pwInput) pwInput.value = '';
                        if (pwConfirmInput) pwConfirmInput.value = '';
                    }
                    
                    // Keep the alert for 3 seconds then hide it
                    setTimeout(() => clearAlert(), 3000);
                }
                return;
            }

            // Not a successful JSON response — show useful error info
            let errMsg = '<?php echo esc_js(__('An error occurred', 'vendor-space')); ?>';
            if (parsed && parsed.data) {
                errMsg = parsed.data;
            } else if (text) {
                // try to extract message from HTML or raw text
                errMsg = text.length > 500 ? text.substring(0, 500) + '...' : text;
            } else {
                errMsg = '<?php echo esc_js(__('Empty response from server', 'vendor-space')); ?> (status ' + status + ')';
            }
            console.error('AJAX error response:', status, text);
            showAlert(errMsg, 'error');
        })
        .catch(error => {
            console.error('Fetch error:', error);
            showAlert('<?php echo esc_js(__('An error occurred while saving', 'vendor-space')); ?>: ' + (error && error.message ? error.message : ''), 'error');
        })
        .finally(() => {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.classList.remove('vs-btn-disabled');
                if (originalBtnHtml !== null) submitBtn.innerHTML = originalBtnHtml;
            }
        });
    }

    // File upload handling
    const uploadBoxes = document.querySelectorAll('.vs-store-upload-box');

    uploadBoxes.forEach(box => {
        const input = box.querySelector('input[type="file"]');
        const removeInput = box.querySelector('input[type="hidden"]');
        const removeBtn = box.querySelector('.vs-store-upload-remove');
        const placeholderText = box.dataset.placeholder || 'Click to upload';

        if (!input) return;

        const clearPreview = () => {
            box.querySelectorAll('.vs-store-media-preview, .vs-store-upload-placeholder, .vs-store-upload-filename').forEach(el => el.remove());
        };

        const addPlaceholder = () => {
            const span = document.createElement('span');
            span.className = 'vs-store-upload-placeholder';
            span.textContent = placeholderText;
            box.appendChild(span);
        };

        const setRemoveButtonVisibility = (visible) => {
            if (!removeBtn) return;
            removeBtn.classList.toggle('is-hidden', !visible);
        };

        input.addEventListener('change', () => {
            if (!input.files || !input.files.length) return;

            clearPreview();

            Array.from(input.files).forEach(file => {
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = e => {
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.className = 'vs-store-media-preview';
                        box.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                } else {
                    const span = document.createElement('span');
                    span.className = 'vs-store-upload-filename';
                    span.textContent = file.name;
                    box.appendChild(span);
                }
            });

            if (removeInput) removeInput.value = '0';
            setRemoveButtonVisibility(true);
        });

        if (removeBtn) {
            removeBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                input.value = '';
                clearPreview();
                addPlaceholder();

                if (removeInput) removeInput.value = '1';
                setRemoveButtonVisibility(false);
            });
        }
    });

    // Live Preview Updates
    const bannerInput = document.getElementById('vs-store-banner');
    const bannerPreview = document.getElementById('vs-banner-preview');

    if (bannerInput && bannerPreview) {
        bannerInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    // Remove placeholder if exists
                    const placeholder = bannerPreview.querySelector('.vs-banner-placeholder');
                    if (placeholder) placeholder.remove();

                    // Remove existing image if exists
                    const existingImg = bannerPreview.querySelector('img');
                    if (existingImg) existingImg.remove();

                    // Add new image
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.alt = 'Store Banner';
                    img.classList.add('fade-in');
                    bannerPreview.appendChild(img);
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    }

    // Handle banner removal for live preview
    const bannerRemoveBtn = document.querySelector('#vs-store-banner').closest('.vs-store-upload-box').querySelector('.vs-store-upload-remove');
    if (bannerRemoveBtn && bannerPreview) {
        bannerRemoveBtn.addEventListener('click', function() {
            // Remove existing image
            const existingImg = bannerPreview.querySelector('img');
            if (existingImg) existingImg.remove();

            // Add placeholder back
            const placeholder = document.createElement('div');
            placeholder.className = 'vs-banner-placeholder';
            placeholder.innerHTML = '<span><?php echo esc_html__('Banner Preview', 'vendor-space'); ?></span>';
            bannerPreview.appendChild(placeholder);
        });
    }

    // Update profile preview when user data changes (if needed)
    // This could be extended to update profile info in real-time

   

    if (sendResetBtn && !useDashboardHandlers) {
        sendResetBtn.addEventListener('click', function() {
            fetch(ajaxurl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    action: 'vs_profile_send_reset',
                    security: vs_nonce
                })
            })
            .then(response => response.json())
            .then(data => {
                alert(data.success ? data.data.message : (data.data || 'Error'));
            });
        });
    }

   
    });
})();
</script>
        <?php
        return ob_get_clean();
    }

    public static function save_account_ajax() {
        if (ob_get_length()) {
            ob_clean();
        }

        if (!check_ajax_referer('vs_nonce', 'security', false)) {
            wp_send_json_error(__('Session expired. Please refresh the page and try again.', 'vendor-space'));
        }
        
        self::assert_vendor_or_die();

        $user_id = get_current_user_id();
        $user = get_userdata($user_id);
        if (!$user) {
            wp_send_json_error(__('User not found.', 'vendor-space'));
        }

        // 1. Gather all fields
        $username = sanitize_user(wp_unslash($_POST['username'] ?? ''), true);
        $email = sanitize_email(wp_unslash($_POST['email'] ?? ''));
        $otp_raw = trim((string) wp_unslash($_POST['otp'] ?? $_POST['email_otp'] ?? ''));
        // Normalize Arabic/Persian digits to Western digits
        $western_digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
        $arabic_digits = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
        $persian_digits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
        $otp = str_replace($arabic_digits, $western_digits, $otp_raw);
        $otp = str_replace($persian_digits, $western_digits, $otp);
        $new_password = (string) wp_unslash($_POST['new_password'] ?? '');
        $confirm_password = (string) wp_unslash($_POST['confirm_password'] ?? '');
        $display_name = sanitize_text_field(wp_unslash($_POST['display_name'] ?? ''));
        $first_name = sanitize_text_field(wp_unslash($_POST['first_name'] ?? ''));
        $last_name = sanitize_text_field(wp_unslash($_POST['last_name'] ?? ''));
        $address = sanitize_text_field(wp_unslash($_POST['address'] ?? ''));
        $country = sanitize_text_field(wp_unslash($_POST['country'] ?? ''));
        $city = sanitize_text_field(wp_unslash($_POST['city'] ?? ''));

        // 2. Initial Basic Validation
        if ($username === '') {
            wp_send_json_error(__('Username is required.', 'vendor-space'));
        }
        if ($email === '' || !is_email($email)) {
            wp_send_json_error(__('A valid email is required.', 'vendor-space'));
        }

        $pending_key = 'vs_profile_update_otp_' . $user_id;
        $current_address = (string) get_user_meta($user_id, 'billing_address_1', true);
        $current_country = (string) get_user_meta($user_id, 'billing_country', true);
        $current_city = (string) get_user_meta($user_id, 'billing_city', true);

        $email_changed = strcasecmp($email, (string) $user->user_email) !== 0;
        $username_changed = ($username !== $user->user_login);
        $password_changed = ($new_password !== '');
        $display_name_changed = ($display_name !== (string) $user->display_name);
        $first_name_changed = ($first_name !== (string) $user->first_name);
        $last_name_changed = ($last_name !== (string) $user->last_name);
        $address_changed = ($address !== $current_address);
        $country_changed = ($country !== $current_country);
        $city_changed = ($city !== $current_city);

        $changed = [];//append changed fields
        if ($username_changed) {
            $changed[] = 'username';
        }
        if ($email_changed) {
            $changed[] = 'email';
        }
        if ($password_changed) {
            $changed[] = 'password';
        }
        if ($display_name_changed) {
            $changed[] = 'display_name';
        }
        if ($first_name_changed) {
            $changed[] = 'first_name';
        }
        if ($last_name_changed) {
            $changed[] = 'last_name';
        }
        if ($address_changed) {
            $changed[] = 'address';
        }
        if ($country_changed) {
            $changed[] = 'country';
        }
        if ($city_changed) {
            $changed[] = 'city';
        }

        if (!$changed) {
            wp_send_json_success([
                'message' => __('No account changes detected.', 'vendor-space'),
                'changed' => [],
            ]);
        }

        // 3. Sensitive Data Validation
        if ($username_changed) {
            $exists = username_exists($username);
            if ($exists && (int) $exists !== (int) $user_id) {
                wp_send_json_error(__('Username already exists.', 'vendor-space'));
            }
        }
       if ($email_changed) {

    $existing_user_id = email_exists($email);

    if ($existing_user_id && (int) $existing_user_id !== (int) $user_id) {

        wp_send_json_error([
            'message' => __('This email address is already registered.', 'vendor-space')
        ]);
    }
}
        if ($password_changed) {
            if (strlen($new_password) < 8) {
                wp_send_json_error(__('Password must be at least 8 characters.', 'vendor-space'));
            }
            if ($new_password !== $confirm_password) {
                wp_send_json_error(__('Passwords do not match.', 'vendor-space'));
            }
        }

        

        // 4. Smart OTP Flow
        $sensitive_change = $email_changed || $password_changed;

        if (!$sensitive_change) {
            $update_data = ['ID' => $user_id];
            if ($display_name_changed) {
                $update_data['display_name'] = $display_name;
            }
            if ($first_name_changed) {
                $update_data['first_name'] = $first_name;
            }
            if ($last_name_changed) {
                $update_data['last_name'] = $last_name;
            }

            if (count($update_data) > 1) {
                $result = wp_update_user($update_data);
                if (is_wp_error($result)) {
                    wp_send_json_error($result->get_error_message());
                }
            }

            if ($username_changed) {
                global $wpdb;
                $username_result = $wpdb->update(
                    $wpdb->users,
                    ['user_login' => $username, 'user_nicename' => sanitize_title($username)],
                    ['ID' => $user_id]
                );

                if ($username_result === false) {
                    wp_send_json_error(__('Failed to update username.', 'vendor-space'));
                }

                clean_user_cache($user_id);
                wp_set_current_user($user_id);
                wp_set_auth_cookie($user_id, true, is_ssl());
            }

            if ($address_changed) {
                update_user_meta($user_id, 'billing_address_1', $address);
            }
            if ($country_changed) {
                update_user_meta($user_id, 'billing_country', $country);
            }
            if ($city_changed) {
                update_user_meta($user_id, 'billing_city', $city);
            }

            delete_transient($pending_key);
            clean_user_cache($user_id);

            wp_send_json_success([
                'message' => __('Account updated successfully.', 'vendor-space'),
                'changed' => $changed,
                'account' => [
                    'display_name' => $display_name,
                    'email' => (string) $user->user_email,
                    'username' => $username,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'address' => $address,
                    'country' => $country,
                    'city' => $city,
                ],
            ]);
        }

        // If OTP is required but not provided, send it
        if ($otp === '') {
            $existing_pending = get_transient($pending_key);
            if (is_array($existing_pending) && !empty($existing_pending['expires']) && time() <= (int) $existing_pending['expires']) {
                $same_request =
                    (string) ($existing_pending['username'] ?? '') === $username
                    && (string) ($existing_pending['email'] ?? '') === $email
                    && (string) ($existing_pending['display_name'] ?? '') === $display_name
                    && (string) ($existing_pending['first_name'] ?? '') === $first_name
                    && (string) ($existing_pending['last_name'] ?? '') === $last_name
                    && (string) ($existing_pending['address'] ?? '') === $address
                    && (string) ($existing_pending['country'] ?? '') === $country
                    && (string) ($existing_pending['city'] ?? '') === $city
                    && (string) ($existing_pending['new_password'] ?? '') === $new_password
                    && (string) ($existing_pending['confirm_password'] ?? '') === $confirm_password;

                if ($same_request) {
                    $recipient = $email_changed ? $email : (string) $user->user_email;

                    wp_send_json_success([
                        'otp_required' => true,
                        'message' => $email_changed ? __('A 4-digit code has already been sent to your new email.', 'vendor-space') : __('A 4-digit code has already been sent to your email.', 'vendor-space'),
                        'email' => $recipient,
                        'changed' => $changed,
                    ]);
                }
            }

            $code = (string) random_int(1000, 9999);
            $expiry = time() + (10 * MINUTE_IN_SECONDS);
            
            // Store pending data in a transient
            $pending_data = [
                'user_id' => $user_id,
                'username' => $username,
                'email' => $email,
                'display_name' => $display_name,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'address' => $address,
                'country' => $country,
                'city' => $city,
                'new_password' => $new_password,
                'confirm_password' => $confirm_password,
                'otp_hash' => wp_hash($code),
                'expires' => $expiry,
            ];
            
            set_transient($pending_key, $pending_data, 10 * MINUTE_IN_SECONDS);
            
            $recipient = ($email_changed) ? $email : $user->user_email;

            // Send OTP to the target email
            $subject = sprintf(__('[%s] Account Verification Code', 'vendor-space'), get_bloginfo('name'));
            $message = '
            <div style="background:#f4f7fb;padding:32px 16px;font-family:Arial,Helvetica,sans-serif;">
                <div style="max-width:480px;margin:0 auto;background:#ffffff;border-radius:20px;padding:32px;box-shadow:0 10px 40px rgba(15,23,42,0.08);border:1px solid #e5e7eb;text-align:center;">
                    <h2 style="margin:0 0 10px;font-size:24px;color:#0f172a;">' . ($email_changed ? esc_html__('Verify your new email', 'vendor-space') : esc_html__('Confirm your changes', 'vendor-space')) . '</h2>
                    <p style="margin:0;font-size:15px;color:#475569;line-height:1.6;">' . esc_html__('Enter the code below in the vendor dashboard to save your account settings.', 'vendor-space') . '</p>
                    <div style="margin:32px 0;">
                        <span style="display:inline-block;padding:16px 24px;background:#2563eb;color:#ffffff;font-size:32px;font-weight:700;letter-spacing:8px;border-radius:12px;">' . esc_html($code) . '</span>
                    </div>
                </div>
            </div>';

            $headers = ['Content-Type: text/html; charset=UTF-8'];
            
            if (!wp_mail($recipient, $subject, $message, $headers)) {
                wp_send_json_error(__('Failed to send verification email. Please check your SMTP settings.', 'vendor-space'));
            }

            wp_send_json_success([
                'otp_required' => true,
                'message' => $email_changed ? __('A 4-digit code has been sent to your new email.', 'vendor-space') : __('A 4-digit code has been sent to your email.', 'vendor-space'),
                'email' => $recipient,
                'changed' => $changed,
            ]);
        }

        // 5. Validate Provided OTP
        $pending = get_transient($pending_key);
        if (!$pending) {
            wp_send_json_error(__('Verification session expired. Please save again to receive a new code.', 'vendor-space'));
        }

        if (time() > (int)$pending['expires']) {
            delete_transient($pending_key);
            wp_send_json_error(__('Verification code expired. Please request a new one.', 'vendor-space'));
        }

        if (!hash_equals($pending['otp_hash'], wp_hash($otp))) {
            wp_send_json_error(__('Invalid verification code.', 'vendor-space'));
        }

        // 6. Apply All Changes
        $pending_matches_request =
            (string) ($pending['username'] ?? '') === $username
            && (string) ($pending['email'] ?? '') === $email
            && (string) ($pending['display_name'] ?? '') === $display_name
            && (string) ($pending['first_name'] ?? '') === $first_name
            && (string) ($pending['last_name'] ?? '') === $last_name
            && (string) ($pending['address'] ?? '') === $address
            && (string) ($pending['country'] ?? '') === $country
            && (string) ($pending['city'] ?? '') === $city
            && (string) ($pending['new_password'] ?? '') === $new_password
            && (string) ($pending['confirm_password'] ?? '') === $confirm_password;

        if (!$pending_matches_request) {
            wp_send_json_error(__('Your account details changed after the code was sent. Please save again to receive a new code.', 'vendor-space'));
        }

        // Consolidate updates
        $update_data = [
            'ID'           => $user_id,
            'display_name' => $pending['display_name'],
            'first_name'   => $pending['first_name'],
            'last_name'    => $pending['last_name'],
        ];

        if (strcasecmp($pending['email'], (string)$user->user_email) !== 0) {
            $update_data['user_email'] = $pending['email'];
        }

        $result = wp_update_user($update_data);
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        // Apply Username
        if ($pending['username'] !== $user->user_login) {
            global $wpdb;
            $username_result = $wpdb->update(
                $wpdb->users,
                ['user_login' => $pending['username'], 'user_nicename' => sanitize_title($pending['username'])],
                ['ID' => $user_id]
            );

            if ($username_result === false) {
                wp_send_json_error(__('Failed to update username.', 'vendor-space'));
            }

            if ($pending['new_password'] === '') {
                clean_user_cache($user_id);
                wp_set_current_user($user_id);
                wp_set_auth_cookie($user_id, true, is_ssl());
            }
        }

        // Apply Password
        if ($pending['new_password'] !== '') {
            wp_set_password($pending['new_password'], $user_id);
            wp_set_auth_cookie($user_id, true, is_ssl());
        }

        // Meta Fields
        update_user_meta($user_id, 'billing_address_1', $pending['address']);
        update_user_meta($user_id, 'billing_country', $pending['country']);
        update_user_meta($user_id, 'billing_city', $pending['city']);
        
        delete_transient($pending_key);
        clean_user_cache($user_id);

        wp_send_json_success([
            'message' => __('Account updated successfully.', 'vendor-space'),
            'changed' => $changed,
            'account' => [
                'display_name' => $pending['display_name'],
                'email'        => $pending['email'],
                'username'     => $pending['username'],
                'first_name'   => $pending['first_name'],
                'last_name'    => $pending['last_name'],
                'address'      => $pending['address'],
                'country'      => $pending['country'],
                'city'         => $pending['city'],
            ],
        ]);
    }

    public static function check_email_ajax() {

    check_ajax_referer('vs_nonce', 'security');

    $user_id = get_current_user_id();
    $email   = sanitize_email(wp_unslash($_POST['email'] ?? ''));

    // 1. Validation أساسي
    if (empty($email) || !is_email($email)) {
        wp_send_json_error([
            'message' => 'Invalid email address.'
        ]);
    }

    $current_user = wp_get_current_user();

    // 2. إذا نفس الإيميل الحالي → مسموح
    if ($current_user->exists() && strcasecmp($email, $current_user->user_email) === 0) {
        wp_send_json_success([
            'available' => true,
            'message'   => ''
        ]);
    }

    /**
     * 3. التحقق الحقيقي من وجود الإيميل
     * WooCommerce و WordPress يستخدمون نفس المصدر (users table)
     */
    $existing_user_id = email_exists($email);

    if ($existing_user_id && (int) $existing_user_id !== (int) $user_id) {

        wp_send_json_error([
            'message' => __('An account is already registered with this email address.', 'vendor-space')
        ]);
    }

    // 4. (اختياري) دعم WooCommerce customers API
    if (function_exists('wc_get_customer_id_by_email')) {

        $wc_user_id = wc_get_customer_id_by_email($email);

        if ($wc_user_id && (int) $wc_user_id !== (int) $user_id) {

            wp_send_json_error([
                'message' => __('This email is already registered (WooCommerce).', 'vendor-space')
            ]);
        }
    }

    // 5. إذا وصل هنا → الإيميل متاح
    wp_send_json_success([
        'available' => true,
        'message'   => __('Email is available.', 'vendor-space')
    ]);
}
    public static function send_reset_ajax() {
        check_ajax_referer('vs_nonce', 'security');
        self::assert_vendor_or_die();

        $user = wp_get_current_user();
        $result = retrieve_password($user->user_login);

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }
        wp_send_json_success([
            'message' => __('Password reset email sent.', 'vendor-space'),
        ]);
    }

   
    private static function clear_pending_email_change($user_id) {
        delete_user_meta($user_id, self::EMAIL_CHANGE_PENDING_META);
        delete_user_meta($user_id, self::EMAIL_CHANGE_OTP_META);
        delete_user_meta($user_id, self::EMAIL_CHANGE_OTP_EXPIRY_META);
    }

    private static function has_pending_email_change($user_id) {
        $pending_email = (string) get_user_meta($user_id, self::EMAIL_CHANGE_PENDING_META, true);
        $stored_hash = (string) get_user_meta($user_id, self::EMAIL_CHANGE_OTP_META, true);
        $expires_at = (int) get_user_meta($user_id, self::EMAIL_CHANGE_OTP_EXPIRY_META, true);

        if ($pending_email === '' || $stored_hash === '' || $expires_at <= 0) {
            return false;
        }

        if ($expires_at < time()) {
            self::clear_pending_email_change($user_id);
            return false;
        }

        return true;
    }

    public static function save_store_ajax() {
        if (!check_ajax_referer('vs_nonce', 'security', false)) {
            wp_send_json_error(__('Session expired. Please refresh the page.', 'vendor-space'));
        }
        self::assert_vendor_or_die();

        $user_id = get_current_user_id();
        $store_name = sanitize_text_field(wp_unslash($_POST['store_name'] ?? ''));

        if ($store_name === '') {
            $store_name = (string) get_user_meta($user_id, 'vs_store_name', true);
        }

        if ($store_name === '') {
            $user = get_userdata($user_id);
            $store_name = $user ? $user->display_name : '';
        }

        if ($store_name === '') {
            wp_send_json_error(__('Store name is required. Please set it in the Store Info tab.', 'vendor-space'));
        }

        $store = [
            'vs_store_name' => $store_name,
            'vs_store_location' => sanitize_text_field(wp_unslash($_POST['location'] ?? '')),
            'vs_store_desc' => sanitize_textarea_field(wp_unslash($_POST['description'] ?? '')),
            'vs_store_contact_phone' => sanitize_text_field(wp_unslash($_POST['contact_phone'] ?? '')),
            'vs_store_address' => sanitize_text_field(wp_unslash($_POST['address'] ?? '')),
            'vs_store_operating_hours' => sanitize_text_field(wp_unslash($_POST['operating_hours'] ?? '')),
        ];

        foreach ($store as $meta_key => $meta_value) {
            update_user_meta($user_id, $meta_key, $meta_value);
        }

        $social = [
            'facebook' => esc_url_raw(wp_unslash($_POST['social_facebook'] ?? '')),
            'instagram' => esc_url_raw(wp_unslash($_POST['social_instagram'] ?? '')),
            'x' => esc_url_raw(wp_unslash($_POST['social_x'] ?? '')),
            'linkedin' => esc_url_raw(wp_unslash($_POST['social_linkedin'] ?? '')),
            'youtube' => esc_url_raw(wp_unslash($_POST['social_youtube'] ?? '')),
        ];
        update_user_meta($user_id, 'vs_store_social_links', $social);

     
        $remove_logo = absint(wp_unslash($_POST['remove_store_logo'] ?? 0)) === 1;
        $remove_banner = absint(wp_unslash($_POST['remove_store_banner'] ?? 0)) === 1;

        if ($remove_logo) {
            delete_user_meta($user_id, 'vs_store_logo_id');
        }

        if ($remove_banner) {
            delete_user_meta($user_id, 'vs_store_banner_id');
        }

        // Branding files feature removed from UI.
        delete_user_meta($user_id, 'vs_store_files');

        if (!current_user_can('upload_files')) {
            wp_send_json_success(['message' => __('Store details saved (file upload not allowed for this account).', 'vendor-space')]);
        }

        if (!empty($_FILES['store_logo']['name']) || !empty($_FILES['store_banner']['name'])) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            require_once ABSPATH . 'wp-admin/includes/media.php';
            require_once ABSPATH . 'wp-admin/includes/image.php';
        }

        if (!empty($_FILES['store_logo']['name'])) {
            $logo_id = media_handle_upload('store_logo', 0);
            if (is_wp_error($logo_id)) {
                wp_send_json_error($logo_id->get_error_message());
            }
            update_user_meta($user_id, 'vs_store_logo_id', (int) $logo_id);
        }

        if (!empty($_FILES['store_banner']['name'])) {
            $banner_id = media_handle_upload('store_banner', 0);
            if (is_wp_error($banner_id)) {
                wp_send_json_error($banner_id->get_error_message());
            }
            update_user_meta($user_id, 'vs_store_banner_id', (int) $banner_id);
        }

        wp_send_json_success([
            'message' => __('Store settings updated successfully.', 'vendor-space'),
        ]);
    }

   
    public static function save_visibility_ajax() {
        if (!check_ajax_referer('vs_nonce', 'security', false)) {
            wp_send_json_error(__('Session expired. Please refresh the page.', 'vendor-space'));
        }
        self::assert_vendor_or_die();

        $visible = isset($_POST['visible']) ? (array) $_POST['visible'] : [];
        $allowed = ['contact_info', 'social_links', 'store_description', 'operating_hours'];
        $settings = [];

        foreach ($allowed as $field) {
            $settings[$field] = in_array($field, $visible, true);
        }

        update_user_meta(get_current_user_id(), 'vs_store_visibility', $settings);
        wp_send_json_success(['message' => __('Visibility settings saved.', 'vendor-space')]);
    }

    
   

    public static function keepalive_ajax() {
        check_ajax_referer('vs_nonce', 'security');
        if (!is_user_logged_in()) {
            wp_send_json_error(__('Session not active.', 'vendor-space'));
        }
        wp_send_json_success(['time' => current_time('mysql')]);
    }

    public static function handle_email_verification() {
        if (empty($_GET['vs_verify_email'])) {
            return;
        }

        $uid = absint($_GET['uid'] ?? 0);
        $token = sanitize_text_field(wp_unslash($_GET['token'] ?? ''));
        $status = 'failed';

        if ($uid && $token !== '') {
            $stored_hash = get_user_meta($uid, self::EMAIL_TOKEN_META, true);
            $expires_at = (int) get_user_meta($uid, self::EMAIL_EXPIRY_META, true);

            if ($stored_hash && $expires_at >= time() && hash_equals($stored_hash, wp_hash($token))) {
                delete_user_meta($uid, self::EMAIL_TOKEN_META);
                delete_user_meta($uid, self::EMAIL_EXPIRY_META);
                $status = 'success';
            }
        }

        wp_safe_redirect(add_query_arg('vs_verify', $status, self::get_dashboard_url()));
        exit;
    }

    public static function prevent_cache_dashboard() {
        if (!is_user_logged_in() || !is_page()) {
            return;
        }

        $page = get_queried_object();
        if (!$page || empty($page->post_name) || $page->post_name !== 'vendor-dashboard') {
            return;
        }

        if (!defined('DONOTCACHEPAGE')) {
            define('DONOTCACHEPAGE', true);
        }

        nocache_headers();
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    }

    public static function enqueue_vendor_custom_css() {
        if (!is_user_logged_in() || !self::is_vendor_user()) {
            return;
        }
        $css = (string) get_user_meta(get_current_user_id(), 'vs_store_custom_css', true);
        if (trim($css) === '') {
            return;
        }
        if (wp_style_is('vs-dashboard-css', 'enqueued')) {
            wp_add_inline_style('vs-dashboard-css', "\n/* Vendor custom css */\n" . $css);
        }
    }

    public static function render_shop_vendor_info() {
        if (!function_exists('wc_get_product')) {
            return;
        }

        global $product;
        if (!$product || !is_a($product, 'WC_Product')) {
            return;
        }

        $vendor_id = (int) get_post_field('post_author', $product->get_id());
        if (!$vendor_id || !self::is_vendor_user($vendor_id)) {
            return;
        }

        echo self::build_public_vendor_html($vendor_id, (int) $product->get_id(), true);
    }

    public static function render_single_vendor_info() {
        if (!function_exists('wc_get_product')) {
            return;
        }

        global $product;
        if (!$product || !is_a($product, 'WC_Product')) {
            return;
        }

        $vendor_id = (int) get_post_field('post_author', $product->get_id());
        if (!$vendor_id || !self::is_vendor_user($vendor_id)) {
            return;
        }

        echo self::build_public_vendor_html($vendor_id, (int) $product->get_id(), false);
    }

    private static function build_public_vendor_html($vendor_id, $product_id, $compact = true) {
        $vendor_user = get_userdata($vendor_id);
        if (!$vendor_user) {
            return '';
        }

        $visibility = get_user_meta($vendor_id, 'vs_store_visibility', true);
        if (!is_array($visibility)) {
            $visibility = [];
        }
        $visibility = wp_parse_args($visibility, [
            'contact_info' => true,
            'social_links' => true,
            'store_description' => true,
            'operating_hours' => true,
        ]);

        $store_name = (string) get_user_meta($vendor_id, 'vs_store_name', true);
        if ($store_name === '') {
            $store_name = $vendor_user->display_name;
        }

        $desc = (string) get_user_meta($vendor_id, 'vs_store_desc', true);
        if ($compact) {
            $desc = wp_trim_words(wp_strip_all_tags($desc), 14, '...');
        }

    
        $social = get_user_meta($vendor_id, 'vs_store_social_links', true);
        if (!is_array($social)) {
            $social = [];
        }
        $social = array_filter(array_map('esc_url', [
            'facebook' => $social['facebook'] ?? '',
            'instagram' => $social['instagram'] ?? '',
            'x' => $social['x'] ?? '',
            'linkedin' => $social['linkedin'] ?? '',
            'youtube' => $social['youtube'] ?? '',
        ]));

        ob_start();
        ?>
      
         


        <?php
        return ob_get_clean();
    }

    private static function build_profile_data($user_id) {
        $user = get_userdata($user_id);
        $social = get_user_meta($user_id, 'vs_store_social_links', true);
        if (!is_array($social)) {
            $social = [];
        }

        $visibility = get_user_meta($user_id, 'vs_store_visibility', true);
        if (!is_array($visibility)) {
            $visibility = [];
        }
        $visibility = wp_parse_args($visibility, [
            'contact_info' => true,
            'social_links' => true,
            'store_description' => true,
            'operating_hours' => true,
        ]);

        $files = [];
        $file_ids = get_user_meta($user_id, 'vs_store_files', true);
        if (is_array($file_ids)) {
            foreach ($file_ids as $file_id) {
                $url = wp_get_attachment_url((int) $file_id);
                if ($url) {
                    $files[] = [
                        'id' => (int) $file_id,
                        'name' => basename($url),
                        'url' => $url,
                    ];
                }
            }
        }

        $email_change_pending = self::has_pending_email_change($user_id);
        $pending_email = $email_change_pending ? (string) get_user_meta($user_id, self::EMAIL_CHANGE_PENDING_META, true) : '';

        return [
            'account' => [
                'username' => $user ? $user->user_login : '',
                'email' => $user ? $user->user_email : '',
                'display_name' => $user ? $user->display_name : '',
                'first_name' => $user ? $user->first_name : '',
                'last_name' => $user ? $user->last_name : '',
                'address' => (string) get_user_meta($user_id, 'billing_address_1', true),
                'country' => (string) get_user_meta($user_id, 'billing_country', true),
                'city' => (string) get_user_meta($user_id, 'billing_city', true),
                'email_change_pending' => $email_change_pending,
                'pending_email' => $pending_email,
            ],
            'store' => [
                'name' => (string) get_user_meta($user_id, 'vs_store_name', true),
                'description' => (string) get_user_meta($user_id, 'vs_store_desc', true),
                'location' => (string) get_user_meta($user_id, 'vs_store_location', true),
                'contact_phone' => (string) get_user_meta($user_id, 'vs_store_contact_phone', true),
                'address' => (string) get_user_meta($user_id, 'vs_store_address', true),
                'operating_hours' => (string) get_user_meta($user_id, 'vs_store_operating_hours', true),
                'social' => [
                    'facebook' => (string) ($social['facebook'] ?? ''),
                    'instagram' => (string) ($social['instagram'] ?? ''),
                    'x' => (string) ($social['x'] ?? ''),
                    'linkedin' => (string) ($social['linkedin'] ?? ''),
                    'youtube' => (string) ($social['youtube'] ?? ''),
                ],
                'logo_url' => wp_get_attachment_image_url((int) get_user_meta($user_id, 'vs_store_logo_id', true), 'thumbnail') ?: '',
                'banner_url' => wp_get_attachment_image_url((int) get_user_meta($user_id, 'vs_store_banner_id', true), 'medium') ?: '',
                'files' => $files,
                'custom_css' => (string) get_user_meta($user_id, 'vs_store_custom_css', true),
                'preview_url' => self::get_store_preview_url($user_id),
            ],
            'visibility' => $visibility,
        ];
    }

    public static function get_profile_data($user_id) {
    return self::build_profile_data($user_id);
}

  

    private static function get_store_preview_url($user_id) {
        $shop_url = get_post_type_archive_link('product');
        if (!$shop_url) {
            $shop_url = site_url('/shop/');
        }
        return add_query_arg('vendor', (int) $user_id, $shop_url);
    }

    private static function get_dashboard_url() {
        $page = get_page_by_path('vendor-dashboard');
        if ($page) {
            return get_permalink($page);
        }
        return site_url('/vendor-dashboard/');
    }

   

    private static function is_vendor_user($user_id = 0) {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        if (!$user_id) {
            return false;
        }
        if (user_can($user_id, 'administrator')) {
            return true;
        }
        return user_can($user_id, 'edit_products');
    }

    private static function assert_vendor_or_die() {
        if (!is_user_logged_in() || !self::is_vendor_user()) {
            wp_send_json_error(__('Permission denied.', 'vendor-space'));
        }
    }

    public static function render_otp_modal() {
        ?>
        <div class="vs-otp-overlay" id="vs-profile-otp-overlay" style="display:none;">
            <div class="vs-otp-card" id="vs-profile-otp-card">
                <button type="button" class="vs-otp-close" id="vs-profile-otp-close" aria-label="<?php echo esc_attr__('Close', 'vendor-space'); ?>">&times;</button>
                <div class="vs-otp-badge"><?php echo esc_html__('Verify it\'s you', 'vendor-space'); ?></div>
                <h2><?php echo esc_html__('Confirm Update', 'vendor-space'); ?></h2>
                <p class="vs-otp-subtitle">
                    <?php echo esc_html__('Enter the 4-digit code sent to your email address.', 'vendor-space'); ?>
                </p>

                <div class="vs-otp-inputs">
                    <?php for ($i = 0; $i < 4; $i++): ?>
                        <input type="text" inputmode="numeric" pattern="[0-9]*" maxlength="1" class="vs-otp-digit" data-index="<?php echo esc_attr((string) $i); ?>" autocomplete="one-time-code">
                    <?php endfor; ?>
                </div>

                <div class="vs-otp-message" id="vs-profile-otp-message" aria-live="polite"></div>

                <div class="vs-otp-actions">
                    <button type="submit" class="vs-btn vs-btn-primary" id="vs-profile-otp-verify">
                        <span><?php echo esc_html__('Verify & Save', 'vendor-space'); ?></span>
                    </button>
                    <button type="button" class="vs-btn vs-btn-outline" id="vs-profile-otp-cancel">
                        <span><?php echo esc_html__('Cancel', 'vendor-space'); ?></span>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }
}
