<?php
/**
 * Dynamic Checkout Template
 * Reads design settings from Impulse block when available,
 * falls back to CheckoutConfig for standalone usage.
 */

if (!defined('ABSPATH')) {
    exit;
}

// Read from Impulse block settings if available, else CheckoutConfig
$impulseSettings = $GLOBALS['impulse_checkout_settings'] ?? null;
// Free build: a CUSTOM checkout (configurable field grid + branded styling +
// layout) is Pro — the thing WooCommerce makes people buy plugins for. Strip the
// design customisation so the standard default checkout renders (the store still
// fully works: products, cart, Stripe). Pro keeps the full custom design.
if (is_array($impulseSettings) && function_exists('instinctor_locked') && instinctor_locked('custom_checkout')) {
    unset($impulseSettings['checkout_design']);
    foreach (array_keys($impulseSettings) as $_ck) {
        if (strpos((string) $_ck, 'checkout_design_') === 0) unset($impulseSettings[$_ck]);
    }
}
if ($impulseSettings) {
    $cd = $impulseSettings['checkout_design'] ?? [];
    $cdColors = $cd['colors'] ?? [];
    
    // Build $config from Store settings first, then element overrides
    $config = [
        'layout' => $cd['preset'] ?? ($impulseSettings['checkout_design_preset'] ?? 'one-page'),
        'style' => 'modern',
        'guest_checkout' => \Instinctor\Core\Config::get('instinctor_guest_checkout', true),
        'create_account_option' => \Instinctor\Core\Config::get('instinctor_create_account', true),
        'email_first' => \Instinctor\Core\Config::get('instinctor_email_first', true),
        'address_autocomplete' => $cd['address_autocomplete'] ?? false,
        'google_places_key' => $cd['google_places_key'] ?? '',
        'show_coupon' => \Instinctor\Core\Config::get('instinctor_show_coupon', true),
        'show_gift_card' => \Instinctor\Core\Config::get('instinctor_show_gift_card', true),
        'express_payments' => $cd['express_payments'] ?? ['enabled' => false, 'apple_pay' => false, 'google_pay' => false],
        'colors' => [
            'button' => $impulseSettings['checkout_design_button'] ?? ($cdColors['button'] ?? '#1d1d1f'),
            'button_text' => $impulseSettings['checkout_design_button_text'] ?? ($cdColors['button_text'] ?? '#ffffff'),
            'text' => $impulseSettings['checkout_design_text'] ?? ($cdColors['text'] ?? '#1d2327'),
            'secondary_text' => $cdColors['secondary_text'] ?? '#86868b',
            'form_bg' => $impulseSettings['checkout_design_form_bg'] ?? ($cdColors['form_bg'] ?? 'rgba(255,255,255,0.94)'),
            'field_bg' => $impulseSettings['checkout_design_field_bg'] ?? ($cdColors['field_bg'] ?? '#ffffff'),
            'field_border' => $impulseSettings['checkout_design_field_border'] ?? ($cdColors['field_border'] ?? '#d2d2d7'),
            'border' => $cdColors['border'] ?? '#d2d2d7',
        ],
        'field_border_width' => $impulseSettings['checkout_design_field_border_width'] ?? ($cd['field_border_width'] ?? 1),
        'field_radius' => $impulseSettings['checkout_design_field_radius'] ?? ($cd['field_radius'] ?? 4),
        'button_radius' => $impulseSettings['checkout_design_button_radius'] ?? ($cd['button_radius'] ?? 4),
    ];
    
    // Fields from Impulse
    $fieldsJson = $impulseSettings['checkout_design_fields'] ?? ($cd['fields'] ?? '');
    if (is_string($fieldsJson) && !empty($fieldsJson)) {
        $impulseFields = json_decode($fieldsJson, true);
    } elseif (is_array($fieldsJson)) {
        $impulseFields = $fieldsJson;
    } else {
        $impulseFields = null;
    }
    if (!empty($impulseFields)) {
        $fields = [];
        foreach ($impulseFields as $idx => $f) {
            $fid = $f['id'] ?? ('custom_' . $idx);
            $fields[$fid] = $f;
        }
    } else {
        $fields = \Instinctor\Services\CheckoutConfig::getFields();
    }
} else {
    // Standalone shortcode fallback
    $config = \Instinctor\Services\CheckoutConfig::get();
    $fields = \Instinctor\Services\CheckoutConfig::getFields();
}

$layout = $config['layout'] ?? 'one-page';
$style = $config['style'] ?? 'modern';

// Preview mode - hide admin bar
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only preview-mode toggle (compared === '1', not stored or output); no state change, so no nonce applies.
$isPreview = isset($_GET['instinctor_preview']) && $_GET['instinctor_preview'] === '1';
if ($isPreview) {
    add_filter('show_admin_bar', '__return_false');
}
$user = wp_get_current_user();

// Logged-in member context: identity + saved card on file. Used to streamline the
// form so a returning member doesn't re-enter info we already have.
$memberCtx = null;
if (is_user_logged_in()) {
    $__uid = \Instinctor\Core\Auth::userId();
    $__cust = $__uid ? \Instinctor\Core\DB::get_row(\Instinctor\Core\DB::prepare("SELECT * FROM `" . \Instinctor\Core\DB::prefix() . "instinctor_customers` WHERE user_id = %d LIMIT 1", $__uid)) : null;
    $__card = null; $__subId = null; $__activePids = [];
    if ($__cust) {
        $__sub = \Instinctor\Core\DB::get_row(\Instinctor\Core\DB::prepare("SELECT id FROM `" . \Instinctor\Core\DB::prefix() . "instinctor_subscriptions` WHERE customer_id = %d AND payment_method = 'authorizenet' ORDER BY id DESC LIMIT 1", $__cust->id));
        if ($__sub) { $__subId = (int) $__sub->id; $__card = \Instinctor\Services\SubscriptionService::instance()->getCardOnFile($__subId); }
        $__activeRows = \Instinctor\Core\DB::get_results(\Instinctor\Core\DB::prepare("SELECT DISTINCT product_id FROM `" . \Instinctor\Core\DB::prefix() . "instinctor_subscriptions` WHERE customer_id = %d AND status IN ('active','trialing','past_due')", $__cust->id));
        foreach ((array) $__activeRows as $__ar) { $__activePids[] = (int) ($__ar->product_id ?? 0); }
    }
    $__fn = (string) ($__cust->first_name ?? '');
    $__ln = (string) ($__cust->last_name ?? '');
    $memberCtx = [
        'email'           => (string) ($user->user_email ?? $user->email ?? ($__cust->email ?? '')),
        'first_name'      => $__fn,
        'last_name'       => $__ln,
        'phone'           => (string) ($__cust->phone ?? ''),
        'name'            => trim($__fn . ' ' . $__ln),
        'card'            => $__card,
        'subscription_id' => $__subId,
        'active_product_ids' => $__activePids,
    ];
}

// Get current currency
$currencyData = \Instinctor\Services\CurrencyService::getCurrentCurrency();

// Custom colors
$colors = $config['colors'] ?? [];
$btnColor = $colors['button'] ?? '#1d1d1f';
$btnTextColor = $colors['button_text'] ?? '#ffffff';
$secondaryTextColor = $colors['secondary_text'] ?? '#86868b';
$textColor = $colors['text'] ?? '#1d2327';
$formBgColor = $colors['form_bg'] ?? 'rgba(255,255,255,0.94)';
$fieldBgColor = $colors['field_bg'] ?? '#ffffff';
$fieldBorderColor = $colors['field_border'] ?? '#d2d2d7';
// Auto-contrast: field text color derived from field background (rgba falls back to form text)
$fieldTextColor = (strpos($fieldBgColor, 'rgba') !== false) ? $textColor : impulse_contrast_color($fieldBgColor);
$fieldBorderWidth = $config['field_border_width'] ?? '1';
// Screen mode: no field borders
// Screen mode keeps a 1px field border so inputs are visible on busy backgrounds.
$borderColor = $colors['border'] ?? '#d2d2d7';
$fieldRadius  = intval($config['field_radius']  ?? 6);
$buttonRadius = intval($config['button_radius'] ?? 6);
$fieldHeight  = intval($config['field_height']  ?? 44);
$fieldBg      = $fieldBgColor;

// Payment gateways
$stripe_key = get_option('instinctor_stripe_publishable_key', '');
$paypal_enabled = get_option('instinctor_paypal_enabled', false);
$paypal_client_id = get_option('instinctor_paypal_client_id', '');
$paypal_sandbox = get_option('instinctor_paypal_sandbox', true);
$currency = strtoupper(get_option('instinctor_currency', 'USD'));

$has_stripe = !empty($stripe_key);
$has_paypal = $paypal_enabled && !empty($paypal_client_id);
$an_api_login_id = get_option('instinctor_authorizenet_api_login_id', '');
$an_public_key   = get_option('instinctor_authorizenet_public_client_key', '');
$an_sandbox      = (bool) get_option('instinctor_authorizenet_sandbox', true);
$has_authorizenet = !empty($an_api_login_id) && !empty($an_public_key);
$has_payment = $has_stripe || $has_paypal || $has_authorizenet;

// Express payments
$express_enabled = $config['express_payments']['enabled'] ?? false;
$apple_pay = $config['express_payments']['apple_pay'] ?? false;
$google_pay = $config['express_payments']['google_pay'] ?? false;

// Address autocomplete
$autocomplete_enabled = $config['address_autocomplete'] ?? false;
$google_places_key = $config['google_places_key'] ?? '';

// Coupon and gift card
$show_coupon = $config['show_coupon'] ?? true;
$show_gift_card = $config['show_gift_card'] ?? true;
// Shipping only applies to stores that ship physical goods. Memberships/services/subscriptions/digital never ship.
$showShipping = in_array(\Instinctor\Core\StoreFeatures::getStoreType(), ['physical_goods', 'mixed'], true);
// Scheduled orders (restaurant vertical): a future pickup/delivery time. Stripped
// from the free build; never shown on any other store type.


// Check for cart recovery
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- recovery token validated inside recoverCart()
if (!empty($_GET['recover']) && class_exists('\\Instinctor\\Services\\AbandonedCartService')) {
    $abandonedService = new \Instinctor\Services\AbandonedCartService();
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Cart-recovery token is sanitize_text_field+wp_unslash'd and validated server-side inside recoverCart(); read-only recovery, no nonce applies.
    $abandonedService->recoverCart(sanitize_text_field(wp_unslash((string)($_GET['recover'] ?? ''))));
}

// Checkout upsells
$upsellService = \Instinctor\Services\UpsellService::instance();
$upsellSettings = $upsellService->getSettings();
$cartService = new \Instinctor\Services\CartService();
$cart = $cartService->getCart();

// A member with an active subscription to a product already in the cart can't buy it
// again. Show a "you're already a member" notice instead of the checkout form.
$memberAlreadySubscribed = false;
if (!empty($memberCtx['active_product_ids'])) {
    $__cartPids = array_filter(array_map(function ($it) { return (int) ($it['product_id'] ?? 0); }, $cart['items'] ?? []));
    $memberAlreadySubscribed = !empty(array_intersect($memberCtx['active_product_ids'], $__cartPids));
}

// Group enabled fields by section
$sections = [];
foreach ($fields as $fieldId => $field) {
    // Skip disabled fields
    if (!($field['enabled'] ?? true)) continue;
    
    $section = $field['section'] ?? 'billing';
    if (!isset($sections[$section])) {
        $sections[$section] = [];
    }
    $sections[$section][$fieldId] = $field;
}

$section_titles = [
    'billing' => __('Billing Address', 'instinctor'),
    'shipping' => __('Shipping Address', 'instinctor'),
    'additional' => __('Additional Information', 'instinctor'),
];
?>

<div class="instinctor-checkout instinctor-checkout-<?php echo esc_attr($layout); ?> instinctor-style-<?php echo esc_attr($style); ?>">
    <?php 
    // Determine if user can proceed with checkout
    $canCheckout = is_user_logged_in() || ($config['guest_checkout'] ?? true);
    ?>
    <?php if ($layout === 'multi-step' && $canCheckout): ?>
    <div class="instinctor-checkout-steps">
        <div class="instinctor-step active" data-step="1"><?php esc_html_e('1. Contact', 'instinctor'); ?></div>
        <div class="instinctor-step" data-step="2"><?php esc_html_e('2. Address', 'instinctor'); ?></div>
        <div class="instinctor-step" data-step="3"><?php esc_html_e('3. Payment', 'instinctor'); ?></div>
    </div>
    <?php endif; ?>

    <div id="instinctor-checkout-app">
        <form id="instinctor-checkout-form" class="instinctor-checkout-form" autocomplete="off">
            <?php echo wp_kses_post(\Instinctor\Core\Security::honeypotField()); ?>
            <div class="instinctor-checkout-grid<?php echo $memberCtx ? ' instinctor-member-checkout' : ''; ?><?php echo (!empty($memberAlreadySubscribed)) ? ' instinctor-member-subscribed' : ''; ?>">
                <div class="instinctor-checkout-main">
                    
                    <?php if (!is_user_logged_in()): ?>
                    <!-- Account Options for Guests -->
                    <div class="instinctor-account-section">
                        <?php if (!($config['guest_checkout'] ?? true)): ?>
                            <!-- Login Required -->
                            <div class="instinctor-login-required">
                                <h2><?php esc_html_e('Login Required', 'instinctor'); ?></h2>
                                <p><?php esc_html_e('Please log in to complete your purchase.', 'instinctor'); ?></p>
                                <a href="<?php echo esc_url(\Instinctor\Services\PageService::resolveUrl('account')); ?>" class="instinctor-login-btn">
                                    <?php esc_html_e('Log In', 'instinctor'); ?>
                                </a>
                                <?php if (get_option('users_can_register')): ?>
                                <p class="instinctor-register-link">
                                    <?php esc_html_e('Don\'t have an account?', 'instinctor'); ?>
                                    <a href="<?php echo esc_url(add_query_arg('tab', 'register', \Instinctor\Services\PageService::resolveUrl('account'))); ?>"><?php esc_html_e('Register', 'instinctor'); ?></a>
                                </p>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <!-- Returning Customer Notice -->
                            <div class="instinctor-returning-customer" id="instinctor-returning-notice">
                                <span><?php esc_html_e('Returning customer?', 'instinctor'); ?></span>
                                <a href="#" id="instinctor-show-login"><?php esc_html_e('Click here to login', 'instinctor'); ?></a>
                            </div>
                            
                            <!-- Login Form (hidden by default) -->
                            <div class="instinctor-login-form-wrap" id="instinctor-login-wrap" style="display:none;">
                                <h3><?php esc_html_e('Login', 'instinctor'); ?></h3>
                                <div class="instinctor-login-form">
                                    <div class="instinctor-form-row">
                                        <label for="instinctor-login-email"><?php esc_html_e('Email', 'instinctor'); ?></label>
                                        <input type="email" id="instinctor-login-email">
                                    </div>
                                    <div class="instinctor-form-row">
                                        <label for="instinctor-login-password"><?php esc_html_e('Password', 'instinctor'); ?></label>
                                        <input type="password" id="instinctor-login-password">
                                    </div>
                                    <div class="instinctor-login-error" id="instinctor-login-error" style="display:none;"></div>
                                    <button type="button" id="instinctor-login-btn" class="instinctor-login-submit">
                                        <?php esc_html_e('Login', 'instinctor'); ?>
                                    </button>
                                    <a href="#" id="instinctor-hide-login" class="instinctor-cancel-login"><?php esc_html_e('Cancel', 'instinctor'); ?></a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($canCheckout): ?>
                    <?php if ($express_enabled && $has_stripe && ($apple_pay || $google_pay)): ?>
                    <!-- Express Checkout -->
                    <div class="instinctor-express-section">
                        <div id="instinctor-payment-request-button"></div>
                        <div class="instinctor-express-divider">
                            <span><?php esc_html_e('or continue below', 'instinctor'); ?></span>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- All Fields in Single Grid -->
                    <?php if ($memberCtx): ?>
                    <div class="instinctor-member-identity">
                        <?php esc_html_e('Checking out as', 'instinctor'); ?> <strong><?php echo esc_html($memberCtx['email']); ?></strong><?php if ($memberCtx['name']): ?> &middot; <?php echo esc_html($memberCtx['name']); ?><?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($memberAlreadySubscribed)): ?>
                    <div class="instinctor-already-subscribed-panel">
                        <h2><?php esc_html_e('Your membership is active', 'instinctor'); ?></h2>
                        <p><?php esc_html_e('You can manage it any time from your account.', 'instinctor'); ?></p>
                        <a href="<?php echo esc_url(\Instinctor\Services\PageService::resolveUrl('account')); ?>" class="instinctor-place-order-btn"><?php esc_html_e('Go to my account', 'instinctor'); ?></a>
                    </div>
                    <?php endif; ?>
                    <?php
                    // For a logged-in member, the contact-field grid is empty when every contact
                    // field is prefilled (and hidden). Collapse it server-side so block-margin
                    // spacing stays uniform (more reliable than :has()).
                    $memberGridEmpty = false;
                    if ($memberCtx) {
                        $memberGridEmpty = true;
                        foreach ($sections as $__sid => $__sfields) {
                            foreach ($__sfields as $__fid => $__f) {
                                if (!($__f['enabled'] ?? true)) continue;
                                $__isContact = in_array($__fid, ['email','phone','first_name','last_name'], true);
                                $__val = ($__fid === 'email') ? $memberCtx['email'] : (($__fid === 'first_name') ? $memberCtx['first_name'] : (($__fid === 'last_name') ? $memberCtx['last_name'] : (($__fid === 'phone') ? $memberCtx['phone'] : '')));
                                if (!($__isContact && $__val !== '')) { $memberGridEmpty = false; break 2; }
                            }
                        }
                    }
                    ?>
                    <div class="instinctor-fields-grid<?php echo $memberGridEmpty ? ' instinctor-member-hidden' : ''; ?>" <?php if ($layout === 'multi-step'): ?>data-step="1"<?php endif; ?>>
                    <?php 
                    // Flatten all sections into single field list
                    $allFields = [];
                    foreach ($sections as $sectionId => $sectionFields) {
                        foreach ($sectionFields as $fieldId => $field) {
                            $field['_section'] = $sectionId;
                            $allFields[$fieldId] = $field;
                        }
                    }
                    
                    $lastFieldId = array_key_last($allFields);
                    foreach ($allFields as $fieldId => $field): 
                        $widthClass = 'instinctor-field-' . ($field['width'] ?? 'full');
                        // Add responsive width classes
                        $widthTablet = $field['width_tablet'] ?? ($field['width'] ?? 'full');
                        $widthMobile = $field['width_mobile'] ?? 'full';
                        $widthClass .= ' instinctor-field-tablet-' . $widthTablet;
                        $widthClass .= ' instinctor-field-mobile-' . $widthMobile;
                        
                        $inputType = $field['type'] ?? 'text';
                        $required = $field['required'] ?? false;
                        $placeholder = $field['placeholder'] ?? '';
                        $autocomplete = $field['autocomplete'] ?? '';
                        $sectionId = $field['_section'] ?? 'billing';
                        
                        // Multi-step: contact fields = step 1, address fields = step 2
                        $stepNum = $sectionId === 'contact' ? '1' : '2';
                        
                        // Pre-fill from user
                        $value = '';
                        // Standalone user rows carry email (not WP's user_email) and may
                        // lack first/last name entirely - null-coalesce both shapes.
                        if ($fieldId === 'email')      $value = (string) ($user->user_email ?? $user->email ?? '');
                        if ($fieldId === 'first_name') $value = (string) ($user->first_name ?? '');
                        if ($fieldId === 'last_name')  $value = (string) ($user->last_name ?? '');
                        // Logged-in member: prefill known contact info from their saved record.
                        if ($memberCtx) {
                            if ($fieldId === 'email')           $value = $memberCtx['email'];
                            elseif ($fieldId === 'first_name')  $value = $memberCtx['first_name'];
                            elseif ($fieldId === 'last_name')   $value = $memberCtx['last_name'];
                            elseif ($fieldId === 'phone')       $value = $memberCtx['phone'];
                        }
                        // Hide a contact field we already have a value for (the identity line stands in for it).
                        $memberHidden = $memberCtx && in_array($fieldId, ['email','phone','first_name','last_name'], true) && $value !== '';
                    ?>
                    <div class="instinctor-form-row <?php echo esc_attr($widthClass); ?><?php echo $memberHidden ? ' instinctor-member-hidden' : ''; ?>" <?php if ($layout === 'multi-step'): ?>data-step="<?php echo esc_attr($stepNum); ?>"<?php endif; ?>>
                        <label for="field-<?php echo esc_attr($fieldId); ?>" class="screen-reader-text">
                            <?php echo esc_html($field['label']); ?>
                            <?php if ($required): ?><span class="required">*</span><?php endif; ?>
                        </label>
                        
                        <?php 
                        // Use label as placeholder for visual consistency with preview
                        $fieldPlaceholder = $field['label'] . ($required ? ' *' : '');
                        ?>
                        
                        <?php if ($inputType === 'textarea'): ?>
                            <textarea id="field-<?php echo esc_attr($fieldId); ?>" 
                                      name="<?php echo esc_attr($fieldId); ?>"
                                      placeholder="<?php echo esc_attr($fieldPlaceholder); ?>"
                                      <?php echo $required ? 'required' : ''; ?>
                                      rows="3"></textarea>
                        
                        <?php elseif ($inputType === 'country'): 
                            $countries = \Instinctor\Services\ShippingService::getCountries();
                        ?>
                            <select id="field-<?php echo esc_attr($fieldId); ?>" 
                                    name="<?php echo esc_attr($fieldId); ?>"
                                    <?php echo $required ? 'required' : ''; ?>>
                                <option value=""><?php echo esc_html($fieldPlaceholder); ?></option>
                                <?php foreach ($countries as $code => $name): ?>
                                <option value="<?php echo esc_attr($code); ?>" <?php selected($code, 'US'); ?>>
                                    <?php echo esc_html($name); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        
                        <?php else: ?>
                            <input type="<?php echo esc_attr($inputType); ?>" 
                                   id="field-<?php echo esc_attr($fieldId); ?>" 
                                   name="<?php echo esc_attr($fieldId); ?>"
                                   value="<?php echo esc_attr($value); ?>"
                                   placeholder="<?php echo esc_attr($fieldPlaceholder); ?>"
                                   autocomplete="one-time-code"
                                   <?php echo $required ? 'required' : ''; ?>
                                   <?php if ($autocomplete === 'address' && $autocomplete_enabled): ?>
                                   data-autocomplete="address"
                                   <?php endif; ?>>
                        <?php endif; ?>
                    </div>
                    
                    <?php // Create-account: checkbox lands under first name, password under last name — inline in the 2-col grid. ?>
                    <?php if ($fieldId === $lastFieldId && !is_user_logged_in() && ($config['guest_checkout'] ?? true) && ($config['create_account_option'] ?? true)): ?>
                    <div class="instinctor-form-row instinctor-field-half instinctor-field-mobile-full instinctor-create-account-row" <?php if ($layout === 'multi-step'): ?>data-step="1"<?php endif; ?>>
                        <label class="instinctor-checkbox-label">
                            <input type="checkbox" name="create_account" id="instinctor-create-account" value="1">
                            <span><?php esc_html_e('Create an account', 'instinctor'); ?></span>
                        </label>
                    </div>
                    <div class="instinctor-form-row instinctor-field-half instinctor-field-mobile-full instinctor-password-fields" id="instinctor-password-fields" style="display:none;" <?php if ($layout === 'multi-step'): ?>data-step="1"<?php endif; ?>>
                        <input type="password" id="instinctor-password" name="account_password" minlength="8" placeholder="<?php echo esc_attr(__('Password', 'instinctor')); ?> *" autocomplete="new-password">
                    </div>
                    <?php endif; ?>
                    <?php endforeach; ?>
                    </div>

                    <?php  ?>

                    <!-- Checkout Upsells -->
                    <?php
                    if ($upsellService->isActive() && ($upsellSettings['display_position'] ?? '') === 'before_payment'):
                        echo wp_kses_post($upsellService->renderOffers($cart));
                    endif;
                    ?>

                    <!-- Payment -->
                    <div class="instinctor-payment-area" <?php if ($layout === 'multi-step'): ?>data-step="3"<?php endif; ?>>
                        <?php
                        // Count active gateways to decide radio vs hidden
                        $active_gateways = array_filter([
                            'stripe'       => $has_stripe,
                            'authorizenet' => $has_authorizenet,
                            'paypal'       => $has_paypal,
                        ]);
                        $gateway_count = count($active_gateways);
                        $first_gateway = array_key_first($active_gateways) ?: 'demo';
                        ?>
                        <?php if ($has_payment): ?>
                            <?php if ($gateway_count > 1): ?>
                            <div class="instinctor-payment-methods">
                                <?php if ($has_stripe): ?>
                                <label class="instinctor-payment-method">
                                    <input type="radio" name="payment_method" value="stripe"<?php echo $first_gateway === 'stripe' ? ' checked' : ''; ?>>
                                    <span><?php esc_html_e('Credit Card', 'instinctor'); ?></span>
                                </label>
                                <?php endif; ?>
                                <?php if ($has_authorizenet): ?>
                                <label class="instinctor-payment-method">
                                    <input type="radio" name="payment_method" value="authorizenet"<?php echo $first_gateway === 'authorizenet' ? ' checked' : ''; ?>>
                                    <span><?php esc_html_e('Credit Card', 'instinctor'); ?></span>
                                </label>
                                <?php endif; ?>
                                <?php if ($has_paypal): ?>
                                <label class="instinctor-payment-method">
                                    <input type="radio" name="payment_method" value="paypal"<?php echo $first_gateway === 'paypal' ? ' checked' : ''; ?>>
                                    <span><?php esc_html_e('PayPal', 'instinctor'); ?></span>
                                </label>
                                <?php endif; ?>
                            </div>
                            <?php else: ?>
                                <input type="hidden" name="payment_method" value="<?php echo esc_attr($first_gateway); ?>">
                            <?php endif; ?>

                            <?php if ($has_stripe): ?>
                            <div id="instinctor-stripe-container" class="instinctor-payment-container"<?php echo ($first_gateway !== 'stripe') ? ' style="display:none"' : ''; ?>>
                                <div id="instinctor-card-element"></div>
                                <div id="instinctor-card-errors" class="instinctor-error-message"></div>
                            </div>
                            <?php endif; ?>

                            <?php if ($has_authorizenet): ?>
                            <?php if ($memberCtx && !empty($memberCtx['card'])): $__sc = $memberCtx['card']; ?>
                            <div class="instinctor-saved-card" id="instinctor-saved-card">
                                <div class="instinctor-saved-card-info">
                                    <span><?php
                                    /* translators: %1$s is the card brand, %2$s is the last 4 digits. */
                                    printf(esc_html__('Pay with %1$s ending %2$s', 'instinctor'), esc_html($__sc['brand']), esc_html($__sc['last4'])); ?><?php if (!empty($__sc['expiry'])): ?> <span class="instinctor-saved-card-exp">&middot; <?php echo esc_html($__sc['expiry']); ?></span><?php endif; ?></span>
                                    <a href="#" id="instinctor-use-new-card" class="instinctor-use-new-card"><?php esc_html_e('Use a different card', 'instinctor'); ?></a>
                                </div>
                            </div>
                            <input type="hidden" name="use_saved_card" id="instinctor-use-saved-card" value="1">
                            <?php endif; ?>
                            <div id="instinctor-authorizenet-container" class="instinctor-payment-container"<?php echo ($first_gateway !== 'authorizenet' || ($memberCtx && !empty($memberCtx['card']))) ? ' style="display:none"' : ''; ?>>
                                <div class="instinctor-an-fields">
                                    <div class="instinctor-an-row" style="display:flex;gap:8px">
                                        <input type="text" id="an-card-number" autocomplete="cc-number" inputmode="numeric" maxlength="19" placeholder="Card number" style="flex:1 1 auto;min-width:0;height:<?php echo esc_attr($fieldHeight); ?>px;padding:0 12px;background:<?php echo esc_attr($fieldBg); ?>;border:1px solid <?php echo esc_attr($fieldBorderColor); ?>;border-radius:<?php echo esc_attr($fieldRadius); ?>px;font-size:14px;color:<?php echo esc_attr($textColor); ?>;box-sizing:border-box;outline:none">
                                        <input type="text" id="an-expiry" autocomplete="cc-exp" inputmode="numeric" maxlength="7" placeholder="MM / YY" style="flex:0 0 92px;width:92px;height:<?php echo esc_attr($fieldHeight); ?>px;padding:0 10px;background:<?php echo esc_attr($fieldBg); ?>;border:1px solid <?php echo esc_attr($fieldBorderColor); ?>;border-radius:<?php echo esc_attr($fieldRadius); ?>px;font-size:14px;color:<?php echo esc_attr($textColor); ?>;box-sizing:border-box;outline:none">
                                        <input type="text" id="an-cvv" autocomplete="cc-csc" inputmode="numeric" maxlength="4" placeholder="CVV" style="flex:0 0 66px;width:66px;height:<?php echo esc_attr($fieldHeight); ?>px;padding:0 10px;background:<?php echo esc_attr($fieldBg); ?>;border:1px solid <?php echo esc_attr($fieldBorderColor); ?>;border-radius:<?php echo esc_attr($fieldRadius); ?>px;font-size:14px;color:<?php echo esc_attr($textColor); ?>;box-sizing:border-box;outline:none">
                                    </div>
                                </div>
                                <div id="instinctor-an-errors" class="instinctor-error-message"></div>
                            </div>
                            <?php endif; ?>

                            <?php if ($has_paypal): ?>
                            <div id="instinctor-paypal-container" class="instinctor-payment-container"<?php echo ($first_gateway !== 'paypal') ? ' style="display:none"' : ''; ?>>
                                <div id="paypal-button-container"></div>
                            </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="instinctor-demo-payment">
                                <p><?php esc_html_e('Demo mode - no payment will be charged.', 'instinctor'); ?></p>
                                <input type="hidden" name="payment_method" value="demo">
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if ($layout === 'multi-step'): ?>
                    <div class="instinctor-step-nav">
                        <button type="button" class="instinctor-btn instinctor-btn-secondary" id="instinctor-prev-step" style="display:none;">
                            <?php esc_html_e('Back', 'instinctor'); ?>
                        </button>
                        <button type="button" class="instinctor-btn instinctor-btn-outline" id="instinctor-next-step">
                            <?php esc_html_e('Continue to Address', 'instinctor'); ?>
                        </button>
                    </div>
                    <?php endif; ?>
                    <?php endif; // End canCheckout ?>
                </div>

                <!-- Order Summary Sidebar -->
                <?php $compactSummary = in_array(\Instinctor\Core\StoreFeatures::getStoreType(), ['memberships', 'subscriptions'], true); ?>
                <div class="instinctor-checkout-sidebar">
                    <div class="instinctor-order-summary<?php echo $compactSummary ? ' instinctor-order-summary-compact' : ''; ?>">
                        <?php if (!$compactSummary): // membership: the plan title is the heading, not a "Summary" label ?>
                        <h2><?php echo esc_html(\Instinctor\Core\StoreFeatures::summaryLabel()); ?></h2>
                        <?php endif; ?>
                        
                        <div id="instinctor-order-items" class="instinctor-order-items">
                            <div class="instinctor-loading"><div class="instinctor-spinner"></div></div>
                        </div>

                        <!-- Order Bumps -->
                        <div id="instinctor-order-bumps" class="instinctor-order-bumps"></div>

                        <!-- Checkout Upsells (after order review position) -->
                        <?php
                        if ($upsellService->isActive() && ($upsellSettings['display_position'] ?? '') === 'after_order_review'):
                            echo wp_kses_post($upsellService->renderOffers($cart));
                        endif;
                        ?>

                        <!-- Coupon Code -->
                        <?php if ($show_coupon): ?>
                        <div class="instinctor-coupon-section">
                            <div id="instinctor-coupon-form" class="instinctor-coupon-form">
                                <input type="text" id="instinctor-coupon-code" placeholder="<?php esc_attr_e('Coupon code', 'instinctor'); ?>">
                                <button type="button" id="instinctor-apply-coupon"><?php esc_html_e('Apply', 'instinctor'); ?></button>
                            </div>
                            <div id="instinctor-coupon-applied" class="instinctor-coupon-applied" style="display:none;">
                                <span id="instinctor-coupon-code-display"></span>
                                <button type="button" id="instinctor-remove-coupon">&times;</button>
                            </div>
                            <div id="instinctor-coupon-error" class="instinctor-coupon-error" style="display:none;"></div>
                        </div>
                        <?php endif; ?>

                        <!-- Gift Card -->
                        <?php if ($show_gift_card): ?>
                        <div class="instinctor-gift-card-section">
                            <div id="instinctor-gift-card-form" class="instinctor-gift-card-form">
                                <input type="text" id="instinctor-gift-card-code" placeholder="<?php esc_attr_e('Gift card code', 'instinctor'); ?>">
                                <button type="button" id="instinctor-apply-gift-card"><?php esc_html_e('Apply', 'instinctor'); ?></button>
                            </div>
                            <div id="instinctor-gift-card-applied" class="instinctor-gift-card-applied" style="display:none;">
                                <span id="instinctor-gift-card-display"></span>
                                <button type="button" id="instinctor-remove-gift-card">&times;</button>
                            </div>
                            <div id="instinctor-gift-card-error" class="instinctor-gift-card-error" style="display:none;"></div>
                        </div>
                        <?php endif; ?>

                        <!-- Loyalty Points -->
                        <?php 
                        $loyaltyEnabled = get_option('instinctor_loyalty_enabled', false);
                        $customerId = null;
                        $customerPoints = 0;
                        if ($loyaltyEnabled && is_user_logged_in()) {
                            global $wpdb;
                            // phpcs:ignore WordPress.DB.DirectDatabaseQuery,WordPress.DB.SlowDBQuery -- direct query against the plugin's own custom table; the WP options/post API does not model this data and the read is request-scoped (object caching would add complexity without benefit)
                            $customerId = $wpdb->get_var($wpdb->prepare(
                                "SELECT id FROM {$wpdb->prefix}instinctor_customers WHERE user_id = %d",
                                get_current_user_id()
                            ));
                            if ($customerId) {
                                $pointsData = \Instinctor\Services\LoyaltyService::getCustomerPoints($customerId);
                                $customerPoints = $pointsData->points ?? 0;
                            }
                        }
                        if ($loyaltyEnabled && $customerPoints > 0): 
                            $minRedeem = intval(get_option('instinctor_loyalty_min_redemption', 100));
                            $pointsValue = floatval(get_option('instinctor_loyalty_points_value', 0.01));
                            $maxValue = $customerPoints * $pointsValue;
                        ?>
                        <div class="instinctor-loyalty-section">
                            <div class="instinctor-loyalty-balance">
                                <span><?php esc_html_e('Your Points:', 'instinctor'); ?></span>
                                <strong id="instinctor-loyalty-balance"><?php echo esc_html( number_format($customerPoints) ); ?></strong>
                                <small>(<?php echo esc_html(\Instinctor\Services\CurrencyService::formatPrice($maxValue)); ?> value)</small>
                            </div>
                            <?php if ($customerPoints >= $minRedeem): ?>
                            <div id="instinctor-loyalty-form" class="instinctor-loyalty-form">
                                <?php /* translators: placeholder values */ ?>
                                <input type="number" id="instinctor-loyalty-points" min="<?php echo esc_attr( (int) $minRedeem ); ?>" max="<?php echo esc_attr( (float) $customerPoints ); ?>" step="1" placeholder="<?php /* translators: %d: minimum points that can be redeemed. */ echo esc_attr( sprintf( __( 'Min %d points', 'instinctor' ), (int) $minRedeem ) ); ?>">
                                <button type="button" id="instinctor-apply-loyalty"><?php esc_html_e('Redeem', 'instinctor'); ?></button>
                            </div>
                            <div id="instinctor-loyalty-applied" class="instinctor-loyalty-applied" style="display:none;">
                                <span id="instinctor-loyalty-display"></span>
                                <button type="button" id="instinctor-remove-loyalty">&times;</button>
                            </div>
                            <div id="instinctor-loyalty-error" class="instinctor-loyalty-error" style="display:none;"></div>
                            <?php else: ?>
                            <small class="instinctor-loyalty-min-notice"><?php
                                /* translators: %d is the minimum number of points required */
                                echo sprintf(esc_html__('Minimum %d points required to redeem', 'instinctor'), intval($minRedeem));
                            ?></small>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <?php  ?>
                        <div class="instinctor-order-totals">
                            <div class="instinctor-totals-row">
                                <span><?php esc_html_e('Subtotal', 'instinctor'); ?></span>
                                <span id="instinctor-subtotal">-</span>
                            </div>
                            <div class="instinctor-totals-row instinctor-discount-row" id="instinctor-discount-row" style="display:none;">
                                <span><?php esc_html_e('Discount', 'instinctor'); ?></span>
                                <span id="instinctor-discount">-</span>
                            </div>
                            <?php if ($show_gift_card): ?>
                            <div class="instinctor-totals-row instinctor-gift-card-row" id="instinctor-gift-card-row" style="display:none;">
                                <span><?php esc_html_e('Gift Card', 'instinctor'); ?></span>
                                <span id="instinctor-gift-card-amount">-</span>
                            </div>
                            <?php endif; ?>
                            <div class="instinctor-totals-row instinctor-loyalty-row" id="instinctor-loyalty-row" style="display:none;">
                                <span><?php esc_html_e('Points Discount', 'instinctor'); ?></span>
                                <span id="instinctor-loyalty-amount">-</span>
                            </div>
                            <?php if ($showShipping): ?>
                            <div class="instinctor-totals-row instinctor-shipping-row" id="instinctor-shipping-row">
                                <span><?php esc_html_e('Shipping', 'instinctor'); ?></span>
                                <span id="instinctor-shipping">-</span>
                            </div>
                            <?php endif; ?>
                            <div class="instinctor-totals-row">
                                <span><?php esc_html_e('Tax', 'instinctor'); ?></span>
                                <span id="instinctor-tax">-</span>
                            </div>
                            <?php  ?>
                            <div class="instinctor-totals-row instinctor-total">
                                <span><?php esc_html_e('Total', 'instinctor'); ?></span>
                                <span id="instinctor-total">-</span>
                            </div>
                        </div>

                        <?php if ($showShipping): ?>
                        <!-- Shipping Methods -->
                        <div id="instinctor-shipping-methods" class="instinctor-shipping-methods" style="display:none;"></div>
                        <?php endif; ?>

                        <?php if ($canCheckout): ?>
                        <button type="submit" id="instinctor-submit-btn" class="instinctor-place-order-btn" disabled>
                            <?php echo esc_html($impulseSettings['checkout_button_text'] ?? __('Pay now', 'instinctor')); ?>
                        </button>
                        <?php endif; ?>
                        
                        <div id="instinctor-checkout-error" class="instinctor-error-message" style="display: none;"></div>

                        <div class="instinctor-secure-badge">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
                                <path d="M7 11V7a5 5 0 0110 0v4"/>
                            </svg>
                            <?php esc_html_e('Secure checkout', 'instinctor'); ?>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<?php 
// Upsell Modal (for modal display position)
if ($upsellService->isActive() && ($upsellSettings['display_position'] ?? '') === 'modal'):
    $modalOffers = $upsellService->getApplicableOffers($cart);
    if (!empty($modalOffers)):
?>
<div id="instinctor-upsell-modal" class="instinctor-upsell-modal">
    <div class="instinctor-upsell-modal-content">
        <button type="button" class="instinctor-upsell-modal-close">&times;</button>
        <h3>Wait! Complete Your Order With These Special Offers</h3>
        <?php
        echo wp_kses_post($upsellService->renderOffers($cart));
        ?>
        <button type="button" class="instinctor-upsell-modal-skip">No thanks, continue to payment</button>
    </div>
</div>
<?php ob_start(); ?>
.instinctor-upsell-modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.6);
    z-index: 99999;
    align-items: center;
    justify-content: center;
}
.instinctor-upsell-modal.active { display: flex; }
.instinctor-upsell-modal-content {
    background: #fff;
    border-radius: 16px;
    padding: 32px;
    max-width: 500px;
    width: 90%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
}
.instinctor-upsell-modal-content h3 {
    margin: 0 0 20px;
    font-size: 20px;
    text-align: center;
}
.instinctor-upsell-modal-close {
    position: absolute;
    top: 12px;
    right: 12px;
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
}
.instinctor-upsell-modal-skip {
    display: block;
    width: 100%;
    margin-top: 16px;
    padding: 12px;
    background: transparent;
    border: 1px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    color: #666;
}
.instinctor-upsell-modal-skip:hover { background: #f5f5f5; }
<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>
<?php ob_start(); ?>
(function() {
    var modal = document.getElementById('instinctor-upsell-modal');
    var form = document.querySelector('.instinctor-checkout form');
    var shown = false;
    
    if (form && modal) {
        form.addEventListener('submit', function(e) {
            if (!shown && modal.querySelector('.instinctor-upsell-offer')) {
                e.preventDefault();
                modal.classList.add('active');
                shown = true;
            }
        });
        
        modal.querySelector('.instinctor-upsell-modal-close').addEventListener('click', function() {
            modal.classList.remove('active');
        });
        
        modal.querySelector('.instinctor-upsell-modal-skip').addEventListener('click', function() {
            modal.classList.remove('active');
            form.submit();
        });
    }
})();
<?php $_inst_ljs = ob_get_clean(); wp_add_inline_script('instinctor-frontend-js', $_inst_ljs, 'after'); ?>
<?php
    endif;
endif;
?>

<?php
// Payment SDK scripts must load from the providers' own CDNs (Stripe, PayPal,
// Google Maps) — they manage versioning + PCI scope on their end. Registered
// dynamically here because each URL embeds runtime params (client_id, API key).
// Documented in External Services section of readme.
if ($has_stripe) {
    wp_register_script('instinctor-stripe-sdk', 'https://js.stripe.com/v3/', [], INSTINCTOR_VERSION, false);
    wp_enqueue_script('instinctor-stripe-sdk');
}
if ($has_authorizenet) {
    $an_js_url = $an_sandbox
        ? 'https://jstest.authorize.net/v1/Accept.js'
        : 'https://js.authorize.net/v1/Accept.js';
    // Accept.js must load from Authorize.net's CDN with NO query string. A ?ver=
    // param fails their script-origin check ("Library is not coming from Accept
    // CDN") and dispatchData refuses to tokenize the card, breaking all payments.
    // Pass null (not INSTINCTOR_VERSION) so wp_register_script appends nothing.
    wp_register_script('instinctor-authorizenet-accept', $an_js_url, [], null, false); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- external Authorize.net Accept.js SDK; a ?ver query string fails its script-origin check and breaks card tokenization (see note above), so the version is intentionally null.
    wp_enqueue_script('instinctor-authorizenet-accept');
}
if ($has_paypal) {
    $paypal_url = 'https://www.paypal.com/sdk/js?client-id=' . rawurlencode($paypal_client_id) . '&currency=' . rawurlencode($currency);
    wp_register_script('instinctor-paypal-sdk', $paypal_url, [], INSTINCTOR_VERSION, false);
    wp_enqueue_script('instinctor-paypal-sdk');
}
if ($autocomplete_enabled && !empty($google_places_key)) {
    $maps_url = 'https://maps.googleapis.com/maps/api/js?key=' . rawurlencode($google_places_key) . '&libraries=places&callback=initInstinctorAutocomplete';
    wp_register_script('instinctor-google-maps', $maps_url, [], INSTINCTOR_VERSION, true);
    wp_enqueue_script('instinctor-google-maps');
}
// Emit immediately — checkout body code below depends on Stripe/PayPal globals.
$_chk_handles = array_filter(['instinctor-stripe-sdk', 'instinctor-paypal-sdk', 'instinctor-google-maps'], 'wp_script_is');
if (defined('INSTINCTOR_ENV') && INSTINCTOR_ENV === 'standalone') {
    if (function_exists('_instinctor_emit_script')) {
        foreach ($_chk_handles as $_h) { _instinctor_emit_script($_h, false); _instinctor_emit_script($_h, true); }
    }
} elseif (function_exists('wp_print_scripts') && $_chk_handles) {
    wp_print_scripts($_chk_handles);
}
?>
<?php ob_start(); ?>
// Autocomplete init function (called by Google Maps callback)
function initInstinctorAutocomplete() {
    window.instinctorMapsLoaded = true;
    if (typeof window.initAddressAutocomplete === 'function') {
        window.initAddressAutocomplete();
    }
}

(function() {
    const apiUrl = '<?php echo esc_js(rest_url('instinctor/v1/')); ?>';
    const nonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    const hasStripe = <?php echo $has_stripe ? 'true' : 'false'; ?>;
    const hasPaypal = <?php echo $has_paypal ? 'true' : 'false'; ?>;
    const hasAuthorizenet = <?php echo $has_authorizenet ? 'true' : 'false'; ?>;
    const stripeKey = '<?php echo esc_js($stripe_key); ?>';
    const anApiLoginId = '<?php echo esc_js($an_api_login_id); ?>';
    const anPublicKey = '<?php echo esc_js($an_public_key); ?>';
    const layout = '<?php echo esc_js($layout); ?>';
    const expressEnabled = <?php echo ($express_enabled && $has_stripe) ? 'true' : 'false'; ?>;
    const autocompleteEnabled = <?php echo ($autocomplete_enabled && !empty($google_places_key)) ? 'true' : 'false'; ?>;
    const emailFirst = <?php echo ($config['email_first'] ?? true) ? 'true' : 'false'; ?>;
    const orderBumps = <?php echo wp_json_encode(\Instinctor\Services\CheckoutConfig::getOrderBumps()); ?>;
    
    // Account settings
    const isLoggedIn = <?php echo is_user_logged_in() ? 'true' : 'false'; ?>;
    const guestCheckout = <?php echo ($config['guest_checkout'] ?? true) ? 'true' : 'false'; ?>;
    const allowAccountCreation = <?php echo ($config['create_account_option'] ?? true) ? 'true' : 'false'; ?>;
    
    // Currency settings
    const currencySymbol = '<?php echo esc_js($currencyData->symbol ?? '$'); ?>';
    const currencyPosition = '<?php echo esc_js($currencyData->symbol_position ?? 'left'); ?>';
    const exchangeRate = <?php echo floatval($currencyData->exchange_rate ?? 1); ?>;
    const currencyDecimals = <?php echo intval($currencyData->decimals ?? 2); ?>;
    const thousandSep = '<?php echo esc_js($currencyData->thousand_separator ?? ','); ?>';
    const decimalSep = '<?php echo esc_js($currencyData->decimal_separator ?? '.'); ?>';
    
    let stripe, elements, cardElement, paymentRequest;
    let cart = null;
    let currentStep = 1;
    

    function formatCurrency(amount) {
        // Convert using exchange rate
        let converted = parseFloat(amount) * exchangeRate;
        
        // Format number
        let formatted = converted.toFixed(currencyDecimals);
        let parts = formatted.split('.');
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);
        if (parts[1]) {
            formatted = parts[0] + decimalSep + parts[1];
        } else {
            formatted = parts[0];
        }
        
        // Apply symbol position
        switch (currencyPosition) {
            case 'right': return formatted + currencySymbol;
            case 'left_space': return currencySymbol + ' ' + formatted;
            case 'right_space': return formatted + ' ' + currencySymbol;
            default: return currencySymbol + formatted;
        }
    }

    

    function collectFormData() {
        const data = {};
        document.querySelectorAll('#instinctor-checkout-form input, #instinctor-checkout-form select, #instinctor-checkout-form textarea').forEach(el => {
            if (el.name && el.type !== 'radio' && el.type !== 'checkbox') {
                data[el.name] = el.value;
            } else if (el.type === 'radio' && el.checked) {
                data[el.name] = el.value;
            } else if (el.type === 'checkbox' && el.checked) {
                data[el.name] = el.value || true;
            }
        });
        return data;
    }

    function getSelectedPaymentMethod() {
        const checked = document.querySelector('input[name="payment_method"]:checked');
        if (checked) return checked.value;
        // Single-gateway checkout renders a hidden input (never matches :checked) - read it directly.
        const single = document.querySelector('input[name="payment_method"]');
        return single ? single.value : 'demo';
    }

    // Capture email for abandoned cart
    function captureEmail() {
        if (!emailFirst) return;
        const emailField = document.getElementById('field-email');
        if (emailField && emailField.value) {
            fetch(apiUrl + 'cart/capture-email', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ 
                    email: emailField.value,
                    billing: collectFormData()
                })
            }).catch(() => {});
        }
    }

    async function loadCart() {
        try {
            const response = await fetch(apiUrl + 'cart', {
                headers: { 'X-WP-Nonce': nonce }
            });
            const data = await response.json();
            cart = data.data;

            renderOrderSummary();
        } catch (error) {
            console.error('Failed to load cart:', error);
        }
    }

    function renderOrderSummary() {
        const itemsContainer = document.getElementById('instinctor-order-items');
        const submitBtn = document.getElementById('instinctor-submit-btn');

        // Order summary not present on this render (e.g. editor preview / partial layout): nothing to draw.
        if (!itemsContainer) return;

        if (!cart || !cart.items || Object.keys(cart.items).length === 0) {
            itemsContainer.innerHTML = '<p class="instinctor-empty-cart">Your cart is empty.</p>';
            if (submitBtn) submitBtn.disabled = true;
            return;
        }
        if (!cart.totals) cart.totals = {};

        let html = '';
        for (const key in cart.items) {
            const item = cart.items[key];
            const meta = item.meta || {};
            const hasBooking = meta.booking_date && meta.booking_time;
            
            let bookingInfo = '';
            if (hasBooking) {
                const dateFormatted = new Date(meta.booking_date + 'T00:00:00').toLocaleDateString(undefined, { 
                    weekday: 'short', month: 'short', day: 'numeric' 
                });
                bookingInfo = `<span class="instinctor-order-item-booking" style="display: block; font-size: 11px; color: #666; margin-top: 4px;">
                    Appointment: ${dateFormatted} at ${meta.booking_time}
                </span>`;
            }

            // Addon selections, keys are names, values are customer input
            let addonsInfo = '';
            if (meta.addons && typeof meta.addons === 'object' && Object.keys(meta.addons).length > 0) {
                const lines = Object.entries(meta.addons).map(([name, val]) => {
                    const display = (val === '1' || val === 1) ? name : (name + ': ' + val);
                    return `<span style="display:inline-block;background:#f0f0f0;border-radius:3px;padding:1px 6px;font-size:11px;color:#555;margin:2px 2px 0 0">${display}</span>`;
                }).join('');
                if (lines) addonsInfo = `<div style="margin-top:4px;line-height:1.6">${lines}</div>`;
            }

            html += `
                <div class="instinctor-order-item">
                    ${item.image ? `<img src="${item.image}" class="instinctor-order-item-image">` : ''}
                    <div class="instinctor-order-item-details">
                        <span class="instinctor-order-item-name">${item.name}</span>
                        ${item.quantity > 1 ? `<span class="instinctor-order-item-qty">Qty: ${item.quantity}</span>` : ''}
                        ${addonsInfo}
                        ${bookingInfo}
                    </div>
                    <span class="instinctor-order-item-price">${formatCurrency(item.price * item.quantity)}</span>
                </div>
            `;
        }
        itemsContainer.innerHTML = html;

        var _subEl = document.getElementById('instinctor-subtotal');
        var _taxEl = document.getElementById('instinctor-tax');
        var _totEl = document.getElementById('instinctor-total');
        if (_subEl) _subEl.textContent = formatCurrency(cart.totals.subtotal);
        if (_taxEl) _taxEl.textContent = formatCurrency(cart.totals.tax);
        if (_totEl) _totEl.textContent = formatCurrency(cart.totals.total);
        
        // Drop redundant rows: Tax when none, Subtotal when it equals the Total (no discount/tax/shipping).
        var _taxRow = _taxEl ? _taxEl.closest('.instinctor-totals-row') : null;
        if (_taxRow) _taxRow.style.display = (cart.totals.tax > 0) ? 'flex' : 'none';
        var _subRow = _subEl ? _subEl.closest('.instinctor-totals-row') : null;
        if (_subRow) _subRow.style.display = (Math.abs((cart.totals.subtotal||0) - (cart.totals.total||0)) > 0.001) ? 'flex' : 'none';
        // A single membership repeats the same number as line price, Total, and Pay button.
        // Drop the line price and collapse the double divider to one; keep the bold Total.
        var _itemCount = itemsContainer.querySelectorAll('.instinctor-order-item').length;
        var _clean = _itemCount <= 1 && Math.abs((cart.totals.subtotal||0) - (cart.totals.total||0)) < 0.001;
        var _priceEl = itemsContainer.querySelector('.instinctor-order-item-price');
        if (_priceEl) _priceEl.style.display = _clean ? 'none' : '';
        var _totalsSection = itemsContainer.parentElement ? itemsContainer.parentElement.querySelector('.instinctor-order-totals') : null;
        if (_totalsSection) _totalsSection.style.display = _clean ? 'none' : '';
        
        // Show/hide discount row
        const discountRow = document.getElementById('instinctor-discount-row');
        if (discountRow && cart.totals.discount > 0) {
            discountRow.style.display = 'flex';
            var _de = document.getElementById('instinctor-discount'); if (_de) _de.textContent = '-' + formatCurrency(cart.totals.discount);
        } else if (discountRow) {
            discountRow.style.display = 'none';
        }

        // Show/hide gift card row
        const giftCardRow = document.getElementById('instinctor-gift-card-row');
        if (giftCardRow && cart.totals.gift_card_amount > 0) {
            giftCardRow.style.display = 'flex';
            document.getElementById('instinctor-gift-card-amount').textContent = '-' + formatCurrency(cart.totals.gift_card_amount);
        } else if (giftCardRow) {
            giftCardRow.style.display = 'none';
        }

        // Show/hide loyalty points row
        const loyaltyRow = document.getElementById('instinctor-loyalty-row');
        if (loyaltyRow && cart.totals.loyalty_discount > 0) {
            loyaltyRow.style.display = 'flex';
            document.getElementById('instinctor-loyalty-amount').textContent = '-' + formatCurrency(cart.totals.loyalty_discount);
        } else if (loyaltyRow) {
            loyaltyRow.style.display = 'none';
        }
        
        // Show shipping
        const shippingEl = document.getElementById('instinctor-shipping');
        if (shippingEl) {
            if (cart.totals.shipping > 0) shippingEl.textContent = formatCurrency(cart.totals.shipping);
            else if (cart.shipping_method) shippingEl.textContent = 'Free';
            else shippingEl.textContent = 'Calculated at next step';
        }
        
        // Show applied coupon
        const couponForm = document.getElementById('instinctor-coupon-form');
        const couponApplied = document.getElementById('instinctor-coupon-applied');
        if (couponForm && couponApplied && cart.coupon) {
            couponForm.style.display = 'none';
            couponApplied.style.display = 'flex';
            var _cd = document.getElementById('instinctor-coupon-code-display'); if (_cd) _cd.textContent = cart.coupon.code;
        } else if (couponForm && couponApplied) {
            couponForm.style.display = 'flex';
            couponApplied.style.display = 'none';
        }

        // Show applied gift card
        const gcForm = document.getElementById('instinctor-gift-card-form');
        const gcApplied = document.getElementById('instinctor-gift-card-applied');
        if (gcForm && gcApplied) {
            if (cart.gift_card) {
                gcForm.style.display = 'none';
                gcApplied.style.display = 'flex';
                document.getElementById('instinctor-gift-card-display').textContent = 
                    cart.gift_card.code + ' (-' + formatCurrency(cart.totals.gift_card_amount) + ')';
            } else {
                gcForm.style.display = 'flex';
                gcApplied.style.display = 'none';
            }
        }

        // Show applied loyalty points
        const loyaltyForm = document.getElementById('instinctor-loyalty-form');
        const loyaltyApplied = document.getElementById('instinctor-loyalty-applied');
        if (loyaltyForm && loyaltyApplied) {
            if (cart.loyalty_points > 0) {
                loyaltyForm.style.display = 'none';
                loyaltyApplied.style.display = 'flex';
                document.getElementById('instinctor-loyalty-display').textContent = 
                    cart.loyalty_points.toLocaleString() + ' points (-' + formatCurrency(cart.totals.loyalty_discount) + ')';
            } else {
                loyaltyForm.style.display = 'flex';
                loyaltyApplied.style.display = 'none';
            }
        }
        
        if (submitBtn) {
            if (layout !== 'multi-step') {
                submitBtn.disabled = false;
            }
            submitBtn.textContent = 'Pay ' + formatCurrency(cart.totals.total);
        }
        
        // Render order bumps
        renderOrderBumps();
    }

    function renderOrderBumps() {
        const container = document.getElementById('instinctor-order-bumps');
        if (!container || !orderBumps || Object.keys(orderBumps).length === 0) {
            return;
        }
        
        let html = '';
        for (const bumpId in orderBumps) {
            const bump = orderBumps[bumpId];
            if (!bump.enabled) continue;
            
            const isAdded = cart.bumps && cart.bumps[bumpId];
            const addedData = isAdded ? cart.bumps[bumpId] : null;
            
            html += `
                <div class="instinctor-order-bump ${isAdded ? 'selected' : ''}" data-bump-id="${bumpId}">
                    <div class="instinctor-bump-checkbox">
                        <input type="checkbox" ${isAdded ? 'checked' : ''}>
                    </div>
                    <div class="instinctor-bump-content">
                        <div class="instinctor-bump-title">${bump.title || 'Add this to your order!'}</div>
                        <div class="instinctor-bump-description">${bump.description || ''}</div>
                    </div>
                    <div class="instinctor-bump-price">
                        ${addedData ? formatCurrency(addedData.price) : ''}
                    </div>
                </div>
            `;
        }
        
        container.innerHTML = html;
        
        // Add click handlers
        container.querySelectorAll('.instinctor-order-bump').forEach(el => {
            el.addEventListener('click', async function(e) {
                if (e.target.type === 'checkbox') return;
                
                const bumpId = this.dataset.bumpId;
                const checkbox = this.querySelector('input[type="checkbox"]');
                const isChecked = checkbox.checked;
                
                // Toggle
                if (isChecked) {
                    await removeBump(bumpId);
                } else {
                    await addBump(bumpId);
                }
            });
            
            el.querySelector('input[type="checkbox"]').addEventListener('change', async function() {
                const bumpId = this.closest('.instinctor-order-bump').dataset.bumpId;
                if (this.checked) {
                    await addBump(bumpId);
                } else {
                    await removeBump(bumpId);
                }
            });
        });
    }
    
    async function addBump(bumpId) {
        try {
            const response = await fetch(apiUrl + 'cart/add-bump', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                body: JSON.stringify({ bump_id: bumpId })
            });
            const result = await response.json();
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to add bump');
        }
    }
    
    async function removeBump(bumpId) {
        try {
            const response = await fetch(apiUrl + 'cart/remove-bump', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                body: JSON.stringify({ bump_id: bumpId })
            });
            const result = await response.json();
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to remove bump');
        }
    }

    // Coupon handlers
    async function applyCoupon() {
        const codeInput = document.getElementById('instinctor-coupon-code');
        const errorEl = document.getElementById('instinctor-coupon-error');
        const code = codeInput.value.trim();
        
        if (!code) return;
        
        errorEl.style.display = 'none';
        
        try {
            const response = await fetch(apiUrl + 'coupon/apply', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ 
                    code: code,
                    email: document.getElementById('field-email')?.value || ''
                })
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
                codeInput.value = '';
            } else {
                errorEl.textContent = result.error || 'Invalid coupon';
                errorEl.style.display = 'block';
            }
        } catch (error) {
            errorEl.textContent = 'Failed to apply coupon';
            errorEl.style.display = 'block';
        }
    }
    
    async function removeCoupon() {
        try {
            const response = await fetch(apiUrl + 'coupon/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to remove coupon');
        }
    }

    // Gift Card handlers
    async function applyGiftCard() {
        const codeInput = document.getElementById('instinctor-gift-card-code');
        const errorEl = document.getElementById('instinctor-gift-card-error');
        const code = codeInput.value.trim().toUpperCase();
        
        if (!code) {
            errorEl.textContent = 'Please enter a gift card code';
            errorEl.style.display = 'block';
            return;
        }
        
        errorEl.style.display = 'none';
        
        try {
            const response = await fetch(apiUrl + 'gift-card/apply', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ code })
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
                codeInput.value = '';
            } else {
                errorEl.textContent = result.error || 'Invalid gift card';
                errorEl.style.display = 'block';
            }
        } catch (error) {
            errorEl.textContent = 'Failed to apply gift card';
            errorEl.style.display = 'block';
        }
    }
    
    async function removeGiftCard() {
        try {
            const response = await fetch(apiUrl + 'gift-card/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to remove gift card');
        }
    }

    // Loyalty Points handlers
    async function applyLoyaltyPoints() {
        const pointsInput = document.getElementById('instinctor-loyalty-points');
        const errorEl = document.getElementById('instinctor-loyalty-error');
        const points = parseInt(pointsInput.value) || 0;
        
        if (points < 1) {
            errorEl.textContent = 'Please enter points to redeem';
            errorEl.style.display = 'block';
            return;
        }
        
        errorEl.style.display = 'none';
        
        try {
            const response = await fetch(apiUrl + 'loyalty/apply', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ points })
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
                pointsInput.value = '';
                // Update balance display
                const balanceEl = document.getElementById('instinctor-loyalty-balance');
                if (balanceEl && result.remaining_points !== undefined) {
                    balanceEl.textContent = result.remaining_points.toLocaleString();
                }
            } else {
                errorEl.textContent = result.error || 'Failed to redeem points';
                errorEl.style.display = 'block';
            }
        } catch (error) {
            errorEl.textContent = 'Failed to apply points';
            errorEl.style.display = 'block';
        }
    }
    
    async function removeLoyaltyPoints() {
        try {
            const response = await fetch(apiUrl + 'loyalty/remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                }
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderOrderSummary();
                // Restore balance display
                const balanceEl = document.getElementById('instinctor-loyalty-balance');
                if (balanceEl && result.remaining_points !== undefined) {
                    balanceEl.textContent = result.remaining_points.toLocaleString();
                }
            }
        } catch (error) {
            console.error('Failed to remove loyalty points');
        }
    }

    // Shipping handlers
    let shippingMethods = [];
    
    async function calculateShipping() {
        const country = document.getElementById('field-country')?.value || '';
        const state = document.getElementById('field-state')?.value || '';
        const postcode = document.getElementById('field-postcode')?.value || '';
        const city = document.getElementById('field-city')?.value || '';
        
        if (!country) return;
        
        try {
            const response = await fetch(apiUrl + 'shipping/calculate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ country, state, postcode, city })
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                shippingMethods = result.shipping.methods || [];
                renderShippingMethods();
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to calculate shipping');
        }
    }
    
    function renderShippingMethods() {
        const container = document.getElementById('instinctor-shipping-methods');
        if (!container) return;
        
        if (shippingMethods.length === 0) {
            container.style.display = 'none';
            return;
        }
        
        if (shippingMethods.length === 1) {
            container.style.display = 'none';
            return;
        }
        
        let html = '<div class="instinctor-shipping-title">Shipping Method</div>';
        shippingMethods.forEach(method => {
            const isSelected = cart.shipping_method && cart.shipping_method.id === method.id;
            const costText = method.cost > 0 ? formatCurrency(method.cost) : 'Free';
            html += `
                <label class="instinctor-shipping-option ${isSelected ? 'selected' : ''}">
                    <input type="radio" name="shipping_method" value="${method.id}" ${isSelected ? 'checked' : ''}>
                    <span class="instinctor-shipping-name">${method.name}</span>
                    <span class="instinctor-shipping-cost">${costText}</span>
                </label>
            `;
        });
        
        container.innerHTML = html;
        container.style.display = 'block';
        
        // Add listeners
        container.querySelectorAll('input[name="shipping_method"]').forEach(input => {
            input.addEventListener('change', () => selectShippingMethod(parseInt(input.value)));
        });
    }
    
    async function selectShippingMethod(methodId) {
        try {
            const response = await fetch(apiUrl + 'shipping/select', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({ method_id: methodId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                cart = result.cart;
                renderShippingMethods();
                renderOrderSummary();
            }
        } catch (error) {
            console.error('Failed to select shipping method');
        }
    }

    // Authorize.net Accept.js tokenization
    // Returns { dataValue, dataDescriptor } or throws on error.
    function tokenizeAuthorizenet() {
        return new Promise(function(resolve, reject) {
            if (typeof Accept === 'undefined') {
                reject(new Error('Payment library not loaded. Please refresh and try again.'));
                return;
            }
            var cardNumber = (document.getElementById('an-card-number')?.value || '').replace(/\s+/g, '');
            var expiryVal  = document.getElementById('an-expiry')?.value || '';
            var parts      = expiryVal.split('/');
            var month      = (parts[0] || '').trim().padStart(2, '0');
            var year       = (parts[1] || '').trim();
            if (year.length === 2) year = '20' + year;
            var cvv        = (document.getElementById('an-cvv')?.value || '').trim();

            if (!cardNumber || !month || !year || !cvv) {
                reject(new Error('Please fill in all card fields.'));
                return;
            }

            var secureData = {
                authData: { clientKey: anPublicKey, apiLoginID: anApiLoginId },
                cardData:  { cardNumber: cardNumber, month: month, year: year, cardCode: cvv },
            };

            Accept.dispatchData(secureData, function(response) {
                if (response.messages.resultCode === 'Ok') {
                    resolve({
                        dataValue:      response.opaqueData.dataValue,
                        dataDescriptor: response.opaqueData.dataDescriptor,
                    });
                } else {
                    var msg = (response.messages.message && response.messages.message[0])
                        ? response.messages.message[0].text
                        : 'Card tokenization failed. Please check your card details.';
                    reject(new Error(msg));
                }
            });
        });
    }

    function initStripe() {
        if (!hasStripe) return;
        
        stripe = Stripe(stripeKey);
        elements = stripe.elements();
        
        cardElement = elements.create('card', {
            style: {
                base: {
                    fontSize: '15px',
                    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                    color: '<?php echo esc_js($textColor); ?>',
                    '::placeholder': { color: '<?php echo esc_js($secondaryTextColor); ?>' }
                }
            }
        });
        
        const cardContainer = document.getElementById('instinctor-card-element');
        if (cardContainer) {
            cardElement.mount('#instinctor-card-element');
            
            cardElement.on('change', function(event) {
                const errorEl = document.getElementById('instinctor-card-errors');
                if (errorEl) {
                    errorEl.textContent = event.error ? event.error.message : '';
                }
            });
        }

        // Express payments (Apple Pay, Google Pay)
        if (expressEnabled && cart) {
            initExpressPayments();
        }
    }

    function initExpressPayments() {
        if (!cart || !cart.totals) return;

        paymentRequest = stripe.paymentRequest({
            country: 'US',
            currency: 'usd',
            total: {
                label: 'Total',
                amount: Math.round(cart.totals.total * 100),
            },
            requestPayerName: true,
            requestPayerEmail: true,
        });

        const prButton = elements.create('paymentRequestButton', {
            paymentRequest: paymentRequest,
        });

        paymentRequest.canMakePayment().then(function(result) {
            if (result) {
                prButton.mount('#instinctor-payment-request-button');
            } else {
                document.querySelector('.instinctor-express-section')?.remove();
            }
        });

        paymentRequest.on('paymentmethod', async function(ev) {
            // Create order and confirm payment
            const response = await fetch(apiUrl + 'checkout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({
                    billing: {
                        email: ev.payerEmail,
                        first_name: ev.payerName?.split(' ')[0] || '',
                        last_name: ev.payerName?.split(' ').slice(1).join(' ') || '',
                    },
                    payment_method: 'stripe'
                })
            });
            const result = await response.json();

            if (result.error) {
                ev.complete('fail');
                return;
            }

            const { error, paymentIntent } = await stripe.confirmCardPayment(
                result.client_secret,
                { payment_method: ev.paymentMethod.id },
                { handleActions: false }
            );

            if (error) {
                ev.complete('fail');
            } else {
                ev.complete('success');
                window.location.href = result.redirect || '/?order=' + result.order_id;
            }
        });
    }

    function initPayPal() {
        if (!hasPaypal) return;
        const container = document.getElementById('paypal-button-container');
        if (!container) return;
        
        paypal.Buttons({
            createOrder: async function() {
                const response = await fetch(apiUrl + 'paypal/create-order', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': nonce
                    }
                });
                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.error || 'Failed to create PayPal order');
                }
                return data.order_id;
            },
            onApprove: async function(data) {
                const submitBtn = document.getElementById('instinctor-submit-btn');
                submitBtn.disabled = true;
                submitBtn.textContent = 'Processing...';

                try {
                    const formData = collectFormData();
                    const response = await fetch(apiUrl + 'paypal/capture', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': nonce
                        },
                        body: JSON.stringify({
                            paypal_order_id: data.orderID,
                            billing: formData
                        })
                    });
                    const result = await response.json();
                    
                    if (result.success) {
                        window.location.href = result.redirect;
                    } else {
                        throw new Error(result.error || 'Payment failed');
                    }
                } catch (error) {
                    document.getElementById('instinctor-checkout-error').textContent = error.message;
                    document.getElementById('instinctor-checkout-error').style.display = 'block';
                    submitBtn.disabled = false;
                    submitBtn.textContent = 'Pay ' + formatCurrency(cart.totals.total);
                }
            }
        }).render('#paypal-button-container');
    }

    function initPaymentMethodToggle() {
        const radios = document.querySelectorAll('input[name="payment_method"]');
        const stripeContainer = document.getElementById('instinctor-stripe-container');
        const paypalContainer = document.getElementById('instinctor-paypal-container');
        const anContainer = document.getElementById('instinctor-authorizenet-container');
        const submitBtn = document.getElementById('instinctor-submit-btn');

        radios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (stripeContainer) stripeContainer.style.display = 'none';
                if (paypalContainer) paypalContainer.style.display = 'none';
                if (anContainer) anContainer.style.display = 'none';
                if (this.value === 'stripe') {
                    if (stripeContainer) stripeContainer.style.display = 'block';
                    if (submitBtn) submitBtn.style.display = 'block';
                } else if (this.value === 'authorizenet') {
                    if (anContainer) anContainer.style.display = 'block';
                    if (submitBtn) submitBtn.style.display = 'block';
                } else if (this.value === 'paypal') {
                    if (paypalContainer) paypalContainer.style.display = 'block';
                    if (submitBtn) submitBtn.style.display = 'none';
                }
            });
        });
    }

    function initAddressAutocomplete() {
        if (!autocompleteEnabled || typeof google === 'undefined') return;
        
        const addressField = document.getElementById('field-address_1');
        if (!addressField) return;

        const autocomplete = new google.maps.places.Autocomplete(addressField, {
            types: ['address'],
            fields: ['address_components', 'formatted_address']
        });

        autocomplete.addListener('place_changed', function() {
            const place = autocomplete.getPlace();
            if (!place.address_components) return;

            const components = {};
            place.address_components.forEach(c => {
                components[c.types[0]] = c.long_name;
                components[c.types[0] + '_short'] = c.short_name;
            });

            // Fill in fields
            const setField = (id, value) => {
                const el = document.getElementById('field-' + id);
                if (el && value) el.value = value;
            };

            setField('address_1', ((components.street_number || '') + ' ' + (components.route || '')).trim());
            setField('city', components.locality || components.sublocality_level_1 || '');
            setField('state', components.administrative_area_level_1_short || '');
            setField('postcode', components.postal_code || '');
            setField('country', components.country_short || '');
            
            // Trigger shipping calculation
            calculateShipping();
        });
    }
    
    // Make it available globally for Google Maps callback
    window.initAddressAutocomplete = initAddressAutocomplete;

    function initMultiStep() {
        if (layout !== 'multi-step') return;

        const steps = document.querySelectorAll('.instinctor-step');
        const formRows = document.querySelectorAll('.instinctor-form-row[data-step], .instinctor-payment-area[data-step]');
        const prevBtn = document.getElementById('instinctor-prev-step');
        const nextBtn = document.getElementById('instinctor-next-step');
        const submitBtn = document.getElementById('instinctor-submit-btn');
        
        // Exit if essential elements are missing (e.g., login required)
        if (!prevBtn || !nextBtn) return;

        function showStep(step) {
            currentStep = step;
            
            steps.forEach((s, i) => {
                s.classList.toggle('active', i + 1 <= step);
                s.classList.toggle('current', i + 1 === step);
            });

            // Show/hide form rows and payment area based on step
            formRows.forEach(el => {
                el.style.display = parseInt(el.dataset.step) === step ? '' : 'none';
            });

            if (prevBtn) prevBtn.style.display = step > 1 ? 'inline-flex' : 'none';
            
            if (step === 3) {
                if (nextBtn) nextBtn.style.display = 'none';
                if (submitBtn) {
                    submitBtn.style.display = 'block';
                    submitBtn.disabled = false;
                }
            } else {
                if (nextBtn) nextBtn.style.display = 'inline-flex';
                if (submitBtn) submitBtn.style.display = 'none';
            }
        }

        prevBtn.addEventListener('click', () => showStep(currentStep - 1));
        nextBtn.addEventListener('click', () => {
            // Validate current step - find all visible required inputs
            const visibleRows = document.querySelectorAll(`.instinctor-form-row[data-step="${currentStep}"]`);
            let valid = true;
            visibleRows.forEach(row => {
                const input = row.querySelector('[required]');
                if (input) {
                    if (!input.value) {
                        input.classList.add('error');
                        valid = false;
                    } else if (input.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value)) {
                        input.classList.add('error');
                        valid = false;
                    } else {
                        input.classList.remove('error');
                    }
                }
            });

            if (valid) {
                if (currentStep === 1) captureEmail();
                showStep(currentStep + 1);
            }
        });

        showStep(1);
    }

    async function handleSubmit(e) {
        e.preventDefault();
        
        const paymentMethod = getSelectedPaymentMethod();
        if (paymentMethod === 'paypal') return;
        
        const submitBtn = document.getElementById('instinctor-submit-btn');
        const errorEl = document.getElementById('instinctor-checkout-error');
        
        // Validate all required fields
        const form = document.getElementById('instinctor-checkout-form');
        const inputs = form.querySelectorAll('[required]');
        let valid = true;
        let firstError = null;
        
        inputs.forEach(input => {
            if (!input.value) {
                input.classList.add('error');
                valid = false;
                if (!firstError) firstError = input;
            } else if (input.type === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value)) {
                input.classList.add('error');
                valid = false;
                if (!firstError) firstError = input;
            } else {
                input.classList.remove('error');
            }
        });
        
        if (!valid) {
            errorEl.textContent = 'Please fill in all required fields.';
            errorEl.style.display = 'block';
            if (firstError) firstError.focus();
            return;
        }
        
        submitBtn.disabled = true;
        submitBtn.textContent = 'Processing...';
        errorEl.style.display = 'none';

        // Authorize.net: tokenize card fields before submitting to server
        let anNonce = null, anDescriptor = null;
        const useSavedCard = (document.getElementById('instinctor-use-saved-card') || {}).value === '1';
        if (paymentMethod === 'authorizenet' && hasAuthorizenet && !useSavedCard) {
            try {
                const token = await tokenizeAuthorizenet();
                anNonce = token.dataValue;
                anDescriptor = token.dataDescriptor;
            } catch (tokenErr) {
                errorEl.textContent = tokenErr.message;
                errorEl.style.display = 'block';
                submitBtn.disabled = false;
                submitBtn.textContent = 'Pay ' + formatCurrency(cart.totals.total);
                return;
            }
        }

        const formData = collectFormData();

        

        // Get account creation data
        const createAccountCheckbox = document.getElementById('instinctor-create-account');
        const createAccount = createAccountCheckbox ? createAccountCheckbox.checked : false;
        const accountPassword = createAccount ? (document.getElementById('instinctor-password')?.value || '') : '';

        try {
            const response = await fetch(apiUrl + 'checkout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({
                    billing: formData,
                    payment_method: paymentMethod,
                    
                    create_account: createAccount,
                    account_password: accountPassword,
                    authorizenet_nonce: anNonce,
                    authorizenet_descriptor: anDescriptor,
                    use_saved_card: useSavedCard,
                })
            });

            const result = await response.json();

            if (result.error) {
                throw new Error(result.error);
            }

            // Handle subscription checkout redirect (Stripe Checkout Session)
            if (result.requires_redirect && result.checkout_url) {
                window.location.href = result.checkout_url;
                return;
            }

            if (!hasStripe || !result.requires_action) {
                window.location.href = result.redirect || '/?order=' + result.order_id;
                return;
            }

            const { error, paymentIntent } = await stripe.confirmCardPayment(result.client_secret, {
                payment_method: {
                    card: cardElement,
                    billing_details: {
                        name: (formData.first_name || '') + ' ' + (formData.last_name || ''),
                        email: formData.email,
                        address: {
                            line1: formData.address_1,
                            city: formData.city,
                            state: formData.state,
                            postal_code: formData.postcode,
                            country: formData.country,
                        }
                    }
                }
            });

            if (error) {
                throw new Error(error.message);
            }

            const confirmResponse = await fetch(apiUrl + 'checkout/confirm', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': nonce
                },
                body: JSON.stringify({
                    order_id: result.order_id,
                    payment_intent_id: paymentIntent.id
                })
            });

            const confirmResult = await confirmResponse.json();

            if (confirmResult.error) {
                throw new Error(confirmResult.error);
            }

            window.location.href = result.redirect || '/?order=' + result.order_id;

        } catch (error) {
            errorEl.textContent = error.message;
            errorEl.style.display = 'block';
            submitBtn.disabled = false;
            submitBtn.textContent = 'Pay ' + formatCurrency(cart.totals.total);
        }
    }

    // Email blur handler for abandoned cart
    document.addEventListener('DOMContentLoaded', function() {
        const emailField = document.getElementById('field-email');
        if (emailField) {
            emailField.addEventListener('blur', captureEmail);
            
            // Real-time email validation
            emailField.addEventListener('blur', function() {
                if (this.value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.value)) {
                    this.classList.add('error');
                } else {
                    this.classList.remove('error');
                }
            });
        }
        
        // Clear error state on input for all required fields
        document.querySelectorAll('#instinctor-checkout-form [required]').forEach(input => {
            input.addEventListener('input', function() {
                this.classList.remove('error');
                document.getElementById('instinctor-checkout-error').style.display = 'none';
            });
        });
    });

    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        loadCart().then(() => {
            initStripe();
            initPayPal();
            initPaymentMethodToggle();
            initAddressAutocomplete();
            initMultiStep();

            // Authorize.net field helpers
            var anCardEl = document.getElementById('an-card-number');
            var anExpiryEl = document.getElementById('an-expiry');
            if (anCardEl) {
                anCardEl.addEventListener('input', function() {
                    var v = this.value.replace(/\D/g, '').slice(0, 16);
                    this.value = v.replace(/(.{4})/g, '$1 ').trim();
                });
            }
            if (anExpiryEl) {
                anExpiryEl.addEventListener('input', function() {
                    var v = this.value.replace(/\D/g, '').slice(0, 4);
                    if (v.length >= 3) v = v.slice(0, 2) + ' / ' + v.slice(2);
                    this.value = v;
                });
            }
        });
        
        document.getElementById('instinctor-checkout-form')?.addEventListener('submit', handleSubmit);
        document.getElementById('instinctor-use-new-card')?.addEventListener('click', function(e){
            e.preventDefault();
            var h = document.getElementById('instinctor-use-saved-card'); if (h) h.value = '0';
            var c = document.getElementById('instinctor-authorizenet-container'); if (c) c.style.display = '';
            var s = document.getElementById('instinctor-saved-card'); if (s) s.style.display = 'none';
        });

        

        // Coupon handlers
        document.getElementById('instinctor-apply-coupon')?.addEventListener('click', applyCoupon);
        document.getElementById('instinctor-coupon-code')?.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                applyCoupon();
            }
        });
        document.getElementById('instinctor-remove-coupon')?.addEventListener('click', removeCoupon);

        // Account login/create handlers
        const showLoginBtn = document.getElementById('instinctor-show-login');
        const hideLoginBtn = document.getElementById('instinctor-hide-login');
        const loginWrap = document.getElementById('instinctor-login-wrap');
        const returningNotice = document.getElementById('instinctor-returning-notice');
        
        if (showLoginBtn) {
            showLoginBtn.addEventListener('click', function(e) {
                e.preventDefault();
                loginWrap.style.display = 'block';
                returningNotice.style.display = 'none';
            });
        }
        
        if (hideLoginBtn) {
            hideLoginBtn.addEventListener('click', function(e) {
                e.preventDefault();
                loginWrap.style.display = 'none';
                returningNotice.style.display = 'flex';
            });
        }
        
        const loginBtn = document.getElementById('instinctor-login-btn');
        if (loginBtn) {
            loginBtn.addEventListener('click', async function() {
                const email = document.getElementById('instinctor-login-email').value;
                const password = document.getElementById('instinctor-login-password').value;
                const errorEl = document.getElementById('instinctor-login-error');
                
                if (!email || !password) {
                    errorEl.textContent = '<?php echo esc_js(__('Please enter email and password.', 'instinctor')); ?>';
                    errorEl.style.display = 'block';
                    return;
                }
                
                loginBtn.disabled = true;
                loginBtn.textContent = '<?php echo esc_js(__('Logging in...', 'instinctor')); ?>';
                
                try {
                    const response = await fetch(apiUrl + 'customer/login', {
                        method: 'POST',
                        headers: { 
                            'Content-Type': 'application/json',
                            'X-WP-Nonce': nonce
                        },
                        body: JSON.stringify({ email, password })
                    });
                    
                    const data = await response.json();
                    
                    if (data.success) {
                        window.location.reload();
                    } else {
                        errorEl.textContent = data.message || '<?php echo esc_js(__('Login failed. Please check your credentials.', 'instinctor')); ?>';
                        errorEl.style.display = 'block';
                        loginBtn.disabled = false;
                        loginBtn.textContent = '<?php echo esc_js(__('Login', 'instinctor')); ?>';
                    }
                } catch (err) {
                    errorEl.textContent = '<?php echo esc_js(__('An error occurred. Please try again.', 'instinctor')); ?>';
                    errorEl.style.display = 'block';
                    loginBtn.disabled = false;
                    loginBtn.textContent = '<?php echo esc_js(__('Login', 'instinctor')); ?>';
                }
            });
        }
        
        // Create account checkbox
        const createAccountCheckbox = document.getElementById('instinctor-create-account');
        const passwordFields = document.getElementById('instinctor-password-fields');
        
        if (createAccountCheckbox && passwordFields) {
            createAccountCheckbox.addEventListener('change', function() {
                passwordFields.style.display = this.checked ? 'block' : 'none';
                const passwordInput = document.getElementById('instinctor-password');
                if (passwordInput) {
                    passwordInput.required = this.checked;
                }
            });
        }

        // Gift Card handlers
        const applyGcBtn = document.getElementById('instinctor-apply-gift-card');
        if (applyGcBtn) {
            applyGcBtn.addEventListener('click', applyGiftCard);
            document.getElementById('instinctor-gift-card-code').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    applyGiftCard();
                }
            });
            document.getElementById('instinctor-remove-gift-card').addEventListener('click', removeGiftCard);
        }

        // Loyalty Points handlers
        const applyLoyaltyBtn = document.getElementById('instinctor-apply-loyalty');
        if (applyLoyaltyBtn) {
            applyLoyaltyBtn.addEventListener('click', applyLoyaltyPoints);
            document.getElementById('instinctor-loyalty-points').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    applyLoyaltyPoints();
                }
            });
            document.getElementById('instinctor-remove-loyalty').addEventListener('click', removeLoyaltyPoints);
        }
        
        // Shipping calculation on address change
        ['field-country', 'field-state', 'field-postcode'].forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.addEventListener('change', calculateShipping);
                if (id === 'field-postcode') {
                    el.addEventListener('blur', calculateShipping);
                }
            }
        });
    });
})();
<?php
$_chkJs = ob_get_clean();
if (function_exists('wp_add_inline_script')) {
    wp_add_inline_script('instinctor-frontend-js', $_chkJs, 'after');
} else {
    wp_print_inline_script_tag($_chkJs);
}
?>

<?php ob_start(); ?>
<?php if ($isPreview): ?>
/* Preview mode - hide admin bar and adjust body */
#wpadminbar, .admin-bar #wpadminbar { display: none !important; }
html.admin-bar { margin-top: 0 !important; }
body.admin-bar { margin-top: 0 !important; padding-top: 0 !important; }
html { margin-top: 0 !important; }
<?php endif; ?>

.instinctor-checkout *, .instinctor-checkout *::before, .instinctor-checkout *::after { box-sizing: border-box; }
.instinctor-checkout { width: 100%; margin: 0 auto; padding: 32px 20px; box-sizing: border-box; }
.instinctor-checkout h1 { font-size: 24px; font-weight: 600; margin: 0 0 24px; }

/* Layout-specific: Hide step indicators for non-multi-step */
.instinctor-checkout-one-page .instinctor-checkout-steps,
.instinctor-checkout-express .instinctor-checkout-steps { display: none; }

/* Layout-specific: Express layout - hide billing/shipping sections */
.instinctor-checkout-express .instinctor-section-billing,
.instinctor-checkout-express .instinctor-section-shipping,
.instinctor-checkout-express .instinctor-section-additional { display: none; }

/* Multi-step indicators - tab style matching preview */
.instinctor-checkout-steps { display: flex; gap: 6px; margin-bottom: 16px; }
.instinctor-step { flex: 1; text-align: center; padding: 8px 4px; background: <?php echo esc_attr($fieldBgColor); ?>; border-radius: 4px; font-size: 12px; font-weight: 600; color: <?php echo esc_attr($secondaryTextColor); ?>; cursor: pointer; transition: all 0.15s; }
.instinctor-step:hover { background: <?php echo esc_attr($borderColor); ?>; }
.instinctor-step.active { background: <?php echo esc_attr($btnColor); ?>; color: <?php echo esc_attr($btnTextColor); ?>; }

/* Multi-step section container */
.instinctor-step-section { border: 1px dashed <?php echo esc_attr($borderColor); ?>; border-radius: <?php echo intval($fieldRadius); ?>px; padding: 14px; margin-bottom: 12px; background: rgba(255,255,255,0.5); }
.instinctor-step-section-title { font-size: 10px; font-weight: 600; color: <?php echo esc_attr($textColor); ?>; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; opacity: 0.6; }

.instinctor-checkout-grid { display: block; max-width: 460px; margin: 0 auto; }

.instinctor-checkout-main { background: transparent; padding: 0; }
.instinctor-checkout-sidebar { margin: 8px 0 0; }
.instinctor-checkout input::placeholder, .instinctor-checkout textarea::placeholder, .instinctor-an-fields input::placeholder { color: #999; opacity: 1; }
.instinctor-member-hidden { display: none !important; }
.instinctor-member-identity { background: #f5f5f7; border-radius: 8px; padding: 12px 16px; font-size: 14px; color: #1d2327; margin-bottom: 16px; }
.instinctor-member-identity strong { font-weight: 600; }
.instinctor-saved-card { background: #f5f5f7; border-radius: 8px; padding: 14px 16px; margin-bottom: 12px; }
.instinctor-saved-card-info { display: flex; align-items: center; justify-content: space-between; gap: 12px; font-size: 14px; color: #1d2327; }
.instinctor-saved-card-exp { color: #999; }
.instinctor-use-new-card { font-size: 13px; color: #555; text-decoration: underline; white-space: nowrap; }
.instinctor-member-checkout .instinctor-member-identity { margin: 0 0 8px !important; }
.instinctor-member-checkout .instinctor-fields-grid { margin: 0 0 8px !important; }
.instinctor-member-checkout .instinctor-fields-grid.instinctor-member-hidden { display: none !important; margin: 0 !important; }
.instinctor-member-checkout .instinctor-payment-area { margin: 0 !important; }
.instinctor-member-checkout .instinctor-saved-card { margin: 0 !important; }
.instinctor-member-checkout .instinctor-checkout-sidebar { margin: 8px 0 0 !important; }
.instinctor-already-subscribed-panel { display: none; }
.instinctor-member-subscribed .instinctor-already-subscribed-panel { display: block; background: #f5f5f7; border-radius: 12px; padding: 32px 28px; text-align: center; }
.instinctor-member-subscribed .instinctor-already-subscribed-panel h2 { font-size: 18px; font-weight: 600; margin: 0 0 8px; color: #1d2327; }
.instinctor-member-subscribed .instinctor-already-subscribed-panel p { color: #555; font-size: 14px; margin: 0 0 20px; }
.instinctor-member-subscribed .instinctor-already-subscribed-panel .instinctor-place-order-btn { display: inline-block; width: auto; padding: 12px 28px; text-decoration: none; }
.instinctor-member-subscribed .instinctor-member-identity,
.instinctor-member-subscribed .instinctor-fields-grid,
.instinctor-member-subscribed .instinctor-create-account-row,
.instinctor-member-subscribed .instinctor-payment-area,
.instinctor-member-subscribed .instinctor-checkout-sidebar { display: none !important; }
.instinctor-create-account-row { display: flex; align-items: center; margin: 0; }
@media (max-width: 640px) {
    .instinctor-checkout-main,
    .instinctor-checkout-sidebar { max-width: 100%; padding-left: 16px; padding-right: 16px; box-sizing: border-box; }
}

/* Account section - no box */
.instinctor-account-section { margin-bottom: 28px; }

/* Express section - subtle styling */
.instinctor-express-section { margin-bottom: 20px; }

/* Payment area - no box */
.instinctor-payment-area { margin-top: 8px; }

/* Fields Grid - 2 column grid matching backend preview */
.instinctor-checkout .instinctor-fields-grid { display: grid !important; grid-template-columns: 1fr 1fr !important; gap: 8px !important; }
.instinctor-checkout .instinctor-fields-grid .instinctor-form-row { margin-bottom: 0 !important; min-width: 0 !important; }
.instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-full { grid-column: span 2 !important; }
.instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-half { grid-column: span 1 !important; }

/* Tablet responsive widths (768px - 1024px) */
@media (max-width: 1024px) and (min-width: 601px) {
    .instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-tablet-full { grid-column: span 2 !important; }
    .instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-tablet-half { grid-column: span 1 !important; }
}

/* Mobile responsive widths */
@media (max-width: 600px) {
    .instinctor-checkout .instinctor-fields-grid { grid-template-columns: 1fr 1fr !important; }
    .instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-mobile-full { grid-column: span 2 !important; }
    .instinctor-checkout .instinctor-fields-grid .instinctor-form-row.instinctor-field-mobile-half { grid-column: span 1 !important; }
}

/* Hide labels visually but keep for screen readers */
.instinctor-form-row label.screen-reader-text { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
.instinctor-form-row label .required { color: #c62828; }
.instinctor-form-row input,
.instinctor-form-row select,
.instinctor-form-row textarea { width: 100%; padding: 10px 12px; font-size: 14px; border: <?php echo esc_attr($fieldBorderWidth); ?>px solid <?php echo esc_attr($fieldBorderColor); ?>; border-radius: <?php echo intval($fieldRadius); ?>px; background: <?php echo esc_attr($fieldBgColor); ?>; transition: border-color 0.15s; color: <?php echo esc_attr($fieldTextColor); ?>; box-sizing: border-box; }
.instinctor-form-row input::placeholder,
.instinctor-form-row textarea::placeholder { color: <?php echo esc_attr($fieldTextColor); ?>; opacity: 0.5; }
.instinctor-form-row select { color: <?php echo esc_attr($fieldTextColor); ?>; opacity: 0.7; }
.instinctor-form-row input:focus,
.instinctor-form-row select:focus,
.instinctor-form-row textarea:focus { border-color: <?php echo esc_attr($btnColor); ?>; outline: none; }
.instinctor-form-row input.error { border-color: #c62828; }

/* Express Checkout */
.instinctor-express-section { text-align: center; }
.instinctor-express-divider { display: flex; align-items: center; margin-top: 20px; color: <?php echo esc_attr($secondaryTextColor); ?>; font-size: 13px; }
.instinctor-express-divider::before,
.instinctor-express-divider::after { content: ''; flex: 1; height: 1px; background: <?php echo esc_attr($borderColor); ?>; }
.instinctor-express-divider span { padding: 0 16px; }

/* Payment Methods */
.instinctor-payment-methods { display: flex; gap: 12px; margin-bottom: 20px; }
.instinctor-payment-method { flex: 1; cursor: pointer; }
.instinctor-payment-method input { display: none; }
.instinctor-payment-method span { display: block; padding: 14px 20px; border: 2px solid <?php echo esc_attr($borderColor); ?>; border-radius: 8px; text-align: center; font-size: 14px; font-weight: 500; transition: all 0.15s; }
.instinctor-payment-method input:checked + span { border-color: <?php echo esc_attr($btnColor); ?>; background: <?php echo esc_attr($fieldBgColor); ?>; }
.instinctor-payment-method span:hover { border-color: <?php echo esc_attr($btnColor); ?>; }

#instinctor-card-element { padding: 10px 12px; border: <?php echo esc_attr($fieldBorderWidth); ?>px solid <?php echo esc_attr($fieldBorderColor); ?>; border-radius: <?php echo intval($fieldRadius); ?>px; background: <?php echo esc_attr($fieldBgColor); ?>; }
.instinctor-error-message { color: #c62828; font-size: 13px; margin-top: 8px; }
.instinctor-demo-payment { padding: 20px; background: #f5f5f7; border-radius: 8px; text-align: center; }
.instinctor-demo-payment p { margin: 0; color: #86868b; font-size: 14px; }

/* Step Navigation */
.instinctor-step-nav { display: flex; justify-content: space-between; margin-top: 16px; }
.instinctor-btn, .instinctor-checkout-container .instinctor-btn, button.instinctor-btn { display: inline-flex; align-items: center; justify-content: center; height: 44px; padding: 0 24px; font-size: 14px; font-weight: 600; border-radius: <?php echo (int) $buttonRadius; ?>px; cursor: pointer; transition: all 0.15s; outline: none !important; outline-style: none !important; outline-width: 0 !important; -webkit-appearance: none; -moz-appearance: none; appearance: none; }
.instinctor-btn:focus, .instinctor-btn:focus-visible, .instinctor-btn:active, .instinctor-btn:focus-within, 
.instinctor-checkout-container .instinctor-btn:focus, .instinctor-checkout-container .instinctor-btn:focus-visible,
button.instinctor-btn:focus, button.instinctor-btn:focus-visible { outline: none !important; outline-style: none !important; outline-width: 0 !important; box-shadow: none !important; border-color: inherit; }
.instinctor-btn::-moz-focus-inner, button.instinctor-btn::-moz-focus-inner { border: 0 !important; outline: 0 !important; }
.instinctor-btn-primary, .instinctor-checkout-container .instinctor-btn-primary, button.instinctor-btn-primary { background: <?php echo esc_attr($btnColor); ?>; color: <?php echo esc_attr($btnTextColor); ?>; border: none !important; outline: none !important; }
.instinctor-btn-primary:hover { opacity: 0.9; }
.instinctor-btn-primary:focus, .instinctor-btn-primary:focus-visible, .instinctor-btn-primary:active { outline: none !important; outline-style: none !important; border: none !important; box-shadow: none !important; }
.instinctor-btn-secondary, .instinctor-checkout-container .instinctor-btn-secondary, button.instinctor-btn-secondary { background: #fff; color: <?php echo esc_attr($textColor); ?>; border: 1px solid <?php echo esc_attr($borderColor); ?> !important; outline: none !important; }
.instinctor-btn-secondary:hover { border-color: <?php echo esc_attr($btnColor); ?> !important; }
.instinctor-btn-secondary:focus, .instinctor-btn-secondary:focus-visible, .instinctor-btn-secondary:active { outline: none !important; outline-style: none !important; box-shadow: none !important; }
.instinctor-btn-outline { background: transparent; color: <?php echo esc_attr($secondaryTextColor); ?>; border: 2px solid <?php echo esc_attr($borderColor); ?> !important; outline: none !important; width: 100%; }
.instinctor-btn-outline:hover { border-color: <?php echo esc_attr($btnColor); ?> !important; color: <?php echo esc_attr($textColor); ?>; }
.instinctor-btn-outline:focus, .instinctor-btn-outline:focus-visible { outline: none !important; box-shadow: none !important; }
#instinctor-next-step, #instinctor-prev-step { outline: none !important; outline-style: none !important; }
#instinctor-next-step:focus, #instinctor-next-step:focus-visible, #instinctor-prev-step:focus, #instinctor-prev-step:focus-visible { outline: none !important; outline-style: none !important; box-shadow: none !important; }
#instinctor-next-step:focus { border: 2px solid <?php echo esc_attr($borderColor); ?> !important; }
#instinctor-prev-step:focus { border: 1px solid <?php echo esc_attr($borderColor); ?> !important; }

/* Order Summary */
.instinctor-order-summary { background: #f5f5f7; border-radius: 12px; padding: 24px; }
.instinctor-order-summary h2 { font-size: 15px; font-weight: 600; margin: 0 0 20px; }

.instinctor-order-item { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid #e8e8ed; }
.instinctor-order-item:last-child { border-bottom: none; }
.instinctor-order-item-image { width: 48px; height: 48px; border-radius: <?php echo intval($fieldRadius); ?>px; object-fit: cover; background: #fff; }
.instinctor-order-item-details { flex: 1; min-width: 0; }
.instinctor-order-item-name { display: block; font-size: 14px; font-weight: 500; }

/* Compact membership summary: bold plan title inline with the Pay button, no
   "Summary" heading, no box, uniform 8px gaps. Memberships only. */
.instinctor-order-summary-compact { background: transparent; padding: 0; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.instinctor-order-summary-compact > #instinctor-order-bumps:empty { display: none; }
.instinctor-order-summary-compact #instinctor-order-items { flex: 1 1 auto; min-width: 0; margin: 0; }
.instinctor-order-summary-compact .instinctor-order-item { padding: 0; border: none; gap: 8px; }
.instinctor-order-summary-compact .instinctor-order-item-name { font-size: 16px; font-weight: 700; color: #1d2327; }
.instinctor-order-summary-compact .instinctor-order-totals { flex-basis: 100%; margin: 0; border: none; padding: 0; }
.instinctor-order-summary-compact .instinctor-place-order-btn { flex: 0 0 auto; width: auto; margin: 0; padding: 12px 28px; }
.instinctor-order-summary-compact .instinctor-error-message { flex-basis: 100%; }
.instinctor-order-summary-compact .instinctor-secure-badge { flex-basis: 100%; justify-content: center; }
.instinctor-order-item-qty { display: block; font-size: 12px; color: #86868b; }
.instinctor-order-item-price { font-size: 14px; font-weight: 500; }

.instinctor-order-bumps { margin-top: 16px; }
.instinctor-order-bump { display: flex; align-items: flex-start; gap: 10px; background: #fff; border: 2px dashed #d2d2d7; border-radius: 8px; padding: 12px; margin-bottom: 8px; cursor: pointer; transition: all 0.15s; }
.instinctor-order-bump:hover { border-color: #1d1d1f; }
.instinctor-order-bump.selected { border-style: solid; border-color: #2e7d32; background: #e8f5e9; }
.instinctor-bump-checkbox { flex-shrink: 0; padding-top: 2px; }
.instinctor-bump-checkbox input { width: 16px; height: 16px; margin: 0; cursor: pointer; }
.instinctor-bump-content { flex: 1; min-width: 0; }
.instinctor-bump-title { font-size: 13px; font-weight: 600; color: #1d1d1f; }
.instinctor-bump-description { font-size: 12px; color: #86868b; margin-top: 2px; }
.instinctor-bump-price { font-size: 14px; font-weight: 600; color: #2e7d32; white-space: nowrap; }

/* Coupon */
.instinctor-coupon-section { margin-top: 16px; padding-top: 16px; border-top: 1px solid #e8e8ed; }
.instinctor-coupon-form { display: flex; gap: 8px; }
.instinctor-coupon-form input { flex: 1; padding: 10px 12px; font-size: 13px; border: 1px solid #d2d2d7; border-radius: <?php echo intval($fieldRadius); ?>px; text-transform: uppercase; }
.instinctor-coupon-form input:focus { border-color: <?php echo esc_attr($btnColor); ?>; outline: none; }
.instinctor-coupon-form button { padding: 10px 16px; font-size: 13px; font-weight: 500; background: #fff; border: 1px solid #d2d2d7; border-radius: <?php echo (int) $buttonRadius; ?>px; cursor: pointer; white-space: nowrap; }
.instinctor-coupon-form button:hover { border-color: #1d1d1f; }
.instinctor-coupon-applied { display: flex; align-items: center; justify-content: space-between; background: #e8f5e9; padding: 10px 12px; border-radius: <?php echo intval($fieldRadius); ?>px; }
.instinctor-coupon-applied span { font-family: monospace; font-size: 13px; font-weight: 600; color: #2e7d32; }
.instinctor-coupon-applied button { background: none; border: none; font-size: 18px; color: #2e7d32; cursor: pointer; padding: 0 4px; }
.instinctor-coupon-applied button:hover { color: #1b5e20; }
.instinctor-coupon-error { color: #c62828; font-size: 12px; margin-top: 6px; }
.instinctor-discount-row { color: #2e7d32; }

/* Gift Card */
.instinctor-gift-card-section { margin-top: 12px; }
.instinctor-gift-card-form { display: flex; gap: 8px; }
.instinctor-gift-card-form input { flex: 1; padding: 10px 12px; font-size: 13px; border: 1px solid #d2d2d7; border-radius: <?php echo intval($fieldRadius); ?>px; text-transform: uppercase; }
.instinctor-gift-card-form input:focus { border-color: <?php echo esc_attr($btnColor); ?>; outline: none; }
.instinctor-gift-card-form button { padding: 10px 16px; font-size: 13px; font-weight: 500; background: #fff; border: 1px solid #d2d2d7; border-radius: <?php echo (int) $buttonRadius; ?>px; cursor: pointer; white-space: nowrap; }
.instinctor-gift-card-form button:hover { border-color: #1d1d1f; }
.instinctor-gift-card-applied { display: flex; align-items: center; justify-content: space-between; background: #e3f2fd; padding: 10px 12px; border-radius: <?php echo intval($fieldRadius); ?>px; }
.instinctor-gift-card-applied span { font-family: monospace; font-size: 13px; font-weight: 600; color: #1565c0; }
.instinctor-gift-card-applied button { background: none; border: none; font-size: 18px; color: #1565c0; cursor: pointer; padding: 0 4px; }
.instinctor-gift-card-applied button:hover { color: #0d47a1; }
.instinctor-gift-card-error { color: #c62828; font-size: 12px; margin-top: 6px; }
.instinctor-gift-card-row { color: #1565c0; }

/* Loyalty Points */
.instinctor-loyalty-section { margin-top: 12px; padding: 12px; background: linear-gradient(135deg, #ffd700 0%, #ffb300 100%); border-radius: 8px; }
.instinctor-loyalty-balance { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #333; margin-bottom: 8px; }
.instinctor-loyalty-balance strong { font-size: 16px; }
.instinctor-loyalty-balance small { opacity: 0.7; }
.instinctor-loyalty-form { display: flex; gap: 8px; }
.instinctor-loyalty-form input { flex: 1; padding: 10px 12px; font-size: 13px; border: 1px solid rgba(0,0,0,0.2); border-radius: <?php echo intval($fieldRadius); ?>px; background: rgba(255,255,255,0.9); }
.instinctor-loyalty-form input:focus { border-color: <?php echo esc_attr($btnColor); ?>; outline: none; }
.instinctor-loyalty-form button { padding: 10px 16px; font-size: 13px; font-weight: 600; background: #333; color: #fff; border: none; border-radius: <?php echo (int) $buttonRadius; ?>px; cursor: pointer; white-space: nowrap; }
.instinctor-loyalty-form button:hover { background: #000; }
.instinctor-loyalty-applied { display: flex; align-items: center; justify-content: space-between; background: rgba(255,255,255,0.9); padding: 10px 12px; border-radius: <?php echo intval($fieldRadius); ?>px; }
.instinctor-loyalty-applied span { font-size: 13px; font-weight: 600; color: #333; }
.instinctor-loyalty-applied button { background: none; border: none; font-size: 18px; color: #333; cursor: pointer; padding: 0 4px; }
.instinctor-loyalty-error { color: #c62828; font-size: 12px; margin-top: 6px; background: #fff; padding: 4px 8px; border-radius: 4px; }
.instinctor-loyalty-min-notice { display: block; font-size: 11px; opacity: 0.7; margin-top: 4px; }
.instinctor-loyalty-row { color: #f57c00; }

.instinctor-order-totals { border-top: 1px solid #d2d2d7; margin-top: 20px; padding-top: 20px; }
.instinctor-totals-row { display: flex; justify-content: space-between; padding: 6px 0; font-size: 14px; }
.instinctor-totals-row.instinctor-total { font-size: 17px; font-weight: 600; margin-top: 12px; padding-top: 12px; border-top: 1px solid #d2d2d7; }

.instinctor-place-order-btn { width: 100%; padding: 12px; font-size: 14px; font-weight: 600; color: <?php echo esc_attr($btnTextColor); ?>; background: <?php echo esc_attr($btnColor); ?>; border: none; border-radius: <?php echo intval($fieldRadius); ?>px; cursor: pointer; margin-top: 12px; transition: background 0.15s; }
.instinctor-place-order-btn:hover { opacity: 0.9; }
.instinctor-place-order-btn:disabled { background: <?php echo esc_attr($borderColor); ?>; cursor: not-allowed; }

.instinctor-secure-badge { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 16px; font-size: 12px; color: #86868b; }

.instinctor-loading { text-align: center; padding: 24px; }
.instinctor-spinner { display: inline-block; width: 24px; height: 24px; border: 2px solid #e8e8ed; border-top-color: #1d1d1f; border-radius: 50%; animation: spin 0.6s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }

.instinctor-empty-cart { color: #86868b; font-size: 14px; text-align: center; padding: 20px; }

/* Shipping Methods */
.instinctor-shipping-methods { margin-top: 16px; padding-top: 16px; border-top: 1px solid #e8e8ed; }
.instinctor-shipping-title { font-size: 12px; font-weight: 600; color: #86868b; text-transform: uppercase; margin-bottom: 8px; }
.instinctor-shipping-option { display: flex; align-items: center; gap: 8px; padding: 10px 12px; background: #f5f5f7; border-radius: <?php echo intval($fieldRadius); ?>px; margin-bottom: 6px; cursor: pointer; }
.instinctor-shipping-option:hover { background: #e8e8ed; }
.instinctor-shipping-option.selected { background: #e8f5e9; }
.instinctor-shipping-option input { margin: 0; }
.instinctor-shipping-name { flex: 1; font-size: 13px; }
.instinctor-shipping-cost { font-size: 13px; font-weight: 500; }
.instinctor-shipping-row span:last-child { font-size: 12px; color: #86868b; }

/* Base Colors - from config, can be overridden by style presets */
.instinctor-checkout .instinctor-place-order-btn { 
    background: <?php echo esc_attr($btnColor); ?>; 
    color: <?php echo esc_attr($btnTextColor); ?>; 
}
.instinctor-checkout .instinctor-place-order-btn:hover { 
    background: <?php echo esc_attr($btnColor); ?>; 
    filter: brightness(0.9);
}
.instinctor-checkout .instinctor-form-row input,
.instinctor-checkout .instinctor-form-row select,
.instinctor-checkout .instinctor-form-row textarea { 
    background: <?php echo esc_attr($fieldBgColor); ?>;
    border-color: <?php echo esc_attr($fieldBorderColor); ?>; 
}
.instinctor-checkout .instinctor-form-row input:focus,
.instinctor-checkout .instinctor-form-row select:focus { 
    border-color: <?php echo esc_attr($btnColor); ?>; 
}
.instinctor-checkout .instinctor-checkout-section { 
    border-color: <?php echo esc_attr($borderColor); ?>; 
}
.instinctor-checkout .instinctor-payment-method input:checked + span { 
    border-color: <?php echo esc_attr($btnColor); ?>; 
}

/* Style: Minimal - transparent backgrounds, underline inputs */
.instinctor-style-minimal .instinctor-checkout-section { border: none !important; border-radius: 0 !important; padding: 24px 16px !important; border-bottom: 1px solid <?php echo esc_attr($borderColor); ?> !important; background: transparent !important; }
.instinctor-style-minimal .instinctor-form-row input,
.instinctor-style-minimal .instinctor-form-row select,
.instinctor-style-minimal .instinctor-form-row textarea { border: none !important; border-bottom: <?php echo esc_attr($fieldBorderWidth); ?>px solid <?php echo esc_attr($fieldBorderColor); ?> !important; border-radius: 0 !important; padding: 12px 8px !important; background: transparent !important; }
.instinctor-style-minimal .instinctor-form-row input:focus,
.instinctor-style-minimal .instinctor-form-row select:focus { border-bottom-color: <?php echo esc_attr($btnColor); ?> !important; }
.instinctor-style-minimal .instinctor-order-summary { background: transparent !important; border: 1px solid <?php echo esc_attr($borderColor); ?> !important; border-radius: 0 !important; padding: 24px 16px !important; }
.instinctor-style-minimal #instinctor-card-element { border: none !important; border-bottom: <?php echo esc_attr($fieldBorderWidth); ?>px solid <?php echo esc_attr($fieldBorderColor); ?> !important; border-radius: 0 !important; background: transparent !important; }
.instinctor-style-minimal .instinctor-place-order-btn { 
    background: transparent !important; 
    color: <?php echo esc_attr($btnColor); ?> !important; 
    border: 2px solid <?php echo esc_attr($btnColor); ?> !important; 
}
.instinctor-style-minimal .instinctor-place-order-btn:hover { 
    background: <?php echo esc_attr($btnColor); ?> !important; 
    color: <?php echo esc_attr($btnTextColor); ?> !important; 
    filter: none;
}

/* Style: Classic - Traditional form look, square corners */
.instinctor-style-classic .instinctor-checkout-section { border-radius: 0 !important; border: 2px solid <?php echo esc_attr($borderColor); ?> !important; }
.instinctor-style-classic .instinctor-form-row input,
.instinctor-style-classic .instinctor-form-row select,
.instinctor-style-classic .instinctor-form-row textarea { border-radius: 0 !important; border: 2px solid <?php echo esc_attr($fieldBorderColor); ?> !important; background: <?php echo esc_attr($fieldBgColor); ?> !important; }
.instinctor-style-classic .instinctor-place-order-btn { border-radius: 0 !important; background: <?php echo esc_attr($btnColor); ?> !important; text-transform: uppercase !important; letter-spacing: 1px !important; }
.instinctor-style-classic .instinctor-order-summary { border-radius: 0 !important; border: 2px solid <?php echo esc_attr($borderColor); ?> !important; }
.instinctor-style-classic .instinctor-payment-method span { border-radius: 0 !important; border-width: 2px !important; }
.instinctor-style-classic #instinctor-card-element { border-radius: 0 !important; border: 2px solid <?php echo esc_attr($fieldBorderColor); ?> !important; background: <?php echo esc_attr($fieldBgColor); ?> !important; }
.instinctor-style-classic .instinctor-order-item-image { border-radius: 0 !important; }

/* Style: Bold - Large rounded corners, prominent inputs */
.instinctor-style-bold .instinctor-checkout-section { border-radius: 16px !important; border-width: 2px !important; }
.instinctor-style-bold .instinctor-form-row input,
.instinctor-style-bold .instinctor-form-row select,
.instinctor-style-bold .instinctor-form-row textarea { border-radius: 12px !important; background: <?php echo esc_attr($fieldBgColor); ?> !important; border: none !important; padding: 14px 16px !important; font-size: 16px !important; }
.instinctor-style-bold .instinctor-form-row input:focus,
.instinctor-style-bold .instinctor-form-row select:focus { background: <?php echo esc_attr($formBgColor); ?> !important; box-shadow: 0 0 0 2px <?php echo esc_attr($btnColor); ?> !important; }
.instinctor-style-bold .instinctor-place-order-btn { border-radius: 12px !important; padding: 18px !important; font-size: 17px !important; }
.instinctor-style-bold .instinctor-order-summary { border-radius: 16px !important; }
.instinctor-style-bold .instinctor-payment-method span { border-radius: 12px !important; border-width: 2px !important; padding: 16px !important; }
.instinctor-style-bold #instinctor-card-element { border-radius: 12px !important; background: <?php echo esc_attr($fieldBgColor); ?> !important; border: none !important; padding: 16px !important; }
.instinctor-style-bold .instinctor-order-item-image { border-radius: 10px !important; }
.instinctor-style-bold .instinctor-checkout-section h2 { font-size: 17px !important; }

/* Account Section */
.instinctor-account-section { margin-bottom: 20px; padding-bottom: 0; }
.instinctor-returning-customer { 
    background: #f5f5f7; 
    height: <?php echo intval($fieldHeight); ?>px; padding: 0 18px; box-sizing: border-box; 
    border-radius: 8px; 
    font-size: 14px; 
    display: flex; 
    align-items: center; 
    gap: 8px;
}
.instinctor-returning-customer a { color: <?php echo esc_attr($btnColor); ?>; font-weight: 500; }
.instinctor-login-form-wrap { 
    background: #f5f5f7; 
    padding: 20px; 
    border-radius: 8px;
    margin-top: 0;
}
.instinctor-login-form-wrap h3 { margin: 0 0 16px; font-size: 16px; }
.instinctor-login-form .instinctor-form-row { margin-bottom: 12px; }
.instinctor-login-submit { 
    background: <?php echo esc_attr($btnColor); ?>; 
    color: <?php echo esc_attr($btnTextColor); ?>; 
    border: none; 
    padding: 12px 24px; 
    border-radius: <?php echo (int) $buttonRadius; ?>px; 
    cursor: pointer; 
    font-weight: 600;
    margin-right: 12px;
}
.instinctor-cancel-login { color: #666; font-size: 14px; }
.instinctor-login-error { 
    background: #fee; 
    color: #c00; 
    padding: 10px 14px; 
    border-radius: <?php echo intval($fieldRadius); ?>px; 
    margin-bottom: 12px; 
    font-size: 13px; 
}
.instinctor-login-required { text-align: center; padding: 40px 20px; }
.instinctor-login-required h2 { margin: 0 0 8px; }
.instinctor-login-required p { color: #666; margin: 0 0 20px; }
.instinctor-login-btn { 
    display: inline-block;
    background: <?php echo esc_attr($btnColor); ?>; 
    color: <?php echo esc_attr($btnTextColor); ?>; 
    padding: 12px 32px; 
    border-radius: <?php echo (int) $buttonRadius; ?>px; 
    text-decoration: none;
    font-weight: 600;
}
.instinctor-register-link { margin-top: 16px; font-size: 14px; color: #666; }
.instinctor-register-link a { color: <?php echo esc_attr($btnColor); ?>; }

/* Create Account — checkbox under first name + password under last name, inline in the 2-col grid */
.instinctor-create-account-row { display: flex; align-items: center; margin: 0; }
.instinctor-checkbox-label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    font-weight: 500;
}
.instinctor-checkbox-label input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: <?php echo esc_attr($btnColor); ?>;
}
.instinctor-password-fields { margin: 0; }

<?php
// Responsive overrides from Impulse settings
if ($impulseSettings) {
    $fieldSels = '.instinctor-form-row input,.instinctor-form-row select,.instinctor-form-row textarea,#instinctor-card-element,.instinctor-coupon-form input,.instinctor-gift-card-form input,.instinctor-loyalty-form input';
    $btnSels = '.instinctor-btn,.instinctor-place-order-btn,.instinctor-coupon-form button,.instinctor-gift-card-form button,.instinctor-loyalty-form button';
    foreach (['tablet' => '1024', 'mobile' => '768'] as $dv => $bp) {
        $fr = $impulseSettings['checkout_design_field_radius_' . $dv] ?? null;
        $fbw = $impulseSettings['checkout_design_field_border_width_' . $dv] ?? null;
        $br = $impulseSettings['checkout_design_button_radius_' . $dv] ?? null;
        if ($fr !== null || $fbw !== null || $br !== null) {
            echo '@media(max-width:' . esc_attr($bp) . 'px){';
            if ($fr !== null) echo '.instinctor-checkout ' . esc_attr($fieldSels) . '{border-radius:' . intval($fr) . 'px!important}';
            if ($fbw !== null) echo '.instinctor-checkout ' . esc_attr($fieldSels) . '{border-width:' . intval($fbw) . 'px!important}';
            if ($br !== null) echo '.instinctor-checkout ' . esc_attr($btnSels) . '{border-radius:' . intval($br) . 'px!important}';
            echo '}';
        }
    }
}
?>
<?php $_inst_lcss = ob_get_clean(); wp_add_inline_style("instinctor-page-inline", $_inst_lcss); ?>
