<?php
/**
 * Checkout Widget - Render Functions
 *
 * Standalone functions prefixed ggmc_checkout_ used by the widget render() method.
 *
 * @package GGM_Commerce
 */

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

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

/**
 * Check if we're in the Elementor editor or preview mode.
 *
 * @return bool
 */
function ggmc_checkout_is_editor_mode() {
    if ( ggmc_is_editor_mode() ) {
        return true;
    }
    if ( class_exists( '\Elementor\Plugin' ) && isset( \Elementor\Plugin::$instance->preview ) ) {
        return \Elementor\Plugin::$instance->preview->is_preview_mode();
    }
    return false;
}

/**
 * Generate dummy cart items for editor preview.
 *
 * @param int $count Number of items to generate.
 * @return array
 */
function ggmc_checkout_get_preview_cart_items( $count = 2 ) {
    // Use different background colors for visual variety
    $colors = ['#e2e8f0', '#dbeafe', '#dcfce7', '#fef3c7'];
    $text_colors = ['#64748b', '#3b82f6', '#22c55e', '#d97706'];

    $sample_products = [
        [
            'name' => 'Premium Wireless Headphones',
            'price' => 149.99,
            'quantity' => 1,
            'color' => 0,
        ],
        [
            'name' => 'Organic Cotton T-Shirt (Blue, M)',
            'price' => 34.99,
            'quantity' => 2,
            'color' => 1,
        ],
        [
            'name' => 'Stainless Steel Water Bottle',
            'price' => 24.99,
            'quantity' => 1,
            'color' => 2,
        ],
        [
            'name' => 'Leather Wallet - Brown',
            'price' => 59.99,
            'quantity' => 1,
            'color' => 3,
        ],
    ];

    $items = [];
    for ($i = 0; $i < min($count, 4); $i++) {
        $product = $sample_products[$i];
        $color_idx = $product['color'];
        $items['preview_' . $i] = [
            'product_id' => 999 + $i,
            'product_name' => $product['name'],
            'price' => $product['price'],
            'quantity' => $product['quantity'],
            'line_total' => $product['price'] * $product['quantity'],
            'image_url' => '', // Empty - we'll use placeholder div
            'preview_color' => $colors[$color_idx],
            'preview_text_color' => $text_colors[$color_idx],
        ];
    }

    return $items;
}

/**
 * Generate preview totals for editor.
 *
 * @param array $cart_items Preview cart items.
 * @param array $settings   Widget settings.
 * @return array
 */
function ggmc_checkout_get_preview_totals( $cart_items, $settings ) {
    $subtotal = 0;
    foreach ($cart_items as $item) {
        $subtotal += $item['line_total'];
    }

    $show_discount = ($settings['preview_show_discount'] ?? 'yes') === 'yes';
    $show_shipping = ($settings['preview_show_shipping_options'] ?? 'yes') === 'yes';

    $discount_amount = $show_discount ? round($subtotal * 0.1, 2) : 0; // 10% discount preview
    $shipping_amount = $show_shipping ? 9.99 : 0;
    $tax_amount = round(($subtotal - $discount_amount) * 0.08, 2); // 8% tax preview
    $grand_total = $subtotal - $discount_amount + $shipping_amount + $tax_amount;

    return [
        'subtotal' => $subtotal,
        'tax_amount' => $tax_amount,
        'tax_label' => __('Tax (8%)', 'ggm-commerce'),
        'prices_include_tax' => false,
        'shipping_amount' => $shipping_amount,
        'shipping_label' => __('Shipping', 'ggm-commerce'),
        'shipping_method_name' => $show_shipping ? __('Standard Shipping', 'ggm-commerce') : '',
        'shipping_methods' => $show_shipping ? [
            [
                'id' => 'preview_standard',
                'name' => __('Standard Shipping', 'ggm-commerce'),
                'cost' => 9.99,
                'formatted_cost' => '$9.99',
                'selected' => true,
            ],
            [
                'id' => 'preview_express',
                'name' => __('Express Shipping', 'ggm-commerce'),
                'cost' => 19.99,
                'formatted_cost' => '$19.99',
                'selected' => false,
            ],
        ] : [],
        'allows_shipping_choice' => $show_shipping,
        'discount_amount' => $discount_amount,
        'discount_code' => $show_discount ? 'SAVE10' : '',
        'discount_type' => $show_discount ? 'percentage' : '',
        'discount_message' => $show_discount ? __('10% discount applied!', 'ggm-commerce') : '',
        'free_shipping_from_discount' => false,
        'total' => round($grand_total, 2),
    ];
}

/**
 * Render custom checkout fields for a given position.
 *
 * @param \GGM_Commerce_Base_Widget $widget   Widget instance.
 * @param string                    $position Position identifier.
 */
function ggmc_checkout_render_checkout_custom_fields( $widget, $position ) {
    // Premium gate check.
    if ( ! function_exists( 'ggm_commerce_license' ) ) {
        return;
    }
    $license = ggm_commerce_license();
    if ( ! $license->is_widget_activated( 'checkout-fields' ) ) {
        return;
    }

    if ( ! class_exists( 'GGM_Commerce_Checkout_Fields' ) ) {
        return;
    }

    $manager = GGM_Commerce_Checkout_Fields::get_instance();
    $data    = $manager->get_fields_by_position( $position );

    // Nothing to render.
    if ( empty( $data['groups'] ) && empty( $data['ungrouped'] ) ) {
        return;
    }

    // Sidebar positions render inline without a checkout-section card.
    $is_sidebar = ( 'after_order_summary_totals' === $position );
    $section_class = $is_sidebar ? 'checkout-custom-fields-group' : 'checkout-section checkout-custom-fields-group';
    $ungrouped_class = $is_sidebar ? 'checkout-custom-fields-ungrouped' : 'checkout-section checkout-custom-fields-ungrouped';

    // Render grouped fields.
    foreach ( $data['groups'] as $group_data ) {
        $group  = $group_data['group'];
        $fields = $group_data['fields'];
        ?>
        <div class="<?php echo esc_attr( $section_class ); ?>">
            <h3><?php echo esc_html( $group->name ); ?></h3>
            <?php if ( ! empty( $group->description ) ) : ?>
                <p class="section-description"><?php echo esc_html( $group->description ); ?></p>
            <?php endif; ?>
            <div class="ggmc-custom-fields-row">
                <?php foreach ( $fields as $field ) : ?>
                    <?php ggmc_checkout_render_single_checkout_field( $field, $is_sidebar ); ?>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }

    // Render ungrouped fields.
    if ( ! empty( $data['ungrouped'] ) ) {
        ?>
        <div class="<?php echo esc_attr( $ungrouped_class ); ?>">
            <div class="ggmc-custom-fields-row">
                <?php foreach ( $data['ungrouped'] as $field ) : ?>
                    <?php ggmc_checkout_render_single_checkout_field( $field, $is_sidebar ); ?>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }
}

/**
 * Render a single custom checkout field.
 *
 * @param object $field      Field object.
 * @param bool   $is_sidebar Whether rendering in sidebar context.
 */
function ggmc_checkout_render_single_checkout_field( $field, $is_sidebar = false ) {
    $field_id    = 'custom_field_' . $field->id;
    $field_name  = 'custom_fields[' . $field->id . ']';
    $required    = $field->required ? ' required' : '';
    $req_mark    = $field->required ? ' <span class="required">*</span>' : '';
    $value       = $field->default_value ?? '';
    $is_checkbox = in_array( $field->field_type, array( 'checkbox', 'radio' ), true );

    // Checkboxes/radios render without the form-group wrapper to avoid block label styles.
    if ( ! $is_checkbox ) :
        $width_class = 'half' === $field->width ? 'form-group form-group-half' : 'form-group';
        if ( $is_sidebar ) {
            $width_class = 'checkout-custom-field-inline';
        }
        ?>
        <div class="<?php echo esc_attr( $width_class ); ?>">
            <label for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $field->label ); ?><?php echo $req_mark; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></label>
    <?php endif; ?>

        <?php
        switch ( $field->field_type ) {
            case 'textarea':
                ?>
                <textarea id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_name ); ?>" rows="4" placeholder="<?php echo esc_attr( $field->placeholder ); ?>"<?php echo $required; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>><?php echo esc_textarea( $value ); ?></textarea>
                <?php
                break;

            case 'select':
                $options = json_decode( $field->options, true );
                ?>
                <select id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_name ); ?>"<?php echo $required; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                    <?php if ( $field->placeholder ) : ?>
                        <option value=""><?php echo esc_html( $field->placeholder ); ?></option>
                    <?php else : ?>
                        <option value=""><?php esc_html_e( 'Select...', 'ggm-commerce' ); ?></option>
                    <?php endif; ?>
                    <?php if ( is_array( $options ) ) : ?>
                        <?php foreach ( $options as $option ) : ?>
                            <option value="<?php echo esc_attr( $option ); ?>" <?php selected( $value, $option ); ?>><?php echo esc_html( $option ); ?></option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <?php
                break;

            case 'radio':
                $options = json_decode( $field->options, true );
                if ( is_array( $options ) ) :
                    foreach ( $options as $option ) :
                        ?>
                        <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px; cursor: pointer;">
                            <input type="radio" name="<?php echo esc_attr( $field_name ); ?>" value="<?php echo esc_attr( $option ); ?>" <?php checked( $value, $option ); ?><?php echo $required; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                            <?php echo esc_html( $option ); ?>
                        </label>
                        <?php
                    endforeach;
                endif;
                break;

            case 'checkbox':
                $options = json_decode( $field->options, true );
                if ( is_array( $options ) && count( $options ) > 1 ) :
                    // Multiple checkboxes.
                    foreach ( $options as $option ) :
                        ?>
                        <label style="display: flex; align-items: center; gap: 8px; margin-bottom: 5px; cursor: pointer;">
                            <input type="checkbox" name="<?php echo esc_attr( $field_name ); ?>[]" value="<?php echo esc_attr( $option ); ?>">
                            <?php echo esc_html( $option ); ?>
                        </label>
                        <?php
                    endforeach;
                else :
                    // Single checkbox.
                    ?>
                    <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                        <input type="checkbox" name="<?php echo esc_attr( $field_name ); ?>" value="1"<?php echo $required; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                        <?php echo esc_html( $field->label ); ?><?php echo $req_mark; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
                    </label>
                    <?php
                endif;
                break;

            default:
                // text, email, tel, number, date, url.
                $input_type = in_array( $field->field_type, array( 'text', 'email', 'tel', 'number', 'date', 'url' ), true ) ? $field->field_type : 'text';
                ?>
                <input type="<?php echo esc_attr( $input_type ); ?>" id="<?php echo esc_attr( $field_id ); ?>" name="<?php echo esc_attr( $field_name ); ?>" value="<?php echo esc_attr( $value ); ?>" placeholder="<?php echo esc_attr( $field->placeholder ); ?>"<?php echo $required; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
                <?php
                break;
        }

        if ( ! empty( $field->help_text ) ) :
            ?>
            <p class="field-help-text"><?php echo esc_html( $field->help_text ); ?></p>
        <?php endif; ?>

    <?php if ( ! $is_checkbox ) : ?>
    </div>
    <?php endif; ?>
    <?php
}

/**
 * Main render function for the Checkout widget.
 *
 * @param \GGM_Commerce_Base_Widget $widget Widget instance.
 */
function ggmc_checkout_render( $widget ) {
    $settings = $widget->get_settings_for_display();
    $cart = GGM_Commerce_Cart::get_instance();

    // Check if we're in editor mode and should show preview data
    $is_editor = ggmc_checkout_is_editor_mode();
    $show_preview = $is_editor && ($settings['show_editor_preview'] ?? 'yes') === 'yes';

    if ($show_preview) {
        // Use preview data for editor styling
        $preview_item_count = intval($settings['preview_item_count'] ?? 2);
        $cart_items = ggmc_checkout_get_preview_cart_items($preview_item_count);
        $full_totals = ggmc_checkout_get_preview_totals($cart_items, $settings);

        $cart_total = $full_totals['subtotal'];
        $cart_count = array_sum(array_column($cart_items, 'quantity'));
        $cart_totals = [
            'subtotal' => $full_totals['subtotal'],
            'tax_amount' => $full_totals['tax_amount'],
            'tax_label' => $full_totals['tax_label'],
            'prices_include_tax' => $full_totals['prices_include_tax'],
            'total' => $full_totals['total'],
        ];
    } else {
        // Use real cart data
        $cart_items = $cart->get_cart_items();

        if (empty($cart_items)) {
            echo '<div class="ggmc-checkout-empty">
                    <h3>' . esc_html__('Your cart is empty', 'ggm-commerce') . '</h3>
                    <p>' . esc_html__('Please add some items to your cart before checkout.', 'ggm-commerce') . '</p>
                  </div>';
            return;
        }

        $cart_total = $cart->get_cart_total();
        $cart_count = $cart->get_cart_count();
        $cart_totals = $cart->get_cart_totals_with_tax();
        $full_totals = $cart->get_cart_totals_with_shipping();
    }

    $required_fields = $settings['required_fields'] ?? [];

    // B2B Tax exemption settings
    $tax = ggm_commerce_tax();
    $b2b_enabled = $show_preview ? false : $tax->is_b2b_enabled();
    $session_tax_exempt = $show_preview ? false : $tax->get_session_tax_exempt();
    $session_tax_id = $show_preview ? '' : $tax->get_session_tax_id();

    // Extract totals
    $tax_enabled = !empty($cart_totals['tax_label']);
    $tax_amount = $cart_totals['tax_amount'];
    $prices_include_tax = $cart_totals['prices_include_tax'];

    // Shipping from the full calculation
    $shipping = $full_totals['shipping_amount'];
    $shipping_label = $full_totals['shipping_label'] ?: __('Shipping', 'ggm-commerce');
    $shipping_method_name = $full_totals['shipping_method_name'];
    $shipping_methods = $full_totals['shipping_methods'];
    $allows_shipping_choice = $full_totals['allows_shipping_choice'];
    $grand_total = $full_totals['total'];

    // Discount from the full calculation
    $discount_amount = $full_totals['discount_amount'] ?? 0;
    $discount_code = $full_totals['discount_code'] ?? '';
    $discount_type = $full_totals['discount_type'] ?? '';
    $discount_message = $full_totals['discount_message'] ?? '';
    $has_discount = !empty($discount_code) && $discount_amount > 0;

    // Discount input display settings - always show in preview mode for styling
    $discounts_activated = $show_preview || (class_exists('GGM_Commerce_Discounts') && GGM_Commerce_Discounts::is_activated());
    $show_discount_input = $discounts_activated && ($settings['show_discount_input'] ?? 'yes') === 'yes';
    $discount_collapsible = ($settings['discount_collapsible'] ?? 'yes') === 'yes';

    // Check if logged-in user already has approved tax exemption in their account
    // If so, we don't need to show the B2B checkout section - they're already exempt
    $user_has_account_exemption = false;
    if ($b2b_enabled && is_user_logged_in()) {
        $user_has_account_exemption = $tax->is_customer_tax_exempt();
    }
    // Only show B2B checkout section if B2B is enabled AND user doesn't have account-level exemption
    $show_b2b_checkout_section = $b2b_enabled && !$user_has_account_exemption;

    // Auto-populate user data if logged in
    $user_data = [
        'first_name' => '',
        'last_name' => '',
        'email' => '',
        'phone' => ''
    ];
    $billing_address = null;
    $shipping_address = null;
    $billing_addresses = [];
    $shipping_addresses = [];
    $show_billing_dropdown = false;
    $show_shipping_dropdown = false;

    if (is_user_logged_in()) {
        global $ggm_commerce_address_manager, $wpdb;
        $user_id = get_current_user_id();
        $user = wp_get_current_user();

        // Get user basic info from WordPress user meta
        $user_data['first_name'] = get_user_meta($user_id, 'first_name', true) ?: '';
        $user_data['last_name'] = get_user_meta($user_id, 'last_name', true) ?: '';
        $user_data['email'] = $user->user_email ?: '';
        $user_data['phone'] = get_user_meta($user_id, 'phone', true) ?: '';

        // Fallback to ggmc_customers table if WordPress meta is empty
        if (empty($user_data['first_name']) || empty($user_data['last_name'])) {
            $customer = $wpdb->get_row($wpdb->prepare(
                "SELECT first_name, last_name, phone FROM {$wpdb->prefix}ggmc_customers
                 WHERE user_id = %d OR email = %s LIMIT 1",
                $user_id,
                $user->user_email
            ));

            if ($customer) {
                if (empty($user_data['first_name']) && !empty($customer->first_name)) {
                    $user_data['first_name'] = $customer->first_name;
                }
                if (empty($user_data['last_name']) && !empty($customer->last_name)) {
                    $user_data['last_name'] = $customer->last_name;
                }
                if (empty($user_data['phone']) && !empty($customer->phone)) {
                    $user_data['phone'] = $customer->phone;
                }
            }
        }

        // Get addresses
        if ($ggm_commerce_address_manager) {
            // Get default addresses
            $billing_address = $ggm_commerce_address_manager->get_default_address($user_id, 'billing');
            $shipping_address = $ggm_commerce_address_manager->get_default_address($user_id, 'shipping');

            // Check if multiple addresses are enabled and get all addresses
            if ($ggm_commerce_address_manager->are_multiple_billing_addresses_enabled()) {
                $billing_addresses = $ggm_commerce_address_manager->get_user_addresses($user_id, 'billing');
                $show_billing_dropdown = count($billing_addresses) > 1;
            }

            if ($ggm_commerce_address_manager->are_multiple_shipping_addresses_enabled()) {
                $shipping_addresses = $ggm_commerce_address_manager->get_user_addresses($user_id, 'shipping');
                $show_shipping_dropdown = count($shipping_addresses) > 1;
            }
        }
    }
    ?>

    <div class="ggmc-checkout-container">
        <?php if ($show_preview) : ?>
        <div class="ggmc-editor-preview-notice" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; padding: 12px 16px; margin-bottom: 20px; border-radius: 8px; display: flex; align-items: center; gap: 10px; font-size: 13px;">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="10"></circle>
                <line x1="12" y1="16" x2="12" y2="12"></line>
                <line x1="12" y1="8" x2="12.01" y2="8"></line>
            </svg>
            <span><strong><?php esc_html_e('Editor Preview Mode', 'ggm-commerce'); ?></strong> — <?php esc_html_e('Showing sample data for styling. This will not appear on the live site.', 'ggm-commerce'); ?></span>
        </div>
        <?php endif; ?>
        <form class="ggmc-checkout-form" id="ggmc-checkout-form" data-cart-total="<?php echo esc_attr($grand_total); ?>"<?php echo $show_preview ? ' data-preview="true"' : ''; ?> novalidate>
            <?php wp_nonce_field('ggm_commerce_checkout', 'checkout_nonce'); ?>

            <div class="checkout-layout">
                <!-- Customer Information Section -->
                <div class="checkout-main">
                    <div class="checkout-section">
                        <h3><?php esc_html_e('Customer Information', 'ggm-commerce'); ?></h3>

                        <div class="form-row">
                            <div class="form-group half">
                                <label for="first_name"><?php esc_html_e('First Name', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="first_name" name="customer[first_name]" value="<?php echo esc_attr($user_data['first_name']); ?>" required>
                            </div>
                            <div class="form-group half">
                                <label for="last_name"><?php esc_html_e('Last Name', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="last_name" name="customer[last_name]" value="<?php echo esc_attr($user_data['last_name']); ?>" required>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="email"><?php esc_html_e('Email Address', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="email" id="email" name="customer[email]" value="<?php echo esc_attr($user_data['email']); ?>" required>
                            </div>
                        </div>

                        <?php if (in_array('phone', $required_fields)) : ?>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="phone"><?php esc_html_e('Phone Number', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="tel" id="phone" name="customer[phone]" value="<?php echo esc_attr($user_data['phone']); ?>" required>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <?php if ($show_b2b_checkout_section && is_user_logged_in()) : ?>
                    <!-- B2B Registration Notice (for logged-in users without approved exemption) -->
                    <div class="checkout-section b2b-notice-section">
                        <div class="b2b-register-notice" style="display: flex; align-items: flex-start; gap: 12px; background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px; padding: 16px;">
                            <span class="dashicons dashicons-building" style="color: #0284c7; font-size: 24px; width: 24px; height: 24px; margin-top: 2px;"></span>
                            <div class="notice-content">
                                <strong style="display: block; margin-bottom: 4px;"><?php esc_html_e('Business Customer?', 'ggm-commerce'); ?></strong>
                                <p style="margin: 0; color: #475569; font-size: 14px;"><?php
                                    $account_page_id = get_option('ggm_commerce_pages_options')['account_page'] ?? 0;
                                    $account_url = $account_page_id ? get_permalink($account_page_id) : '#';
                                    printf(
                                        /* translators: %1$s: tax label (e.g., VAT), %2$s: link to account page */
                                        esc_html__('Register your %1$s number in %2$s to apply for tax exemption on future orders.', 'ggm-commerce'),
                                        esc_html($tax->get_label()),
                                        '<a href="' . esc_url($account_url) . '" style="color: #0284c7; text-decoration: underline;">' . esc_html__('your account', 'ggm-commerce') . '</a>'
                                    );
                                ?></p>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php ggmc_checkout_render_checkout_custom_fields( $widget, 'after_customer_info' ); ?>

                    <!-- Billing Information Section -->
                    <div class="checkout-section">
                        <h3><?php esc_html_e('Billing Address', 'ggm-commerce'); ?></h3>

                        <?php if ($show_billing_dropdown) : ?>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="billing_address_select"><?php esc_html_e('Select Saved Address', 'ggm-commerce'); ?></label>
                                <select id="billing_address_select" class="address-selector" data-address-type="billing">
                                    <?php foreach ($billing_addresses as $address) :
                                        $label = $ggm_commerce_address_manager->get_address_label($address);
                                        $is_default = $address->is_default ? ' (Default)' : '';
                                    ?>
                                        <option value="<?php echo esc_attr($address->id); ?>"
                                                <?php selected($address->is_default, 1); ?>
                                                data-address='<?php echo esc_attr(wp_json_encode($address)); ?>'>
                                            <?php echo esc_html($label . $is_default); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (in_array('company', $required_fields)) : ?>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="billing_company"><?php esc_html_e('Company', 'ggm-commerce'); ?></label>
                                <input type="text" id="billing_company" name="customer[billing_company]" value="<?php echo esc_attr($billing_address->company ?? ''); ?>">
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="billing_address_1"><?php esc_html_e('Address', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="billing_address_1" name="customer[billing_address_1]" value="<?php echo esc_attr($billing_address->address_1 ?? ''); ?>" required>
                            </div>
                        </div>

                        <?php if (in_array('address_2', $required_fields)) : ?>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="billing_address_2"><?php esc_html_e('Address Line 2', 'ggm-commerce'); ?></label>
                                <input type="text" id="billing_address_2" name="customer[billing_address_2]" value="<?php echo esc_attr($billing_address->address_2 ?? ''); ?>">
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="form-row">
                            <div class="form-group half">
                                <label for="billing_city"><?php esc_html_e('City', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="billing_city" name="customer[billing_city]" value="<?php echo esc_attr($billing_address->city ?? ''); ?>" required>
                            </div>
                            <div class="form-group quarter">
                                <label for="billing_state"><?php esc_html_e('State', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="billing_state" name="customer[billing_state]" value="<?php echo esc_attr($billing_address->state ?? ''); ?>" required>
                            </div>
                            <div class="form-group quarter">
                                <label for="billing_postcode"><?php esc_html_e('ZIP Code', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <input type="text" id="billing_postcode" name="customer[billing_postcode]" value="<?php echo esc_attr($billing_address->postcode ?? ''); ?>" required>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="billing_country"><?php esc_html_e('Country', 'ggm-commerce'); ?> <span class="required">*</span></label>
                                <select id="billing_country" name="customer[billing_country]" required>
                                    <option value=""><?php esc_html_e('Select a country', 'ggm-commerce'); ?></option>
                                    <option value="US" <?php selected($billing_address->country ?? '', 'US'); ?>><?php esc_html_e('United States', 'ggm-commerce'); ?></option>
                                    <option value="CA" <?php selected($billing_address->country ?? '', 'CA'); ?>><?php esc_html_e('Canada', 'ggm-commerce'); ?></option>
                                    <option value="GB" <?php selected($billing_address->country ?? '', 'GB'); ?>><?php esc_html_e('United Kingdom', 'ggm-commerce'); ?></option>
                                    <option value="AU" <?php selected($billing_address->country ?? '', 'AU'); ?>><?php esc_html_e('Australia', 'ggm-commerce'); ?></option>
                                    <option value="DE" <?php selected($billing_address->country ?? '', 'DE'); ?>><?php esc_html_e('Germany', 'ggm-commerce'); ?></option>
                                    <option value="FR" <?php selected($billing_address->country ?? '', 'FR'); ?>><?php esc_html_e('France', 'ggm-commerce'); ?></option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <?php ggmc_checkout_render_checkout_custom_fields( $widget, 'after_billing' ); ?>

                    <?php if ($settings['show_shipping_fields'] === 'yes') : ?>
                    <!-- Shipping Information Section -->
                    <div class="checkout-section">
                        <h3>
                            <label class="ship-different">
                                <input type="checkbox" id="ship_to_different_address" name="ship_to_different_address" value="1">
                                <?php esc_html_e('Ship to a different address?', 'ggm-commerce'); ?>
                            </label>
                        </h3>

                        <div id="shipping_fields" style="display: none;">
                            <?php if ($show_shipping_dropdown) : ?>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="shipping_address_select"><?php esc_html_e('Select Saved Address', 'ggm-commerce'); ?></label>
                                    <select id="shipping_address_select" class="address-selector" data-address-type="shipping">
                                        <?php foreach ($shipping_addresses as $address) :
                                            $label = $ggm_commerce_address_manager->get_address_label($address);
                                            $is_default = $address->is_default ? ' (Default)' : '';
                                        ?>
                                            <option value="<?php echo esc_attr($address->id); ?>"
                                                    <?php selected($address->is_default, 1); ?>
                                                    data-address='<?php echo esc_attr(wp_json_encode($address)); ?>'>
                                                <?php echo esc_html($label . $is_default); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <?php endif; ?>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="shipping_address_1"><?php esc_html_e('Shipping Address', 'ggm-commerce'); ?></label>
                                    <input type="text" id="shipping_address_1" name="customer[shipping_address_1]" value="<?php echo esc_attr($shipping_address->address_1 ?? ''); ?>">
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group half">
                                    <label for="shipping_city"><?php esc_html_e('City', 'ggm-commerce'); ?></label>
                                    <input type="text" id="shipping_city" name="customer[shipping_city]" value="<?php echo esc_attr($shipping_address->city ?? ''); ?>">
                                </div>
                                <div class="form-group quarter">
                                    <label for="shipping_state"><?php esc_html_e('State', 'ggm-commerce'); ?></label>
                                    <input type="text" id="shipping_state" name="customer[shipping_state]" value="<?php echo esc_attr($shipping_address->state ?? ''); ?>">
                                </div>
                                <div class="form-group quarter">
                                    <label for="shipping_postcode"><?php esc_html_e('ZIP Code', 'ggm-commerce'); ?></label>
                                    <input type="text" id="shipping_postcode" name="customer[shipping_postcode]" value="<?php echo esc_attr($shipping_address->postcode ?? ''); ?>">
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="shipping_country"><?php esc_html_e('Country', 'ggm-commerce'); ?></label>
                                    <select id="shipping_country" name="customer[shipping_country]">
                                        <option value=""><?php esc_html_e('Select a country', 'ggm-commerce'); ?></option>
                                        <option value="US" <?php selected($shipping_address->country ?? '', 'US'); ?>><?php esc_html_e('United States', 'ggm-commerce'); ?></option>
                                        <option value="CA" <?php selected($shipping_address->country ?? '', 'CA'); ?>><?php esc_html_e('Canada', 'ggm-commerce'); ?></option>
                                        <option value="GB" <?php selected($shipping_address->country ?? '', 'GB'); ?>><?php esc_html_e('United Kingdom', 'ggm-commerce'); ?></option>
                                        <option value="AU" <?php selected($shipping_address->country ?? '', 'AU'); ?>><?php esc_html_e('Australia', 'ggm-commerce'); ?></option>
                                        <option value="DE" <?php selected($shipping_address->country ?? '', 'DE'); ?>><?php esc_html_e('Germany', 'ggm-commerce'); ?></option>
                                        <option value="FR" <?php selected($shipping_address->country ?? '', 'FR'); ?>><?php esc_html_e('France', 'ggm-commerce'); ?></option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php ggmc_checkout_render_checkout_custom_fields( $widget, 'after_shipping' ); ?>

                    <?php if ($settings['enable_order_notes'] === 'yes') : ?>
                    <!-- Order Notes Section -->
                    <div class="checkout-section">
                        <h3><?php esc_html_e('Order Notes', 'ggm-commerce'); ?></h3>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="order_notes"><?php esc_html_e('Notes about your order (optional)', 'ggm-commerce'); ?></label>
                                <textarea id="order_notes" name="order_notes" rows="4" placeholder="Special delivery instructions, etc."></textarea>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php ggmc_checkout_render_checkout_custom_fields( $widget, 'after_order_notes' ); ?>
                </div>

                <!-- Order Summary Sidebar -->
                <div class="checkout-sidebar">
                    <?php
                    $sticky_class = ($settings['order_summary_sticky'] ?? 'yes') === 'yes' ? 'is-sticky' : '';
                    $show_images = ($settings['show_product_images'] ?? 'yes') === 'yes';
                    $link_product = ($settings['link_product_name'] ?? 'yes') === 'yes';
                    $admin_bar_offset = ($settings['order_summary_admin_bar_offset'] ?? 'yes') === 'yes' ? 'true' : 'false';
                    $base_offset = isset($settings['order_summary_sticky_offset']['size']) ? intval($settings['order_summary_sticky_offset']['size']) : 20;
                    ?>
                    <div class="order-summary <?php echo esc_attr($sticky_class); ?>" data-admin-bar-offset="<?php echo esc_attr($admin_bar_offset); ?>" data-base-offset="<?php echo esc_attr($base_offset); ?>">
                        <h3><?php esc_html_e('Order Summary', 'ggm-commerce'); ?></h3>

                        <div class="order-items">
                            <?php foreach ($cart_items as $item_key => $item) :
                                // Check if this is preview data (has product_name key)
                                $is_preview_item = isset($item['product_name']);

                                if ($is_preview_item) {
                                    // Preview mode: use pre-populated data
                                    $product_name = $item['product_name'];
                                    $item_price = $item['price'];
                                    $item_total = $item['line_total'];
                                    $product_image = $item['image_url'] ?? '';
                                    $variation_display = '';
                                    $product_url = '';
                                } else {
                                    // Real cart: fetch from database
                                    global $wpdb;
                                    $product = $wpdb->get_row($wpdb->prepare(
                                        "SELECT * FROM {$wpdb->prefix}ggmc_products WHERE id = %d AND status = 'active'",
                                        $item['product_id']
                                    ));

                                    if (!$product) continue;

                                    $product_name = $product->name;

                                    // Get variation data if present
                                    $item_price = $product->price;
                                    $variation_display = '';
                                    $variation_image = '';

                                    // Check for Independent mode first (no variation_id, uses variation_data)
                                    $variation_data = isset($item['variation_data']) ? $item['variation_data'] : [];
                                    $is_independent = isset($variation_data['variation_mode']) && 'independent' === $variation_data['variation_mode'];

                                    if ($is_independent && class_exists('GGM_Commerce_Variations')) {
                                        // Independent mode: use calculated price and format options
                                        $variations_manager = GGM_Commerce_Variations::instance();

                                        // Use pre-calculated price from cart
                                        if (isset($variation_data['calculated_price'])) {
                                            $item_price = floatval($variation_data['calculated_price']);
                                        }

                                        // Format selected options for display
                                        if (!empty($variation_data['attributes'])) {
                                            $variation_display = $variations_manager->format_selected_options(
                                                $product->id,
                                                $variation_data['attributes']
                                            );

                                            // Fallback: if format_selected_options returns empty, build simple display
                                            if (empty($variation_display)) {
                                                $attr_parts = [];
                                                foreach ($variation_data['attributes'] as $attr_id => $value) {
                                                    $attr_parts[] = $value;
                                                }
                                                $variation_display = implode(', ', $attr_parts);
                                            }
                                        }
                                    } elseif (!empty($item['variation_id']) && class_exists('GGM_Commerce_Variations')) {
                                        // Combined mode: use variation-specific data
                                        $variations_manager = GGM_Commerce_Variations::instance();
                                        $variation = $variations_manager->get_variation($item['variation_id']);

                                        if ($variation) {
                                            // Use variation price if set
                                            $variation_price = $variations_manager->get_variation_price($item['variation_id']);
                                            if ($variation_price !== null) {
                                                $item_price = $variation_price;
                                            }

                                            // Get variation image if available
                                            if (!empty($variation['image_id'])) {
                                                $variation_image = wp_get_attachment_image_url($variation['image_id'], 'thumbnail');
                                            }

                                            // Build variation attributes display
                                            if (!empty($variation['attributes'])) {
                                                $attr_parts = [];
                                                foreach ($variation['attributes'] as $attr) {
                                                    $attr_parts[] = $attr['attribute_name'] . ': ' . $attr['attribute_value'];
                                                }
                                                $variation_display = implode(', ', $attr_parts);
                                            }
                                        }
                                    }

                                    $item_total = $item_price * $item['quantity'];
                                    $product_url = $link_product ? GGM_Commerce_Helpers::get_product_details_url($product->id) : '';

                                    // Use variation image if available, otherwise product image
                                    $product_image = $variation_image;
                                    if (!$product_image && $show_images && !empty($product->image_id)) {
                                        $product_image = wp_get_attachment_image_url($product->image_id, 'thumbnail');
                                    }
                                }
                            ?>
                            <div class="order-item">
                                <?php if ($show_images) : ?>
                                <div class="item-image">
                                    <?php if ($is_preview_item && !empty($item['preview_color'])) : ?>
                                        <div class="preview-placeholder-image" style="background-color: <?php echo esc_attr($item['preview_color']); ?>; width: 60px; height: 60px; border-radius: 6px; display: flex; align-items: center; justify-content: center;">
                                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="<?php echo esc_attr($item['preview_text_color']); ?>" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                                <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                                                <circle cx="8.5" cy="8.5" r="1.5"></circle>
                                                <polyline points="21 15 16 10 5 21"></polyline>
                                            </svg>
                                        </div>
                                    <?php elseif ($product_image) : ?>
                                        <img src="<?php echo esc_url($product_image); ?>" alt="<?php echo esc_attr($product_name); ?>">
                                    <?php else : ?>
                                        <div class="placeholder-image"><?php esc_html_e('No Image', 'ggm-commerce'); ?></div>
                                    <?php endif; ?>
                                </div>
                                <?php endif; ?>
                                <div class="item-details">
                                    <?php if (!$is_preview_item && $link_product && $product_url) : ?>
                                        <a href="<?php echo esc_url($product_url); ?>" class="item-name item-name-link"><?php echo esc_html($product_name ?? 'Unknown Product'); ?></a>
                                    <?php else : ?>
                                        <span class="item-name"><?php echo esc_html($product_name ?? 'Unknown Product'); ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($variation_display)) : ?>
                                        <span class="item-variation"><?php echo esc_html($variation_display); ?></span>
                                    <?php endif; ?>
                                    <span class="item-quantity">× <?php echo absint($item['quantity']); ?></span>
                                </div>
                                <div class="item-price">$<?php echo esc_html(number_format($item_total, 2)); ?></div>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <?php if ($show_discount_input) : ?>
                        <!-- Discount Code Section -->
                        <div class="ggmc-discount-section" data-nonce="<?php echo esc_attr(wp_create_nonce('ggmc_discount_nonce')); ?>">
                            <?php if ($has_discount) : ?>
                                <!-- Applied Discount Display -->
                                <div class="discount-applied">
                                    <span class="discount-code-badge"><?php echo esc_html($discount_code); ?></span>
                                    <span class="discount-savings">-$<?php echo esc_html(number_format($discount_amount, 2)); ?></span>
                                    <button type="button" class="discount-remove-btn" title="<?php esc_attr_e('Remove discount', 'ggm-commerce'); ?>">&times;</button>
                                </div>
                            <?php else : ?>
                                <!-- Discount Input Form -->
                                <?php if ($discount_collapsible) : ?>
                                <div class="discount-toggle-label">
                                    <span class="discount-label"><?php echo esc_html($settings['discount_label'] ?? __('Have a discount code?', 'ggm-commerce')); ?></span>
                                    <span class="discount-toggle-icon">+</span>
                                </div>
                                <div class="discount-form-container" style="display: none;">
                                <?php else : ?>
                                <div class="discount-label-static"><?php echo esc_html($settings['discount_label'] ?? __('Have a discount code?', 'ggm-commerce')); ?></div>
                                <div class="discount-form-container">
                                <?php endif; ?>
                                    <div class="discount-form">
                                        <input type="text" class="discount-input" placeholder="<?php echo esc_attr($settings['discount_placeholder'] ?? __('Enter code', 'ggm-commerce')); ?>" />
                                        <button type="button" class="discount-apply-btn"><?php echo esc_html($settings['discount_button_text'] ?? __('Apply', 'ggm-commerce')); ?></button>
                                    </div>
                                    <div class="discount-message" style="display: none;"></div>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

                        <div class="order-totals">
                            <?php
                            // Tax variables were calculated earlier for data-cart-total attribute
                            $tax_label = $cart_totals['tax_label'] ?: __('Tax', 'ggm-commerce');

                            // Determine what to show as subtotal
                            if ($prices_include_tax && $tax_enabled) {
                                // Prices include tax - show net as subtotal
                                $display_subtotal = $cart_totals['subtotal_net'];
                                $subtotal_label = __('Subtotal (excl. tax):', 'ggm-commerce');
                            } else {
                                $display_subtotal = $cart_total;
                                $subtotal_label = __('Subtotal:', 'ggm-commerce');
                            }
                            ?>
                            <div class="total-row">
                                <span><?php echo esc_html($subtotal_label); ?></span>
                                <span>$<?php echo esc_html(number_format($display_subtotal, 2)); ?></span>
                            </div>
                            <?php if ($tax_enabled && $tax_amount > 0) : ?>
                            <div class="total-row tax-row">
                                <span><?php echo esc_html($tax_label); ?>:</span>
                                <span>$<?php echo esc_html(number_format($tax_amount, 2)); ?></span>
                            </div>
                            <?php endif; ?>

                            <?php if ($allows_shipping_choice && !empty($shipping_methods)) : ?>
                            <!-- Shipping Method Selection -->
                            <div class="shipping-methods-section">
                                <div class="total-row shipping-row-header">
                                    <span><?php echo esc_html($shipping_label); ?>:</span>
                                </div>
                                <div class="shipping-methods-list">
                                    <?php foreach ($shipping_methods as $method) : ?>
                                    <label class="shipping-method-option <?php echo $method['selected'] ? 'selected' : ''; ?>">
                                        <input type="radio" name="shipping_method" value="<?php echo esc_attr($method['id']); ?>" <?php checked($method['selected']); ?> data-cost="<?php echo esc_attr($method['cost']); ?>">
                                        <span class="method-name"><?php echo esc_html($method['name']); ?></span>
                                        <span class="method-cost"><?php echo esc_html($method['formatted_cost']); ?></span>
                                    </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php else : ?>
                            <div class="total-row shipping-row">
                                <span>
                                    <?php
                                    if (!empty($shipping_method_name)) {
                                        echo esc_html($shipping_method_name) . ':';
                                    } else {
                                        echo esc_html($shipping_label) . ':';
                                    }
                                    ?>
                                </span>
                                <span class="shipping-cost">
                                    <?php
                                    if ($shipping > 0) {
                                        echo '$' . esc_html(number_format($shipping, 2));
                                    } else {
                                        esc_html_e('Free', 'ggm-commerce');
                                    }
                                    ?>
                                </span>
                            </div>
                            <?php endif; ?>
                            <?php if ($has_discount) : ?>
                            <div class="total-row discount-row">
                                <span><?php esc_html_e('Discount:', 'ggm-commerce'); ?> <small>(<?php echo esc_html($discount_code); ?>)</small></span>
                                <span class="discount-amount">-$<?php echo esc_html(number_format($discount_amount, 2)); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="total-row total-final">
                                <span><?php esc_html_e('Total:', 'ggm-commerce'); ?></span>
                                <span>$<?php echo esc_html(number_format($grand_total, 2)); ?></span>
                            </div>
                        </div>

                        <?php ggmc_checkout_render_checkout_custom_fields( $widget, 'after_order_summary_totals' ); ?>

                        <?php
                        // Payment Methods Section
                        $gateway_manager = ggm_commerce_gateways();
                        $available_gateways = $gateway_manager->get_available_gateways();

                        if (!empty($available_gateways) && $grand_total > 0) :
                        ?>
                        <div class="payment-methods-section">
                            <h4><?php esc_html_e('Payment Method', 'ggm-commerce'); ?></h4>
                            <div class="ggmc-payment-methods">
                                <?php
                                $first = true;
                                foreach ($available_gateways as $gateway) :
                                ?>
                                <div class="ggmc-payment-method" data-gateway="<?php echo esc_attr($gateway->get_id()); ?>">
                                    <label class="ggmc-payment-method-label">
                                        <input type="radio"
                                               name="payment_method"
                                               value="<?php echo esc_attr($gateway->get_id()); ?>"
                                               <?php checked($first); ?>>
                                        <span class="ggmc-payment-method-info">
                                            <img src="<?php echo esc_url($gateway->get_icon()); ?>"
                                                 alt="<?php echo esc_attr($gateway->get_title()); ?>"
                                                 class="ggmc-payment-method-icon">
                                            <span class="ggmc-payment-method-title">
                                                <?php echo esc_html($gateway->get_title()); ?>
                                            </span>
                                        </span>
                                    </label>
                                    <div class="ggmc-payment-method-fields" style="<?php echo $first ? '' : 'display: none;'; ?>">
                                        <?php $gateway->render_payment_fields(); ?>
                                    </div>
                                </div>
                                <?php
                                $first = false;
                                endforeach;
                                ?>
                            </div>
                            <div id="ggmc-payment-message"></div>
                        </div>
                        <?php endif; ?>

                        <div class="checkout-actions">
                            <button type="submit" class="checkout-button">
                                <?php esc_html_e('Place Order', 'ggm-commerce'); ?>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <?php // Payment & shipping styles moved to widgets.css (structural) and professional-defaults.css (design) ?>

    <script>
    // Inject cart items into payment gateway configs (localized script may run before cart session loads)
    (function() {
        var cartItems = <?php echo wp_json_encode( array_values( array_map( function( $key, $item ) {
            return array(
                'cart_key'   => $key,
                'product_id' => $item['product_id'],
                'quantity'   => $item['quantity'],
            );
        }, array_keys( $cart_items ), $cart_items ) ) ); ?>;

        if (typeof ggmcPayPal !== 'undefined') {
            ggmcPayPal.cartItems = cartItems;
        }
        if (typeof ggmcStripe !== 'undefined') {
            ggmcStripe.cartItems = cartItems;
        }
    })();

    jQuery(document).ready(function($) {
        // Function to update checkout button visibility based on payment method
        function updateCheckoutButton(selectedMethod) {
            var $submitBtn = $('.checkout-button');
            // Hide submit button only for PayPal - it provides its own button
            // Stripe uses the standard form submit button
            if (selectedMethod === 'paypal') {
                $submitBtn.hide();
            } else {
                $submitBtn.show();
            }
        }

        // Payment method switching
        $('input[name="payment_method"]').on('change', function() {
            var selectedMethod = $(this).val();
            $('.ggmc-payment-method-fields').hide();
            $(this).closest('.ggmc-payment-method').find('.ggmc-payment-method-fields').show();
            updateCheckoutButton(selectedMethod);
        });

        // Initialize button state on page load
        var initialMethod = $('input[name="payment_method"]:checked').val();
        if (initialMethod) {
            updateCheckoutButton(initialMethod);
        }

        // Admin bar offset for sticky order summary
        function adjustStickyForAdminBar() {
            var $orderSummary = $('.order-summary.is-sticky');
            if ($orderSummary.length === 0) return;

            var shouldAccountForAdminBar = $orderSummary.data('admin-bar-offset') === true || $orderSummary.data('admin-bar-offset') === 'true';
            var baseOffset = parseInt($orderSummary.data('base-offset')) || 20;

            if (shouldAccountForAdminBar) {
                var adminBar = document.getElementById('wpadminbar');
                if (adminBar || document.body.classList.contains('admin-bar')) {
                    // Admin bar height: 32px on desktop, 46px on mobile (<=782px)
                    var adminBarHeight = window.innerWidth <= 782 ? 46 : 32;
                    var totalOffset = baseOffset + adminBarHeight;
                    $orderSummary.css('top', totalOffset + 'px');
                } else {
                    $orderSummary.css('top', baseOffset + 'px');
                }
            }
        }

        // Run on load and resize
        adjustStickyForAdminBar();
        $(window).on('resize', adjustStickyForAdminBar);

        // Toggle shipping fields
        $('#ship_to_different_address').on('change', function() {
            $('#shipping_fields').toggle(this.checked);
        });

        // Handle address selector change
        $('.address-selector').on('change', function() {
            const selectedOption = $(this).find('option:selected');
            const addressData = selectedOption.data('address');
            const addressType = $(this).data('address-type');

            if (addressData) {
                // Populate form fields based on address type
                const prefix = addressType === 'billing' ? 'billing_' : 'shipping_';

                if (addressData.company) {
                    $('#' + prefix + 'company').val(addressData.company);
                }
                $('#' + prefix + 'address_1').val(addressData.address_1 || '');
                $('#' + prefix + 'address_2').val(addressData.address_2 || '');
                $('#' + prefix + 'city').val(addressData.city || '');
                $('#' + prefix + 'state').val(addressData.state || '');
                $('#' + prefix + 'postcode').val(addressData.postcode || '');

                // Set country dropdown
                if (addressData.country) {
                    $('#' + prefix + 'country').val(addressData.country);
                }
            }
        });

        // B2B Tax exemption is now handled via user account registration
        // Session-based checkout exemption has been removed for security reasons

        // Shipping method selection handler
        $('input[name="shipping_method"]').on('change', function() {
            var $selected = $(this);
            var methodId = $selected.val();
            var methodCost = parseFloat($selected.data('cost')) || 0;

            // Update visual selection
            $('.shipping-method-option').removeClass('selected');
            $selected.closest('.shipping-method-option').addClass('selected');

            // Call AJAX to update session and get new totals
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: {
                    action: 'ggm_commerce_select_shipping_method',
                    nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_nonce')); ?>',
                    method_id: methodId
                },
                success: function(response) {
                    if (response.success) {
                        // Update grand total display
                        $('.order-totals .total-final span:last').text(response.data.total_formatted);
                        // Update form data attribute
                        $('#ggmc-checkout-form').data('cart-total', response.data.total);
                    }
                }
            });
        });

        // Recalculate shipping when address changes
        var shippingDebounceTimer;
        function recalculateShipping() {
            clearTimeout(shippingDebounceTimer);
            shippingDebounceTimer = setTimeout(function() {
                var useDifferentAddress = $('#ship_to_different_address').is(':checked');
                var country, state, postcode;

                if (useDifferentAddress) {
                    country = $('#shipping_country').val();
                    state = $('#shipping_state').val();
                    postcode = $('#shipping_postcode').val();
                } else {
                    country = $('#billing_country').val();
                    state = $('#billing_state').val();
                    postcode = $('#billing_postcode').val();
                }

                // Only recalculate if we have at least a country
                if (!country) return;

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_calculate_shipping',
                        nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_nonce')); ?>',
                        country: country,
                        state: state,
                        postcode: postcode
                    },
                    success: function(response) {
                        if (response.success) {
                            var data = response.data;

                            // Update shipping display
                            if (data.allows_shipping_choice && data.shipping_methods && data.shipping_methods.length > 0) {
                                // Update shipping methods list if present
                                var $methodsList = $('.shipping-methods-list');
                                if ($methodsList.length) {
                                    var html = '';
                                    $.each(data.shipping_methods, function(i, method) {
                                        html += '<label class="shipping-method-option ' + (method.selected ? 'selected' : '') + '">' +
                                            '<input type="radio" name="shipping_method" value="' + method.id + '" ' + (method.selected ? 'checked' : '') + ' data-cost="' + method.cost + '">' +
                                            '<span class="method-name">' + method.name + '</span>' +
                                            '<span class="method-cost">' + method.formatted_cost + '</span>' +
                                            '</label>';
                                    });
                                    $methodsList.html(html);
                                }
                            } else {
                                // Update single shipping line
                                var shippingDisplay = data.shipping_amount > 0 ? '$' + parseFloat(data.shipping_amount).toFixed(2) : 'Free';
                                $('.shipping-row .shipping-cost').text(shippingDisplay);
                            }

                            // Update grand total
                            $('.order-totals .total-final span:last').text('$' + parseFloat(data.total).toFixed(2));
                            $('#ggmc-checkout-form').data('cart-total', data.total);
                        }
                    }
                });
            }, 500);
        }

        // Bind address change events for shipping recalculation
        $('#billing_country, #billing_state, #billing_postcode').on('change blur', function() {
            if (!$('#ship_to_different_address').is(':checked')) {
                recalculateShipping();
            }
        });
        $('#shipping_country, #shipping_state, #shipping_postcode').on('change blur', function() {
            if ($('#ship_to_different_address').is(':checked')) {
                recalculateShipping();
            }
        });
        $('#ship_to_different_address').on('change', function() {
            recalculateShipping();
        });

        // Function to update order totals display
        function updateOrderTotals(data) {
            if (data.tax_amount !== undefined) {
                var $taxRow = $('.order-totals .tax-row');
                if (data.tax_amount > 0) {
                    if ($taxRow.length === 0) {
                        // Create tax row if it doesn't exist
                        var taxHtml = '<div class="total-row tax-row"><span>' + data.tax_label + ':</span><span>$' + parseFloat(data.tax_amount).toFixed(2) + '</span></div>';
                        $('.order-totals .total-row:first').after(taxHtml);
                    } else {
                        $taxRow.find('span:last').text('$' + parseFloat(data.tax_amount).toFixed(2));
                    }
                    $taxRow.show();
                } else {
                    $taxRow.hide();
                }
            }
            if (data.grand_total !== undefined) {
                $('.order-totals .total-final span:last').text('$' + parseFloat(data.grand_total).toFixed(2));
            }
            if (data.is_exempt) {
                // Show tax exempt notice
                if ($('.tax-exempt-notice').length === 0) {
                    $('.order-totals').prepend('<div class="tax-exempt-notice" style="background: #d4edda; color: #155724; padding: 8px 12px; border-radius: 4px; margin-bottom: 15px; font-size: 13px;">Tax exempt order</div>');
                }
            } else {
                $('.tax-exempt-notice').remove();
            }
        }

        // Handle form submission
        $('#ggmc-checkout-form').on('submit', function(e) {
            e.preventDefault();
            e.stopPropagation();

            const $form = $(this);

            // Don't submit in editor preview mode
            if ($form.data('preview') === true || $form.data('preview') === 'true') {
                alert('<?php esc_html_e('Form submission is disabled in editor preview mode.', 'ggm-commerce'); ?>');
                return false;
            }

            const $submitBtn = $form.find('.checkout-button');
            const originalText = $submitBtn.text();

            // Disable submit button and show loading
            $submitBtn.prop('disabled', true).text('Processing...');

            // Get form data
            const formData = new FormData(this);
            formData.append('action', 'ggm_commerce_create_order');
            formData.append('nonce', '<?php echo esc_js(wp_create_nonce('ggm_commerce_checkout')); ?>');

            // Add cart items (including variation_id for variable products and variation_data for Independent mode)
            <?php foreach ($cart_items as $key => $item) : ?>
            formData.append('cart_items[<?php echo esc_js($key); ?>][product_id]', '<?php echo esc_js($item['product_id']); ?>');
            formData.append('cart_items[<?php echo esc_js($key); ?>][quantity]', '<?php echo esc_js($item['quantity']); ?>');
            <?php if (!empty($item['variation_id'])) : ?>
            formData.append('cart_items[<?php echo esc_js($key); ?>][variation_id]', '<?php echo esc_js($item['variation_id']); ?>');
            <?php endif; ?>
            <?php if (!empty($item['variation_data'])) : ?>
            formData.append('cart_items[<?php echo esc_js($key); ?>][variation_data]', <?php echo wp_json_encode(wp_json_encode($item['variation_data'])); ?>);
            <?php endif; ?>
            <?php endforeach; ?>

            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        var order = response.data.order;
                        var paymentMethod = $('input[name="payment_method"]:checked').val() || 'default';
                        var orderTotal = parseFloat(order.total);

                        // Free orders: skip payment gateway entirely
                        if (orderTotal === 0) {
                            paymentMethod = 'free';
                        }

                        // Trigger order created event for payment gateways
                        $(document).trigger('ggm_commerce_order_created', {
                            order_id: order.order_id,
                            order_number: order.order_number,
                            total: orderTotal,
                            payment_method: paymentMethod
                        });

                        // For free orders, Stripe/PayPal not needed — redirect immediately
                        // For default/other payment methods, redirect to thank you page immediately
                        if (paymentMethod !== 'stripe' && paymentMethod !== 'paypal') {
                            // Trigger cart update to show 0 items
                            $(document).trigger('ggm_commerce_cart_updated', {
                                count: 0,
                                total: 0,
                                items: []
                            });

                            // Redirect to confirmation page
                            if (response.data.confirmation_url) {
                                window.location.href = response.data.confirmation_url;
                            } else {
                                // Fallback: show inline confirmation if no thank you page configured
                                $('#ggmc-checkout-form').hide();
                                var confirmationHtml = '<div class="order-confirmation">' +
                                    '<div class="confirmation-header">' +
                                    '<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                                    '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>' +
                                    '<polyline points="22 4 12 14.01 9 11.01"></polyline>' +
                                    '</svg>' +
                                    '<h2>Thank You!</h2>' +
                                    '<p>Your order has been placed successfully</p>' +
                                    '</div>' +
                                    '<div class="order-details">' +
                                    '<div class="order-number"><strong>Order Number:</strong> ' + order.order_number + '</div>' +
                                    '<div class="order-total"><strong>Total:</strong> $' + parseFloat(order.total).toFixed(2) + '</div>' +
                                    '</div>' +
                                    '<div class="confirmation-actions">' +
                                    '<a href="<?php echo esc_url(home_url('/shop')); ?>" class="btn btn-primary">Continue Shopping</a>' +
                                    <?php if (is_user_logged_in()) : ?>'<a href="<?php echo esc_url(home_url('/my-account')); ?>" class="btn btn-secondary">View My Orders</a>' +<?php endif; ?>
                                    '</div>' +
                                    '</div>';
                                $('.ggmc-checkout-container').html(confirmationHtml);
                            }
                        }
                        // For Stripe/PayPal, store order data and confirmation URL for later use by completion handler
                        if (paymentMethod === 'stripe' || paymentMethod === 'paypal') {
                            window.ggmcPendingOrder = order;
                            window.ggmcConfirmationUrl = response.data.confirmation_url || '';
                        }
                    } else {
                        alert('Error: ' + response.data.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Checkout AJAX error:', status, error, xhr.responseText);
                    alert('An error occurred: ' + (error || status) + '. Please try again.');
                },
                complete: function() {
                    $submitBtn.prop('disabled', false).text(originalText);
                }
            });
        });

        // Listen for order completion from payment gateways (Stripe/PayPal)
        $(document).on('ggm_commerce_order_complete', function(e, data) {
            var order = window.ggmcPendingOrder;
            var confirmationUrl = window.ggmcConfirmationUrl;

            // Trigger cart update to show 0 items
            $(document).trigger('ggm_commerce_cart_updated', {
                count: 0,
                total: 0,
                items: []
            });

            // Clear pending order data
            window.ggmcPendingOrder = null;
            window.ggmcConfirmationUrl = null;

            // Redirect to confirmation page
            if (confirmationUrl) {
                window.location.href = confirmationUrl;
            } else {
                // Fallback: show inline confirmation if no thank you page configured
                if (!order) {
                    order = {
                        order_number: data.order_id,
                        total: 0,
                        status: 'processing'
                    };
                }

                $('#ggmc-checkout-form').hide();

                var confirmationHtml = '<div class="order-confirmation">' +
                    '<div class="confirmation-header">' +
                    '<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">' +
                    '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>' +
                    '<polyline points="22 4 12 14.01 9 11.01"></polyline>' +
                    '</svg>' +
                    '<h2>Thank You!</h2>' +
                    '<p>Your order has been placed successfully</p>' +
                    '</div>' +
                    '<div class="order-details">' +
                    '<div class="order-number"><strong>Order Number:</strong> ' + order.order_number + '</div>' +
                    '<div class="order-total"><strong>Total:</strong> $' + parseFloat(order.total).toFixed(2) + '</div>' +
                    '<div class="payment-method"><strong>Payment:</strong> ' + (data.gateway === 'stripe' ? 'Card (Stripe)' : 'PayPal') + '</div>' +
                    '</div>' +
                    '<div class="confirmation-actions">' +
                    '<a href="<?php echo esc_url(home_url('/shop')); ?>" class="btn btn-primary">Continue Shopping</a>' +
                    <?php if (is_user_logged_in()) : ?>'<a href="<?php echo esc_url(home_url('/my-account')); ?>" class="btn btn-secondary">View My Orders</a>' +<?php endif; ?>
                    '</div>' +
                    '</div>';

                $('.ggmc-checkout-container').html(confirmationHtml);
            }
        });

        // Discount Code Toggle
        $('.discount-toggle-label').on('click', function() {
            var $toggle = $(this);
            var $form = $toggle.siblings('.discount-form-container');
            var $icon = $toggle.find('.discount-toggle-icon');
            $toggle.toggleClass('expanded');
            $form.slideToggle(200);
            $icon.text($toggle.hasClass('expanded') ? '-' : '+');
            if ($toggle.hasClass('expanded')) {
                setTimeout(function() {
                    $form.find('.discount-input').focus();
                }, 210);
            }
        });

        // Apply Discount Code
        $('.ggmc-discount-section').on('click', '.discount-apply-btn', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $section = $btn.closest('.ggmc-discount-section');
            var $input = $section.find('.discount-input');
            var code = $input.val().trim();
            var nonce = $section.data('nonce');

            if (!code) {
                $input.addClass('error');
                return;
            }

            $input.removeClass('error');
            $btn.prop('disabled', true).text('<?php esc_html_e('Applying...', 'ggm-commerce'); ?>');

            // Remove any existing message
            $section.find('.discount-message').hide().empty();

            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: {
                    action: 'ggmc_apply_discount',
                    nonce: nonce,
                    code: code
                },
                success: function(response) {
                    if (response.success) {
                        // Reload the page to show updated totals with discount
                        // (Full AJAX update would require rebuilding the entire order summary)
                        location.reload();
                    } else {
                        // Show error message
                        $section.find('.discount-message').addClass('error').text(response.data.message).show();
                        $btn.prop('disabled', false).text('<?php echo esc_js($settings['discount_button_text'] ?? __('Apply', 'ggm-commerce')); ?>');
                    }
                },
                error: function() {
                    $section.find('.discount-message').addClass('error').text('<?php esc_html_e('An error occurred. Please try again.', 'ggm-commerce'); ?>').show();
                    $btn.prop('disabled', false).text('<?php echo esc_js($settings['discount_button_text'] ?? __('Apply', 'ggm-commerce')); ?>');
                }
            });
        });

        // Enter key to apply discount
        $('.ggmc-discount-section').on('keypress', '.discount-input', function(e) {
            if (e.which === 13) {
                e.preventDefault();
                $(this).closest('.ggmc-discount-section').find('.discount-apply-btn').click();
            }
        });

        // Remove Discount Code
        $('.ggmc-discount-section').on('click', '.discount-remove-btn', function(e) {
            e.preventDefault();
            var $btn = $(this);
            var $section = $btn.closest('.ggmc-discount-section');
            var nonce = $section.data('nonce');

            $btn.prop('disabled', true);

            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                type: 'POST',
                data: {
                    action: 'ggmc_remove_discount',
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Reload the page to show updated totals without discount
                        location.reload();
                    } else {
                        alert(response.data.message || '<?php esc_html_e('Error removing discount', 'ggm-commerce'); ?>');
                        $btn.prop('disabled', false);
                    }
                },
                error: function() {
                    alert('<?php esc_html_e('An error occurred. Please try again.', 'ggm-commerce'); ?>');
                    $btn.prop('disabled', false);
                }
            });
        });
    });
    </script>
    <?php
}
