<?php
/**
 * Customer Account Widget - Render Functions
 *
 * Standalone functions that replace the former GGM_Commerce_Customer_Account_Renderer class.
 * All functions are prefixed ggmc_customer_account_.
 * The data handler is instantiated locally inside ggmc_customer_account_render().
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Main render entry point — called from the widget's render() method.
 *
 * @param GGM_Commerce_Widget_Customer_Account $widget
 */
function ggmc_customer_account_render( $widget ) {
    $settings     = $widget->get_settings_for_display();
    $data_handler = new GGM_Commerce_Customer_Account_Data_Handler();

    echo '<div class="ggmc-customer-account-widget">';

    if ( $data_handler->is_user_logged_in() ) {
        ggmc_customer_account_render_dashboard( $data_handler, $settings );
    } else {
        ggmc_customer_account_render_login_register_forms( $data_handler, $settings );
    }

    echo '</div>';

    ggmc_customer_account_render_styles();
    ggmc_customer_account_render_scripts( $settings );
}

/**
 * Render account dashboard for logged-in users.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param array                                      $settings
 */
function ggmc_customer_account_render_dashboard( $data_handler, $settings ) {
    $user_id = $data_handler->get_current_user_id();
    $user    = $data_handler->get_current_user();

    // Pagination settings
    $orders_per_page = isset( $settings['orders_per_page'] ) ? (int) $settings['orders_per_page'] : 10;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Pagination page number, no action taken
    $current_page = isset( $_GET['orders_page'] ) ? max( 1, (int) $_GET['orders_page'] ) : 1;
    $offset       = ( $current_page - 1 ) * $orders_per_page;

    // Get orders with pagination
    $orders       = $data_handler->get_user_orders( $user_id, $orders_per_page, $offset );
    $total_orders = $data_handler->get_user_orders_count( $user_id );
    $total_pages  = ceil( $total_orders / $orders_per_page );

    ?>
    <div class="ggmc-account-dashboard">
        <?php ggmc_customer_account_render_welcome_section( $user ); ?>
        <?php ggmc_customer_account_render_account_tabs( $data_handler, $settings, $user_id, $orders, $current_page, $total_pages, $total_orders ); ?>
        <?php ggmc_customer_account_render_account_actions( $data_handler ); ?>
    </div>
    <?php
}

/**
 * Render welcome section.
 *
 * @param WP_User $user
 */
function ggmc_customer_account_render_welcome_section( $user ) {
    ?>
    <div class="account-welcome">
        <h2><?php echo sprintf(
            /* translators: %s: user display name */
            esc_html__( 'Welcome, %s!', 'ggm-commerce' ),
            esc_html( $user->display_name )
        ); ?></h2>
        <p><?php esc_html_e( 'Manage your account and view your orders.', 'ggm-commerce' ); ?></p>
    </div>
    <?php
}

/**
 * Render account tabs.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param array                                      $settings
 * @param int                                        $user_id
 * @param array                                      $orders
 * @param int                                        $current_page
 * @param int                                        $total_pages
 * @param int                                        $total_orders
 */
function ggmc_customer_account_render_account_tabs( $data_handler, $settings, $user_id, $orders, $current_page = 1, $total_pages = 1, $total_orders = 0 ) {
    $default_tab           = isset( $settings['default_tab'] ) ? $settings['default_tab'] : 'orders';
    $tax                   = ggm_commerce_tax();
    $show_business_tab     = $tax->is_b2b_enabled();
    $show_downloads_tab    = $data_handler->is_downloads_feature_active();
    $show_wishlists_tab    = ggmc_customer_account_is_wishlist_feature_active();
    $show_subscriptions_tab = ggmc_customer_account_is_subscriptions_feature_active();
    ?>
    <div class="account-tabs">
        <nav class="tab-nav">
            <button class="tab-link <?php echo $default_tab === 'orders' ? 'active' : ''; ?>" data-tab="orders"><?php esc_html_e( 'My Orders', 'ggm-commerce' ); ?></button>
            <?php if ( $show_downloads_tab ) : ?>
                <button class="tab-link <?php echo $default_tab === 'downloads' ? 'active' : ''; ?>" data-tab="downloads"><?php esc_html_e( 'Downloads', 'ggm-commerce' ); ?></button>
            <?php endif; ?>
            <?php if ( $show_wishlists_tab ) : ?>
                <button class="tab-link <?php echo $default_tab === 'wishlists' ? 'active' : ''; ?>" data-tab="wishlists"><?php esc_html_e( 'Wishlists', 'ggm-commerce' ); ?></button>
            <?php endif; ?>
            <?php if ( $show_subscriptions_tab ) : ?>
                <button class="tab-link <?php echo $default_tab === 'subscriptions' ? 'active' : ''; ?>" data-tab="subscriptions"><?php esc_html_e( 'Subscriptions', 'ggm-commerce' ); ?></button>
            <?php endif; ?>
            <button class="tab-link <?php echo $default_tab === 'profile' ? 'active' : ''; ?>" data-tab="profile"><?php esc_html_e( 'Profile', 'ggm-commerce' ); ?></button>
            <button class="tab-link <?php echo $default_tab === 'addresses' ? 'active' : ''; ?>" data-tab="addresses"><?php esc_html_e( 'Addresses', 'ggm-commerce' ); ?></button>
            <?php if ( $show_business_tab ) : ?>
                <button class="tab-link <?php echo $default_tab === 'business' ? 'active' : ''; ?>" data-tab="business"><?php esc_html_e( 'Business Settings', 'ggm-commerce' ); ?></button>
            <?php endif; ?>
        </nav>

        <?php ggmc_customer_account_render_orders_tab( $data_handler, $orders, $default_tab === 'orders', $current_page, $total_pages, $total_orders ); ?>
        <?php if ( $show_downloads_tab ) : ?>
            <?php ggmc_customer_account_render_downloads_tab( $data_handler, $user_id, $default_tab === 'downloads' ); ?>
        <?php endif; ?>
        <?php if ( $show_wishlists_tab ) : ?>
            <?php ggmc_customer_account_render_wishlists_tab( $user_id, $default_tab === 'wishlists' ); ?>
        <?php endif; ?>
        <?php if ( $show_subscriptions_tab ) : ?>
            <?php ggmc_customer_account_render_subscriptions_tab( $user_id, $default_tab === 'subscriptions' ); ?>
        <?php endif; ?>
        <?php ggmc_customer_account_render_profile_tab( $data_handler, $user_id, $default_tab === 'profile' ); ?>
        <?php ggmc_customer_account_render_addresses_tab( $user_id, $default_tab === 'addresses' ); ?>
        <?php if ( $show_business_tab ) : ?>
            <?php ggmc_customer_account_render_business_tab( $data_handler, $user_id, $default_tab === 'business' ); ?>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Render orders tab.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param array                                      $orders
 * @param bool                                       $is_active
 * @param int                                        $current_page
 * @param int                                        $total_pages
 * @param int                                        $total_orders
 */
function ggmc_customer_account_render_orders_tab( $data_handler, $orders, $is_active = false, $current_page = 1, $total_pages = 1, $total_orders = 0 ) {
    $currency_options = get_option( 'ggm_commerce_currency_options', array() );
    $currency_symbol  = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '£';
    ?>
    <div id="orders" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <!-- Orders List View -->
        <div class="orders-list-view">
            <div class="orders-header">
                <h3><?php esc_html_e( 'My Orders', 'ggm-commerce' ); ?></h3>
                <?php if ( $total_orders > 0 ) : ?>
                    <span class="orders-count">
                        <?php
                        /* translators: %d: total number of orders */
                        echo esc_html( sprintf( _n( '%d order', '%d orders', $total_orders, 'ggm-commerce' ), $total_orders ) );
                        ?>
                    </span>
                <?php endif; ?>
            </div>
            <?php if ( $orders ) : ?>
                <div class="orders-table-responsive">
                    <table class="orders-table">
                        <thead>
                            <tr>
                                <th><?php esc_html_e( 'Order #', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Date', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Status', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Total', 'ggm-commerce' ); ?></th>
                                <th><?php esc_html_e( 'Actions', 'ggm-commerce' ); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ( $orders as $order ) : ?>
                                <tr>
                                    <td>#<?php echo esc_html( $order->order_number ); ?></td>
                                    <td><?php echo esc_html( gmdate( 'M j, Y', strtotime( $order->created_at ) ) ); ?></td>
                                    <td>
                                        <span class="order-status status-<?php echo esc_attr( $order->status ); ?>">
                                            <?php echo esc_html( $data_handler->format_order_status( $order->status ) ); ?>
                                        </span>
                                    </td>
                                    <td><?php echo esc_html( $currency_symbol . number_format( $order->total_amount, 2 ) ); ?></td>
                                    <td>
                                        <button class="btn-view-order" data-order-id="<?php echo esc_attr( $order->id ); ?>">
                                            <?php esc_html_e( 'View', 'ggm-commerce' ); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ( $total_pages > 1 ) : ?>
                    <?php ggmc_customer_account_render_orders_pagination( $current_page, $total_pages ); ?>
                <?php endif; ?>
            <?php else : ?>
                <p class="no-orders"><?php esc_html_e( 'You have no orders yet.', 'ggm-commerce' ); ?></p>
            <?php endif; ?>
        </div>

        <!-- Order Detail View (hidden by default) -->
        <div class="order-detail-view" style="display: none;">
            <div class="order-detail-header">
                <button class="btn-back-to-orders">
                    <span class="dashicons dashicons-arrow-left-alt"></span>
                    <?php esc_html_e( 'Back to Orders', 'ggm-commerce' ); ?>
                </button>
                <button class="btn-print-invoice">
                    <span class="dashicons dashicons-printer"></span>
                    <?php esc_html_e( 'Print Invoice', 'ggm-commerce' ); ?>
                </button>
            </div>
            <div class="order-detail-content">
                <!-- Content loaded via AJAX -->
            </div>
        </div>
    </div>
    <?php
}

/**
 * Render orders pagination controls.
 *
 * @param int $current_page
 * @param int $total_pages
 */
function ggmc_customer_account_render_orders_pagination( $current_page, $total_pages ) {
    $base_url = remove_query_arg( 'orders_page' );
    ?>
    <nav class="orders-pagination">
        <?php if ( $current_page > 1 ) : ?>
            <a href="<?php echo esc_url( add_query_arg( 'orders_page', $current_page - 1, $base_url ) ); ?>#orders" class="pagination-link pagination-prev">
                &larr; <?php esc_html_e( 'Previous', 'ggm-commerce' ); ?>
            </a>
        <?php else : ?>
            <span class="pagination-link pagination-prev disabled">&larr; <?php esc_html_e( 'Previous', 'ggm-commerce' ); ?></span>
        <?php endif; ?>

        <span class="pagination-info">
            <?php
            /* translators: 1: current page number, 2: total pages */
            echo esc_html( sprintf( __( 'Page %1$d of %2$d', 'ggm-commerce' ), $current_page, $total_pages ) );
            ?>
        </span>

        <?php if ( $current_page < $total_pages ) : ?>
            <a href="<?php echo esc_url( add_query_arg( 'orders_page', $current_page + 1, $base_url ) ); ?>#orders" class="pagination-link pagination-next">
                <?php esc_html_e( 'Next', 'ggm-commerce' ); ?> &rarr;
            </a>
        <?php else : ?>
            <span class="pagination-link pagination-next disabled"><?php esc_html_e( 'Next', 'ggm-commerce' ); ?> &rarr;</span>
        <?php endif; ?>
    </nav>
    <?php
}

/**
 * Render downloads tab.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param int                                        $user_id
 * @param bool                                       $is_active
 */
function ggmc_customer_account_render_downloads_tab( $data_handler, $user_id, $is_active = false ) {
    $downloads = $data_handler->get_customer_downloads( $user_id );
    ?>
    <div id="downloads" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <div class="downloads-header">
            <h3><?php esc_html_e( 'My Downloads', 'ggm-commerce' ); ?></h3>
            <?php if ( ! empty( $downloads ) ) : ?>
                <span class="downloads-count">
                    <?php
                    $count = count( $downloads );
                    /* translators: %d: total number of downloads */
                    echo esc_html( sprintf( _n( '%d file', '%d files', $count, 'ggm-commerce' ), $count ) );
                    ?>
                </span>
            <?php endif; ?>
        </div>

        <?php if ( ! empty( $downloads ) ) : ?>
            <div class="ggmc-downloads-list">
                <?php foreach ( $downloads as $download ) :
                    $can_download   = ggmc_customer_account_can_download( $download );
                    $status_class   = $can_download ? '' : 'unavailable';
                    $remaining_text = ggmc_customer_account_get_remaining_downloads_text( $download );
                    $expiry_text    = ggmc_customer_account_get_expiry_text( $download );
                ?>
                    <div class="ggmc-download-item <?php echo esc_attr( $status_class ); ?>">
                        <div class="ggmc-download-info">
                            <div class="ggmc-download-product">
                                <span class="ggmc-download-label"><?php esc_html_e( 'Product:', 'ggm-commerce' ); ?></span>
                                <span class="ggmc-download-value"><?php echo esc_html( $download['product_name'] ?? __( 'Unknown Product', 'ggm-commerce' ) ); ?></span>
                            </div>
                            <div class="ggmc-download-file">
                                <span class="ggmc-download-label"><?php esc_html_e( 'File:', 'ggm-commerce' ); ?></span>
                                <span class="ggmc-download-value"><?php echo esc_html( $download['download_name'] ?? __( 'Download', 'ggm-commerce' ) ); ?></span>
                            </div>
                            <div class="ggmc-download-order">
                                <span class="ggmc-download-label"><?php esc_html_e( 'Order:', 'ggm-commerce' ); ?></span>
                                <span class="ggmc-download-value">#<?php echo esc_html( $download['order_id'] ); ?></span>
                            </div>
                            <?php if ( $remaining_text ) : ?>
                                <div class="ggmc-download-remaining">
                                    <span class="ggmc-download-label"><?php esc_html_e( 'Remaining:', 'ggm-commerce' ); ?></span>
                                    <span class="ggmc-download-value"><?php echo esc_html( $remaining_text ); ?></span>
                                </div>
                            <?php endif; ?>
                            <?php if ( $expiry_text ) : ?>
                                <div class="ggmc-download-expiry">
                                    <span class="ggmc-download-label"><?php esc_html_e( 'Expires:', 'ggm-commerce' ); ?></span>
                                    <span class="ggmc-download-value"><?php echo esc_html( $expiry_text ); ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="ggmc-download-actions">
                            <?php if ( $can_download ) : ?>
                                <a href="<?php echo esc_url( $download['download_url'] ?? '#' ); ?>" class="ggmc-download-button">
                                    <?php esc_html_e( 'Download', 'ggm-commerce' ); ?>
                                </a>
                            <?php else : ?>
                                <span class="ggmc-download-status <?php echo esc_attr( ggmc_customer_account_get_unavailable_reason_class( $download ) ); ?>">
                                    <?php echo esc_html( ggmc_customer_account_get_unavailable_reason( $download ) ); ?>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else : ?>
            <div class="ggmc-downloads-empty">
                <p><?php esc_html_e( 'You have no downloadable files yet. Purchase a digital product to see your downloads here.', 'ggm-commerce' ); ?></p>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Check if a download can be downloaded (works with array format).
 *
 * @param array $download
 * @return bool
 */
function ggmc_customer_account_can_download( $download ) {
    // Use pre-computed can_download from Downloads class if available
    if ( isset( $download['can_download'] ) ) {
        return (bool) $download['can_download'];
    }

    // Fallback checks
    if ( ! empty( $download['access_expires_at'] ) && strtotime( $download['access_expires_at'] ) < time() ) {
        return false;
    }

    $download_limit = isset( $download['download_limit'] ) ? (int) $download['download_limit'] : -1;
    $download_count = isset( $download['download_count'] ) ? (int) $download['download_count'] : 0;
    if ( $download_limit > 0 && $download_count >= $download_limit ) {
        return false;
    }

    if ( isset( $download['status'] ) && $download['status'] !== 'active' ) {
        return false;
    }

    return true;
}

/**
 * Get remaining downloads text (works with array format).
 *
 * @param array $download
 * @return string
 */
function ggmc_customer_account_get_remaining_downloads_text( $download ) {
    // Use pre-computed downloads_remaining from Downloads class if available
    if ( isset( $download['downloads_remaining'] ) ) {
        if ( $download['downloads_remaining'] === 'unlimited' ) {
            return __( 'Unlimited', 'ggm-commerce' );
        }
        $remaining = (int) $download['downloads_remaining'];
        /* translators: %d: number of downloads remaining */
        return sprintf( _n( '%d download left', '%d downloads left', $remaining, 'ggm-commerce' ), $remaining );
    }

    // Fallback
    $download_limit = isset( $download['download_limit'] ) ? (int) $download['download_limit'] : -1;
    if ( $download_limit <= 0 ) {
        return __( 'Unlimited', 'ggm-commerce' );
    }

    $download_count = isset( $download['download_count'] ) ? (int) $download['download_count'] : 0;
    $remaining      = max( 0, $download_limit - $download_count );
    /* translators: %d: number of downloads remaining */
    return sprintf( _n( '%d download left', '%d downloads left', $remaining, 'ggm-commerce' ), $remaining );
}

/**
 * Get expiry text (works with array format).
 *
 * @param array $download
 * @return string
 */
function ggmc_customer_account_get_expiry_text( $download ) {
    if ( isset( $download['is_expired'] ) && $download['is_expired'] ) {
        return __( 'Expired', 'ggm-commerce' );
    }

    if ( empty( $download['access_expires_at'] ) ) {
        return __( 'Never', 'ggm-commerce' );
    }

    $expiry_time = strtotime( $download['access_expires_at'] );
    if ( $expiry_time < time() ) {
        return __( 'Expired', 'ggm-commerce' );
    }

    return gmdate( 'M j, Y', $expiry_time );
}

/**
 * Get unavailable reason (works with array format).
 *
 * @param array $download
 * @return string
 */
function ggmc_customer_account_get_unavailable_reason( $download ) {
    if ( ! empty( $download['is_expired'] ) || ( ! empty( $download['access_expires_at'] ) && strtotime( $download['access_expires_at'] ) < time() ) ) {
        return __( 'Expired', 'ggm-commerce' );
    }

    $download_limit = isset( $download['download_limit'] ) ? (int) $download['download_limit'] : -1;
    $download_count = isset( $download['download_count'] ) ? (int) $download['download_count'] : 0;
    if ( $download_limit > 0 && $download_count >= $download_limit ) {
        return __( 'Download limit reached', 'ggm-commerce' );
    }

    if ( isset( $download['status'] ) && $download['status'] !== 'active' ) {
        return __( 'Unavailable', 'ggm-commerce' );
    }

    return __( 'Unavailable', 'ggm-commerce' );
}

/**
 * Get CSS class for unavailable reason (works with array format).
 *
 * @param array $download
 * @return string
 */
function ggmc_customer_account_get_unavailable_reason_class( $download ) {
    if ( ! empty( $download['is_expired'] ) || ( ! empty( $download['access_expires_at'] ) && strtotime( $download['access_expires_at'] ) < time() ) ) {
        return 'expired';
    }

    $download_limit = isset( $download['download_limit'] ) ? (int) $download['download_limit'] : -1;
    $download_count = isset( $download['download_count'] ) ? (int) $download['download_count'] : 0;
    if ( $download_limit > 0 && $download_count >= $download_limit ) {
        return 'limit-reached';
    }

    return 'unavailable';
}

/**
 * Render profile tab.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param int                                        $user_id
 * @param bool                                       $is_active
 */
function ggmc_customer_account_render_profile_tab( $data_handler, $user_id, $is_active = false ) {
    $profile = $data_handler->get_user_profile( $user_id );

    ?>
    <div id="profile" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <h3><?php esc_html_e( 'Profile Information', 'ggm-commerce' ); ?></h3>
        <form class="profile-form" data-action="update_profile">
            <div class="form-row">
                <div class="form-group">
                    <label><?php esc_html_e( 'First Name', 'ggm-commerce' ); ?></label>
                    <input type="text" name="first_name" value="<?php echo esc_attr( $profile['first_name'] ); ?>" required>
                </div>
                <div class="form-group">
                    <label><?php esc_html_e( 'Last Name', 'ggm-commerce' ); ?></label>
                    <input type="text" name="last_name" value="<?php echo esc_attr( $profile['last_name'] ); ?>" required>
                </div>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Email', 'ggm-commerce' ); ?></label>
                <input type="email" name="email" value="<?php echo esc_attr( $profile['email'] ); ?>" required>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Phone', 'ggm-commerce' ); ?></label>
                <input type="tel" name="phone" value="<?php echo esc_attr( $profile['phone'] ); ?>">
            </div>
            <button type="submit" class="btn-update-profile"><?php esc_html_e( 'Update Profile', 'ggm-commerce' ); ?></button>
        </form>
    </div>
    <?php
}

/**
 * Render addresses tab.
 *
 * @param int  $user_id
 * @param bool $is_active
 */
function ggmc_customer_account_render_addresses_tab( $user_id, $is_active = false ) {
    global $ggm_commerce_address_manager;

    // Check if multiple addresses are enabled
    $multiple_billing_enabled  = $ggm_commerce_address_manager->are_multiple_billing_addresses_enabled();
    $multiple_shipping_enabled = $ggm_commerce_address_manager->are_multiple_shipping_addresses_enabled();

    ?>
    <div id="addresses" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <h3><?php esc_html_e( 'Billing & Shipping Addresses', 'ggm-commerce' ); ?></h3>

        <!-- Billing Addresses -->
        <div class="address-type-section">
            <div class="address-type-header">
                <h4><?php esc_html_e( 'Billing Addresses', 'ggm-commerce' ); ?></h4>
                <?php if ( $multiple_billing_enabled ) : ?>
                    <button class="btn-add-address" data-type="billing">
                        <?php esc_html_e( '+ Add New Address', 'ggm-commerce' ); ?>
                    </button>
                <?php endif; ?>
            </div>
            <?php ggmc_customer_account_render_address_list( $user_id, 'billing', $multiple_billing_enabled ); ?>
        </div>

        <!-- Shipping Addresses -->
        <div class="address-type-section">
            <div class="address-type-header">
                <h4><?php esc_html_e( 'Shipping Addresses', 'ggm-commerce' ); ?></h4>
                <?php if ( $multiple_shipping_enabled ) : ?>
                    <button class="btn-add-address" data-type="shipping">
                        <?php esc_html_e( '+ Add New Address', 'ggm-commerce' ); ?>
                    </button>
                <?php endif; ?>
            </div>
            <?php ggmc_customer_account_render_address_list( $user_id, 'shipping', $multiple_shipping_enabled ); ?>
        </div>
    </div>

    <?php
}

/**
 * Render list of addresses.
 *
 * @param int    $user_id
 * @param string $type
 * @param bool   $multiple_enabled
 */
function ggmc_customer_account_render_address_list( $user_id, $type, $multiple_enabled ) {
    global $ggm_commerce_address_manager;

    $addresses = $ggm_commerce_address_manager->get_user_addresses( $user_id, $type );

    if ( empty( $addresses ) ) {
        ?>
        <div class="no-addresses">
            <p><?php printf(
                /* translators: %s: address type (billing or shipping) */
                esc_html__( 'No %s addresses found.', 'ggm-commerce' ),
                esc_html( $type )
            ); ?></p>
            <button class="btn-add-address" data-type="<?php echo esc_attr( $type ); ?>">
                <?php printf(
                    /* translators: %s: address type (Billing or Shipping) */
                    esc_html__( 'Add %s Address', 'ggm-commerce' ),
                    esc_html( ucfirst( $type ) )
                ); ?>
            </button>
        </div>
        <?php
        return;
    }

    ?>
    <div class="address-list">
        <?php foreach ( $addresses as $address ) :
            $label             = $ggm_commerce_address_manager->get_address_label( $address );
            $formatted_address = $ggm_commerce_address_manager->format_address( $address, 'html' );
        ?>
            <div class="address-card" data-address-id="<?php echo esc_attr( $address->id ); ?>">
                <div class="address-card-header">
                    <h5>
                        <?php echo esc_html( $label ); ?>
                        <?php if ( $address->is_default ) : ?>
                            <span class="badge-default"><?php esc_html_e( 'Default', 'ggm-commerce' ); ?></span>
                        <?php endif; ?>
                    </h5>
                    <div class="address-actions">
                        <button class="btn-edit-address" data-address-id="<?php echo esc_attr( $address->id ); ?>" title="<?php esc_attr_e( 'Edit', 'ggm-commerce' ); ?>">
                            <span class="dashicons dashicons-edit"></span>
                        </button>
                        <?php if ( $multiple_enabled && count( $addresses ) > 1 ) : ?>
                            <button class="btn-delete-address" data-address-id="<?php echo esc_attr( $address->id ); ?>" title="<?php esc_attr_e( 'Delete', 'ggm-commerce' ); ?>">
                                <span class="dashicons dashicons-trash"></span>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="address-card-body">
                    <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $formatted_address contains pre-escaped HTML from WP formatting functions ?>
                    <?php echo $formatted_address; ?>
                </div>
                <?php if ( $multiple_enabled && ! $address->is_default ) : ?>
                    <div class="address-card-footer">
                        <button class="btn-set-default" data-address-id="<?php echo esc_attr( $address->id ); ?>">
                            <?php esc_html_e( 'Set as Default', 'ggm-commerce' ); ?>
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php
}

/**
 * Render business settings tab (B2B / VAT).
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param int                                        $user_id
 * @param bool                                       $is_active
 */
function ggmc_customer_account_render_business_tab( $data_handler, $user_id, $is_active = false ) {
    $tax      = ggm_commerce_tax();
    $customer = $data_handler->get_customer_by_user_id( $user_id );

    // Get customer B2B data
    $company_name      = $customer ? ( $customer->company ?? '' ) : '';
    $tax_id            = $customer ? ( $customer->tax_id ?? '' ) : '';
    $tax_exempt_status = $customer ? ( $customer->tax_exempt_status ?? 'none' ) : 'none';
    $is_tax_exempt     = $customer ? ( $customer->is_tax_exempt ?? 0 ) : 0;

    // Get price display preference
    $price_display_pref = get_user_meta( $user_id, 'ggmc_price_display_preference', true );
    if ( empty( $price_display_pref ) ) {
        $price_display_pref = 'default';
    }

    $tax_label           = $tax->get_label();
    $validation_required = $tax->is_b2b_validation_required();

    ?>
    <div id="business" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <h3><?php esc_html_e( 'Business Settings', 'ggm-commerce' ); ?></h3>

        <!-- Tax Exemption Status -->
        <div class="business-status-card">
            <h4><?php esc_html_e( 'Tax Exemption Status', 'ggm-commerce' ); ?></h4>
            <?php
            $status_class       = 'status-none';
            $status_text        = __( 'Not Registered', 'ggm-commerce' );
            $status_description = __( 'Register your business details below to apply for tax exemption.', 'ggm-commerce' );

            if ( $tax_exempt_status === 'approved' ) {
                $status_class       = 'status-approved';
                $status_text        = __( 'Approved', 'ggm-commerce' );
                $status_description = __( 'Your tax exemption is active. Tax will not be charged on your orders.', 'ggm-commerce' );
            } elseif ( $tax_exempt_status === 'pending' ) {
                $status_class       = 'status-pending';
                $status_text        = __( 'Pending Approval', 'ggm-commerce' );
                $status_description = __( 'Your tax exemption request is awaiting approval. You will be notified once it is reviewed.', 'ggm-commerce' );
            } elseif ( $tax_exempt_status === 'rejected' ) {
                $status_class       = 'status-rejected';
                $status_text        = __( 'Rejected', 'ggm-commerce' );
                $status_description = __( 'Your tax exemption request was rejected. Please contact support for more information.', 'ggm-commerce' );
            }
            ?>
            <div class="exemption-status <?php echo esc_attr( $status_class ); ?>">
                <span class="status-badge"><?php echo esc_html( $status_text ); ?></span>
                <p class="status-description"><?php echo esc_html( $status_description ); ?></p>
            </div>
        </div>

        <!-- Business Details Form -->
        <form class="business-form" data-action="update_business">
            <h4><?php esc_html_e( 'Business Details', 'ggm-commerce' ); ?></h4>

            <div class="form-group">
                <label><?php esc_html_e( 'Company Name', 'ggm-commerce' ); ?></label>
                <input type="text" name="company_name" value="<?php echo esc_attr( $company_name ); ?>" placeholder="<?php esc_attr_e( 'Your company or business name', 'ggm-commerce' ); ?>">
            </div>

            <div class="form-group">
                <label><?php echo esc_html( $tax_label ); ?> <?php esc_html_e( 'Number', 'ggm-commerce' ); ?> <span class="required">*</span></label>
                <input type="text" name="tax_id" value="<?php echo esc_attr( $tax_id ); ?>" placeholder="<?php esc_attr_e( 'e.g., GB123456789', 'ggm-commerce' ); ?>" required>
                <p class="field-description">
                    <?php
                    /* translators: %s: tax label (e.g., VAT, GST) */
                    printf( esc_html__( 'Enter your %s registration number for tax exemption.', 'ggm-commerce' ), esc_html( $tax_label ) );
                    ?>
                </p>
            </div>

            <?php if ( $validation_required && $tax_exempt_status !== 'approved' ) : ?>
                <p class="validation-notice">
                    <span class="dashicons dashicons-info"></span>
                    <?php esc_html_e( 'Tax exemption requires approval. Once submitted, your request will be reviewed.', 'ggm-commerce' ); ?>
                </p>
            <?php endif; ?>

            <button type="submit" class="btn-update-business"><?php esc_html_e( 'Save Business Details', 'ggm-commerce' ); ?></button>
        </form>

        <!-- Price Display Preference -->
        <div class="price-preference-section">
            <h4><?php esc_html_e( 'Price Display Preference', 'ggm-commerce' ); ?></h4>
            <p class="section-description"><?php esc_html_e( 'Choose how you would like to see prices displayed throughout the store.', 'ggm-commerce' ); ?></p>

            <form class="price-preference-form" data-action="update_price_preference">
                <div class="form-group radio-group">
                    <label class="radio-label">
                        <input type="radio" name="price_display" value="default" <?php checked( $price_display_pref, 'default' ); ?>>
                        <span><?php esc_html_e( 'Use store default', 'ggm-commerce' ); ?></span>
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="price_display" value="excluding" <?php checked( $price_display_pref, 'excluding' ); ?>>
                        <span><?php esc_html_e( 'Show prices excluding tax', 'ggm-commerce' ); ?></span>
                    </label>
                    <label class="radio-label">
                        <input type="radio" name="price_display" value="including" <?php checked( $price_display_pref, 'including' ); ?>>
                        <span><?php esc_html_e( 'Show prices including tax', 'ggm-commerce' ); ?></span>
                    </label>
                </div>
                <button type="submit" class="btn-update-preference"><?php esc_html_e( 'Save Preference', 'ggm-commerce' ); ?></button>
            </form>
        </div>
    </div>
    <?php
}

/**
 * Check if wishlist premium feature is active.
 *
 * @return bool
 */
function ggmc_customer_account_is_wishlist_feature_active() {
    if ( ! class_exists( 'GGM_Commerce_License' ) ) {
        return false;
    }
    $license = \GGM_Commerce_License::instance();
    return $license->is_widget_activated( 'wishlist' );
}

/**
 * Check if subscription billing premium feature is active.
 *
 * @return bool
 */
function ggmc_customer_account_is_subscriptions_feature_active() {
    if ( ! class_exists( 'GGM_Commerce_License' ) ) {
        return false;
    }
    $license = \GGM_Commerce_License::instance();
    return $license->is_widget_activated( 'subscription-billing' );
}

/**
 * Render subscriptions tab.
 *
 * @param int  $user_id
 * @param bool $is_active
 */
function ggmc_customer_account_render_subscriptions_tab( $user_id, $is_active = false ) {
    $sub_manager   = \GGM_Commerce_Subscriptions::instance();
    $sub_settings  = \GGM_Commerce_Subscriptions::get_settings();
    $current_user  = wp_get_current_user();
    $subscriptions = $sub_manager->get_customer_subscriptions_by_email( $current_user->user_email );

    $statuses        = \GGM_Commerce_Subscriptions::get_statuses();
    $billing_periods = \GGM_Commerce_Subscriptions::get_billing_periods();
    $status_classes  = array(
        'active'         => 'ggmc-sub-active',
        'trial'          => 'ggmc-sub-trial',
        'paused'         => 'ggmc-sub-paused',
        'cancelled'      => 'ggmc-sub-cancelled',
        'on_hold'        => 'ggmc-sub-on-hold',
        'pending'        => 'ggmc-sub-pending',
        'expired'        => 'ggmc-sub-expired',
        'pending_cancel' => 'ggmc-sub-pending-cancel',
        'failed_payment' => 'ggmc-sub-failed',
    );

    $currency_options = get_option( 'ggm_commerce_currency_options', array() );
    $currency_symbol  = isset( $currency_options['symbol'] ) ? $currency_options['symbol'] : '$';

    $nonce = wp_create_nonce( 'ggmc_subscription_action' );
    ?>
    <div id="subscriptions" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <h3><?php esc_html_e( 'My Subscriptions', 'ggm-commerce' ); ?></h3>

        <?php if ( empty( $subscriptions ) ) : ?>
            <div class="ggmc-account-subscriptions-empty">
                <p><?php esc_html_e( 'You have no subscriptions.', 'ggm-commerce' ); ?></p>
            </div>
        <?php else : ?>
            <div class="ggmc-account-subscriptions-list">
                <?php foreach ( $subscriptions as $sub ) :
                    $status_class = $status_classes[ $sub->status ] ?? 'ggmc-sub-pending';
                    $status_label = $statuses[ $sub->status ] ?? ucfirst( str_replace( '_', ' ', $sub->status ) );
                    $period_label = $billing_periods[ $sub->billing_period ] ?? $sub->billing_period;

                    $cycle_text = (int) $sub->billing_interval === 1
                        ? $currency_symbol . number_format( (float) $sub->recurring_total, 2 ) . '/' . rtrim( $period_label, '(s)' )
                        : $currency_symbol . number_format( (float) $sub->recurring_total, 2 ) . ' every ' . (int) $sub->billing_interval . ' ' . $period_label;

                    // Get product name.
                    global $wpdb;
                    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $product_name = $wpdb->get_var( $wpdb->prepare(
                        "SELECT name FROM {$wpdb->prefix}ggmc_products WHERE id = %d",
                        $sub->product_id
                    ) );

                    // Determine available actions.
                    $actions = array();
                    if ( in_array( $sub->status, array( 'active', 'trial' ), true ) ) {
                        if ( $sub_settings['allow_pause'] ) {
                            $actions['pause'] = __( 'Pause', 'ggm-commerce' );
                        }
                        if ( $sub_settings['allow_cancel'] ) {
                            $actions['cancel'] = __( 'Cancel', 'ggm-commerce' );
                        }
                    } elseif ( 'paused' === $sub->status ) {
                        $actions['resume'] = __( 'Resume', 'ggm-commerce' );
                        if ( $sub_settings['allow_cancel'] ) {
                            $actions['cancel'] = __( 'Cancel', 'ggm-commerce' );
                        }
                    } elseif ( 'pending_cancel' === $sub->status ) {
                        // No actions — waiting for end of billing period.
                    } elseif ( in_array( $sub->status, array( 'cancelled', 'expired' ), true ) && $sub_settings['allow_reactivate'] ) {
                        $actions['reactivate'] = __( 'Reactivate', 'ggm-commerce' );
                    }
                ?>
                    <div class="ggmc-account-sub-card" data-subscription-id="<?php echo esc_attr( $sub->id ); ?>">
                        <div class="ggmc-account-sub-header">
                            <div class="ggmc-account-sub-title">
                                <span class="ggmc-account-sub-number">#<?php echo esc_html( $sub->subscription_number ); ?></span>
                                <span class="ggmc-account-sub-badge <?php echo esc_attr( $status_class ); ?>"><?php echo esc_html( $status_label ); ?></span>
                            </div>
                            <div class="ggmc-account-sub-price"><?php echo esc_html( $cycle_text ); ?></div>
                        </div>
                        <div class="ggmc-account-sub-details">
                            <?php if ( $product_name ) : ?>
                                <div class="ggmc-account-sub-detail">
                                    <span class="ggmc-account-sub-label"><?php esc_html_e( 'Product', 'ggm-commerce' ); ?>:</span>
                                    <?php echo esc_html( $product_name ); ?>
                                </div>
                            <?php endif; ?>
                            <?php if ( ! empty( $sub->start_date ) && '0000-00-00 00:00:00' !== $sub->start_date ) : ?>
                                <div class="ggmc-account-sub-detail">
                                    <span class="ggmc-account-sub-label"><?php esc_html_e( 'Started', 'ggm-commerce' ); ?>:</span>
                                    <?php echo esc_html( gmdate( 'M j, Y', strtotime( $sub->start_date ) ) ); ?>
                                </div>
                            <?php endif; ?>
                            <?php if ( ! empty( $sub->next_payment_date ) && '0000-00-00 00:00:00' !== $sub->next_payment_date && in_array( $sub->status, array( 'active', 'trial' ), true ) ) : ?>
                                <div class="ggmc-account-sub-detail">
                                    <span class="ggmc-account-sub-label"><?php esc_html_e( 'Next Payment', 'ggm-commerce' ); ?>:</span>
                                    <?php echo esc_html( gmdate( 'M j, Y', strtotime( $sub->next_payment_date ) ) ); ?>
                                </div>
                            <?php endif; ?>
                            <?php if ( 'pending_cancel' === $sub->status && ! empty( $sub->next_payment_date ) && '0000-00-00 00:00:00' !== $sub->next_payment_date ) : ?>
                                <div class="ggmc-account-sub-detail" style="color: var(--ggmc-sub-pending-cancel, #ea580c);">
                                    <span class="ggmc-account-sub-label"><?php esc_html_e( 'Cancels on', 'ggm-commerce' ); ?>:</span>
                                    <?php echo esc_html( gmdate( 'M j, Y', strtotime( $sub->next_payment_date ) ) ); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php if ( ! empty( $actions ) ) : ?>
                            <div class="ggmc-account-sub-actions">
                                <?php foreach ( $actions as $action_key => $action_label ) :
                                    $btn_class = 'cancel' === $action_key ? 'ggmc-btn-sub-danger' : 'ggmc-btn-sub-default';
                                    $confirm   = 'cancel' === $action_key ? ' data-confirm="' . esc_attr__( 'Are you sure you want to cancel this subscription?', 'ggm-commerce' ) . '"' : '';
                                ?>
                                    <button type="button"
                                        class="ggmc-account-sub-action <?php echo esc_attr( $btn_class ); ?>"
                                        data-action="<?php echo esc_attr( $action_key ); ?>"
                                        data-nonce="<?php echo esc_attr( $nonce ); ?>"
                                        <?php
                                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $confirm is built with esc_attr above
                                        echo $confirm;
                                        ?>
                                    ><?php echo esc_html( $action_label ); ?></button>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>

            <script>
            (function() {
                document.querySelectorAll('.ggmc-account-sub-action').forEach(function(btn) {
                    btn.addEventListener('click', function(e) {
                        var confirmMsg = this.getAttribute('data-confirm');
                        if (confirmMsg && !confirm(confirmMsg)) return;

                        var card  = this.closest('.ggmc-account-sub-card');
                        var subId = card.getAttribute('data-subscription-id');
                        var action = this.getAttribute('data-action');
                        var nonce  = this.getAttribute('data-nonce');
                        var originalText = this.textContent;

                        this.disabled = true;
                        this.textContent = '...';

                        var data = new FormData();
                        data.append('action', 'ggmc_customer_subscription_action');
                        data.append('subscription_id', subId);
                        data.append('subscription_action', action);
                        data.append('nonce', nonce);

                        fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
                            method: 'POST',
                            body: data,
                            credentials: 'same-origin'
                        })
                        .then(function(r) { return r.json(); })
                        .then(function(resp) {
                            if (resp.success) {
                                location.reload();
                            } else {
                                alert(resp.data && resp.data.message ? resp.data.message : '<?php echo esc_js( __( 'An error occurred.', 'ggm-commerce' ) ); ?>');
                                btn.disabled = false;
                                btn.textContent = originalText;
                            }
                        })
                        .catch(function() {
                            alert('<?php echo esc_js( __( 'An error occurred. Please try again.', 'ggm-commerce' ) ); ?>');
                            btn.disabled = false;
                            btn.textContent = originalText;
                        });
                    });
                });
            })();
            </script>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Render wishlists tab.
 *
 * @param int  $user_id
 * @param bool $is_active
 */
function ggmc_customer_account_render_wishlists_tab( $user_id, $is_active = false ) {
    $wishlist      = \GGM_Commerce_Wishlist::instance();
    $wishlists     = $wishlist->get_wishlists( true );
    $max_wishlists = $wishlist->get_max_wishlists();
    $can_create    = count( $wishlists ) < $max_wishlists;

    ?>
    <div id="wishlists" class="tab-content <?php echo $is_active ? 'active' : ''; ?>">
        <div class="wishlists-header">
            <h3><?php esc_html_e( 'My Wishlists', 'ggm-commerce' ); ?></h3>
            <?php if ( $can_create ) : ?>
                <button type="button" class="btn-create-wishlist">
                    <span class="dashicons dashicons-plus-alt2"></span>
                    <?php esc_html_e( 'New Wishlist', 'ggm-commerce' ); ?>
                </button>
            <?php endif; ?>
        </div>

        <?php if ( empty( $wishlists ) ) : ?>
            <div class="wishlists-empty">
                <p><?php esc_html_e( 'You have no wishlists yet.', 'ggm-commerce' ); ?></p>
                <?php if ( $can_create ) : ?>
                    <button type="button" class="btn-create-wishlist btn-primary">
                        <?php esc_html_e( 'Create Your First Wishlist', 'ggm-commerce' ); ?>
                    </button>
                <?php endif; ?>
            </div>
        <?php else : ?>
            <!-- Wishlists List View -->
            <div class="wishlists-list-view">
                <div class="wishlists-grid">
                    <?php foreach ( $wishlists as $wl ) :
                        $item_count = isset( $wl->item_count ) ? (int) $wl->item_count : 0;
                    ?>
                        <div class="wishlist-card" data-wishlist-id="<?php echo esc_attr( $wl->id ); ?>">
                            <div class="wishlist-card-header">
                                <h4 class="wishlist-card-name">
                                    <?php echo esc_html( $wl->name ); ?>
                                    <?php if ( (int) $wl->is_default === 1 ) : ?>
                                        <span class="badge-default"><?php esc_html_e( 'Default', 'ggm-commerce' ); ?></span>
                                    <?php endif; ?>
                                </h4>
                                <div class="wishlist-card-actions">
                                    <button type="button" class="btn-edit-wishlist" data-wishlist-id="<?php echo esc_attr( $wl->id ); ?>" title="<?php esc_attr_e( 'Rename', 'ggm-commerce' ); ?>">
                                        <span class="dashicons dashicons-edit"></span>
                                    </button>
                                    <?php if ( (int) $wl->is_default !== 1 ) : ?>
                                        <button type="button" class="btn-delete-wishlist" data-wishlist-id="<?php echo esc_attr( $wl->id ); ?>" data-wishlist-name="<?php echo esc_attr( $wl->name ); ?>" title="<?php esc_attr_e( 'Delete', 'ggm-commerce' ); ?>">
                                            <span class="dashicons dashicons-trash"></span>
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="wishlist-card-body">
                                <span class="wishlist-item-count">
                                    <?php
                                    /* translators: %d: number of items in wishlist */
                                    echo esc_html( sprintf( _n( '%d item', '%d items', $item_count, 'ggm-commerce' ), $item_count ) );
                                    ?>
                                </span>
                                <?php if ( ! empty( $wl->updated_at ) ) : ?>
                                    <span class="wishlist-updated">
                                        <?php
                                        /* translators: %s: relative time like "2 days ago" */
                                        echo esc_html( sprintf( __( 'Updated %s', 'ggm-commerce' ), human_time_diff( strtotime( $wl->updated_at ), current_time( 'timestamp' ) ) . ' ' . __( 'ago', 'ggm-commerce' ) ) );
                                        ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <div class="wishlist-card-footer">
                                <button type="button" class="btn-view-wishlist" data-wishlist-id="<?php echo esc_attr( $wl->id ); ?>">
                                    <?php esc_html_e( 'View Items', 'ggm-commerce' ); ?>
                                </button>
                                <?php if ( (int) $wl->is_default !== 1 ) : ?>
                                    <button type="button" class="btn-set-default-wishlist" data-wishlist-id="<?php echo esc_attr( $wl->id ); ?>">
                                        <?php esc_html_e( 'Set as Default', 'ggm-commerce' ); ?>
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Wishlist Detail View (hidden by default) -->
            <div class="wishlist-detail-view" style="display: none;">
                <div class="wishlist-detail-header">
                    <button type="button" class="btn-back-to-wishlists">
                        <span class="dashicons dashicons-arrow-left-alt"></span>
                        <?php esc_html_e( 'Back to Wishlists', 'ggm-commerce' ); ?>
                    </button>
                    <h4 class="wishlist-detail-title"></h4>
                </div>
                <div class="wishlist-detail-content">
                    <!-- Content loaded via AJAX -->
                </div>
            </div>
        <?php endif; ?>

        <!-- Create Wishlist Modal -->
        <div class="ggmc-modal wishlist-create-modal" style="display: none;">
            <div class="ggmc-modal-overlay"></div>
            <div class="ggmc-modal-content">
                <div class="ggmc-modal-header">
                    <h4><?php esc_html_e( 'Create New Wishlist', 'ggm-commerce' ); ?></h4>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <div class="form-group">
                        <label for="new-wishlist-name"><?php esc_html_e( 'Wishlist Name', 'ggm-commerce' ); ?></label>
                        <input type="text" id="new-wishlist-name" placeholder="<?php esc_attr_e( 'e.g., Birthday Ideas', 'ggm-commerce' ); ?>" maxlength="100">
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button type="button" class="btn-cancel"><?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?></button>
                    <button type="button" class="btn-confirm btn-primary"><?php esc_html_e( 'Create Wishlist', 'ggm-commerce' ); ?></button>
                </div>
            </div>
        </div>

        <!-- Rename Wishlist Modal -->
        <div class="ggmc-modal wishlist-rename-modal" style="display: none;">
            <div class="ggmc-modal-overlay"></div>
            <div class="ggmc-modal-content">
                <div class="ggmc-modal-header">
                    <h4><?php esc_html_e( 'Rename Wishlist', 'ggm-commerce' ); ?></h4>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <input type="hidden" id="rename-wishlist-id">
                    <div class="form-group">
                        <label for="rename-wishlist-name"><?php esc_html_e( 'Wishlist Name', 'ggm-commerce' ); ?></label>
                        <input type="text" id="rename-wishlist-name" maxlength="100">
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button type="button" class="btn-cancel"><?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?></button>
                    <button type="button" class="btn-confirm btn-primary"><?php esc_html_e( 'Save Changes', 'ggm-commerce' ); ?></button>
                </div>
            </div>
        </div>

        <!-- Delete Wishlist Modal -->
        <div class="ggmc-modal wishlist-delete-modal" style="display: none;">
            <div class="ggmc-modal-overlay"></div>
            <div class="ggmc-modal-content">
                <div class="ggmc-modal-header">
                    <h4><?php esc_html_e( 'Delete Wishlist', 'ggm-commerce' ); ?></h4>
                    <button type="button" class="ggmc-modal-close">&times;</button>
                </div>
                <div class="ggmc-modal-body">
                    <input type="hidden" id="delete-wishlist-id">
                    <p class="delete-confirm-message"></p>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="delete-move-items">
                            <?php esc_html_e( 'Move items to default wishlist before deleting', 'ggm-commerce' ); ?>
                        </label>
                    </div>
                </div>
                <div class="ggmc-modal-footer">
                    <button type="button" class="btn-cancel"><?php esc_html_e( 'Cancel', 'ggm-commerce' ); ?></button>
                    <button type="button" class="btn-confirm btn-danger"><?php esc_html_e( 'Delete Wishlist', 'ggm-commerce' ); ?></button>
                </div>
            </div>
        </div>
    </div>
    <?php
}

/**
 * Render account actions (logout link).
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 */
function ggmc_customer_account_render_account_actions( $data_handler ) {
    ?>
    <div class="account-actions">
        <a href="<?php echo esc_url( $data_handler->get_logout_url() ); ?>" class="btn-logout">
            <?php esc_html_e( 'Logout', 'ggm-commerce' ); ?>
        </a>
    </div>
    <?php
}

/**
 * Render login and register forms.
 *
 * @param GGM_Commerce_Customer_Account_Data_Handler $data_handler
 * @param array                                      $settings
 */
function ggmc_customer_account_render_login_register_forms( $data_handler, $settings ) {
    $show_login    = $settings['show_login'] === 'yes';
    $show_register = $settings['show_register'] === 'yes';
    $redirect_url  = ! empty( $settings['redirect_after_login']['url'] ) ? $settings['redirect_after_login']['url'] : get_permalink();

    ?>
    <div class="auth-forms-container">
        <?php if ( $show_login ) : ?>
            <?php ggmc_customer_account_render_login_form( $redirect_url ); ?>
        <?php endif; ?>

        <?php if ( $show_register ) : ?>
            <?php ggmc_customer_account_render_register_form( $redirect_url ); ?>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * Render login form.
 *
 * @param string $redirect_url
 */
function ggmc_customer_account_render_login_form( $redirect_url ) {
    ?>
    <div class="login-form-container">
        <h3><?php esc_html_e( 'Login', 'ggm-commerce' ); ?></h3>
        <form class="login-form" data-redirect="<?php echo esc_url( $redirect_url ); ?>">
            <div class="form-group">
                <label><?php esc_html_e( 'Username or Email', 'ggm-commerce' ); ?></label>
                <input type="text" name="username" required>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Password', 'ggm-commerce' ); ?></label>
                <input type="password" name="password" required>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" name="remember"> <?php esc_html_e( 'Remember me', 'ggm-commerce' ); ?>
                </label>
            </div>
            <button type="submit" class="btn-login"><?php esc_html_e( 'Login', 'ggm-commerce' ); ?></button>
        </form>
    </div>
    <?php
}

/**
 * Render register form.
 *
 * @param string $redirect_url
 */
function ggmc_customer_account_render_register_form( $redirect_url ) {
    $tax                        = ggm_commerce_tax();
    $show_account_type_selector = $tax->should_show_account_type_selector();
    $business_only              = $tax->get_allowed_account_types() === 'business_only';
    $tax_label                  = $tax->get_label();

    ?>
    <div class="register-form-container">
        <h3><?php esc_html_e( 'Register', 'ggm-commerce' ); ?></h3>
        <form class="register-form" data-redirect="<?php echo esc_url( $redirect_url ); ?>">
            <?php if ( $show_account_type_selector ) : ?>
            <!-- Account Type Selection -->
            <div class="form-group account-type-selector">
                <label><?php esc_html_e( 'Account Type', 'ggm-commerce' ); ?></label>
                <div class="account-type-options">
                    <label class="account-type-option">
                        <input type="radio" name="account_type" value="individual" checked>
                        <span class="option-content">
                            <strong><?php esc_html_e( 'Individual', 'ggm-commerce' ); ?></strong>
                            <small><?php esc_html_e( 'Personal shopping account', 'ggm-commerce' ); ?></small>
                        </span>
                    </label>
                    <label class="account-type-option">
                        <input type="radio" name="account_type" value="business">
                        <span class="option-content">
                            <strong><?php esc_html_e( 'Business', 'ggm-commerce' ); ?></strong>
                            <small><?php esc_html_e( 'Company account with VAT exemption', 'ggm-commerce' ); ?></small>
                        </span>
                    </label>
                </div>
            </div>
            <?php elseif ( $business_only ) : ?>
            <input type="hidden" name="account_type" value="business">
            <?php else : ?>
            <input type="hidden" name="account_type" value="individual">
            <?php endif; ?>

            <div class="form-row">
                <div class="form-group">
                    <label><?php esc_html_e( 'First Name', 'ggm-commerce' ); ?></label>
                    <input type="text" name="first_name" required>
                </div>
                <div class="form-group">
                    <label><?php esc_html_e( 'Last Name', 'ggm-commerce' ); ?></label>
                    <input type="text" name="last_name" required>
                </div>
            </div>

            <!-- Business fields (shown when business account type is selected or business_only mode) -->
            <div class="business-fields" style="<?php echo $business_only ? '' : 'display: none;'; ?>">
                <div class="form-group">
                    <label><?php esc_html_e( 'Company Name', 'ggm-commerce' ); ?> <span class="required">*</span></label>
                    <input type="text" name="company_name" <?php echo $business_only ? 'required' : ''; ?>>
                </div>
                <div class="form-group">
                    <label><?php echo esc_html( $tax_label ); ?> <?php esc_html_e( 'Number', 'ggm-commerce' ); ?></label>
                    <input type="text" name="tax_id" placeholder="<?php esc_attr_e( 'e.g., GB123456789', 'ggm-commerce' ); ?>">
                    <p class="field-description">
                        <?php
                        /* translators: %s: tax label (e.g., VAT, GST) */
                        printf( esc_html__( 'Optional: Enter your %s number to apply for tax exemption.', 'ggm-commerce' ), esc_html( $tax_label ) );
                        ?>
                    </p>
                </div>
            </div>

            <div class="form-group">
                <label><?php esc_html_e( 'Username', 'ggm-commerce' ); ?></label>
                <input type="text" name="username" required>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Email', 'ggm-commerce' ); ?></label>
                <input type="email" name="email" required>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Password', 'ggm-commerce' ); ?></label>
                <input type="password" name="password" required>
            </div>
            <div class="form-group">
                <label><?php esc_html_e( 'Confirm Password', 'ggm-commerce' ); ?></label>
                <input type="password" name="confirm_password" required>
            </div>
            <button type="submit" class="btn-register"><?php esc_html_e( 'Register', 'ggm-commerce' ); ?></button>
        </form>
    </div>
    <?php
}

/**
 * Render CSS styles — only minimal structural CSS; all visual styling via Elementor controls.
 */
function ggmc_customer_account_render_styles() {
    ?>
    <style>
        .auth-message { padding: 10px 14px; border-radius: 4px; margin-bottom: 15px; font-size: 14px; }
        .auth-error { background: #fef2f2; color: #dc2626; border: 1px solid #fecaca; }
        .auth-success { background: #f0fdf4; color: #16a34a; border: 1px solid #bbf7d0; }
    </style>
    <?php
}

/**
 * Render JavaScript.
 *
 * @param array $settings Widget settings (used for address_popup_template).
 */
function ggmc_customer_account_render_scripts( $settings ) {
    // Ensure address form render functions are loaded (for country list in native modal).
    $address_render = dirname( __DIR__ ) . '/widget-address-form/elementor-render.php';
    if ( file_exists( $address_render ) && ! function_exists( 'ggmc_address_form_get_countries_list' ) ) {
        require_once $address_render;
    }

    // Build country options HTML for the native modal.
    $country_options = '';
    if ( function_exists( 'ggmc_address_form_get_countries_list' ) ) {
        foreach ( ggmc_address_form_get_countries_list() as $code => $name ) {
            $country_options .= '<option value="' . esc_attr( $code ) . '">' . esc_html( $name ) . '</option>';
        }
    }
    ?>
    <script>
        jQuery(document).ready(function($) {
            const addressNonce = '<?php echo esc_js(wp_create_nonce('ggm_commerce_address_nonce')); ?>';
            const orderNonce = '<?php echo esc_js(wp_create_nonce('ggm_commerce_order_nonce')); ?>';
            const authNonce = '<?php echo esc_js(wp_create_nonce('ggm_commerce_auth_nonce')); ?>';
            const ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';

            // Login form submission
            $('.login-form').on('submit', function(e) {
                e.preventDefault();
                const $form = $(this);
                const $btn = $form.find('.btn-login');
                const originalText = $btn.text();

                $btn.prop('disabled', true).text('<?php echo esc_js(__('Logging in...', 'ggm-commerce')); ?>');
                $form.find('.auth-message').remove();

                $.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_login',
                        nonce: authNonce,
                        username: $form.find('input[name="username"]').val(),
                        password: $form.find('input[name="password"]').val(),
                        remember: $form.find('input[name="remember"]').is(':checked') ? 'true' : 'false'
                    },
                    success: function(response) {
                        if (response.success) {
                            const redirect = $form.data('redirect');
                            window.location.href = redirect || window.location.href;
                        } else {
                            $btn.prop('disabled', false).text(originalText);
                            $form.prepend('<div class="auth-message auth-error">' + response.data.message + '</div>');
                        }
                    },
                    error: function() {
                        $btn.prop('disabled', false).text(originalText);
                        $form.prepend('<div class="auth-message auth-error"><?php echo esc_js(__('An error occurred. Please try again.', 'ggm-commerce')); ?></div>');
                    }
                });
            });

            // Register form submission
            $('.register-form').on('submit', function(e) {
                e.preventDefault();
                const $form = $(this);
                const $btn = $form.find('.btn-register');
                const originalText = $btn.text();

                // Client-side password match check
                const password = $form.find('input[name="password"]').val();
                const confirmPassword = $form.find('input[name="confirm_password"]').val();
                if (password !== confirmPassword) {
                    $form.find('.auth-message').remove();
                    $form.prepend('<div class="auth-message auth-error"><?php echo esc_js(__('Passwords do not match.', 'ggm-commerce')); ?></div>');
                    return;
                }

                $btn.prop('disabled', true).text('<?php echo esc_js(__('Registering...', 'ggm-commerce')); ?>');
                $form.find('.auth-message').remove();

                const data = {
                    action: 'ggm_commerce_register',
                    nonce: authNonce,
                    first_name: $form.find('input[name="first_name"]').val(),
                    last_name: $form.find('input[name="last_name"]').val(),
                    username: $form.find('input[name="username"]').val(),
                    email: $form.find('input[name="email"]').val(),
                    password: password,
                    confirm_password: confirmPassword
                };

                // Include business fields if present
                const accountType = $form.find('input[name="account_type"]:checked').val() || $form.find('input[name="account_type"]').val();
                if (accountType) data.account_type = accountType;
                const companyName = $form.find('input[name="company_name"]').val();
                if (companyName) data.company_name = companyName;
                const taxId = $form.find('input[name="tax_id"]').val();
                if (taxId) data.tax_id = taxId;

                $.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        if (response.success) {
                            const redirect = $form.data('redirect');
                            window.location.href = redirect || window.location.href;
                        } else {
                            $btn.prop('disabled', false).text(originalText);
                            $form.prepend('<div class="auth-message auth-error">' + response.data.message + '</div>');
                        }
                    },
                    error: function() {
                        $btn.prop('disabled', false).text(originalText);
                        $form.prepend('<div class="auth-message auth-error"><?php echo esc_js(__('An error occurred. Please try again.', 'ggm-commerce')); ?></div>');
                    }
                });
            });

            // Account type toggle for registration form
            $('input[name="account_type"]').on('change', function() {
                const isBusinessSelected = $(this).val() === 'business';
                const businessFields = $(this).closest('form').find('.business-fields');
                const companyInput = businessFields.find('input[name="company_name"]');

                if (isBusinessSelected) {
                    businessFields.slideDown(200);
                    companyInput.prop('required', true);
                } else {
                    businessFields.slideUp(200);
                    companyInput.prop('required', false);
                }
            });

            // Tab functionality
            function activateTab(tabId) {
                $('.tab-link').removeClass('active');
                $('.tab-content').removeClass('active');

                $('.tab-link[data-tab="' + tabId + '"]').addClass('active');
                $('#' + tabId).addClass('active');
            }

            $('.tab-link').click(function() {
                var tabId = $(this).data('tab');
                activateTab(tabId);
                // Update URL hash without scrolling
                history.replaceState(null, null, '#' + tabId);
            });

            // Restore tab from URL hash on page load
            if (window.location.hash) {
                var hashTab = window.location.hash.substring(1);
                if ($('#' + hashTab).length && $('.tab-link[data-tab="' + hashTab + '"]').length) {
                    activateTab(hashTab);
                }
            }

            // Helper to reload page and return to a specific tab
            function reloadToTab(tabId) {
                window.location.href = window.location.pathname + window.location.search + '#' + tabId;
                window.location.reload();
            }

            // ===== ORDER VIEW FUNCTIONALITY =====

            // View Order button click
            $(document).on('click', '.btn-view-order', function(e) {
                e.preventDefault();
                const orderId = $(this).data('order-id');
                const $ordersTab = $('#orders');
                const $listView = $ordersTab.find('.orders-list-view');
                const $detailView = $ordersTab.find('.order-detail-view');
                const $detailContent = $ordersTab.find('.order-detail-content');

                // Show loading state
                $detailContent.html('<div class="order-loading"><span class="spinner"></span> <?php echo esc_js(__('Loading order details...', 'ggm-commerce')); ?></div>');

                // Switch views
                $listView.hide();
                $detailView.show();

                // Fetch order details via AJAX
                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_get_order_details_html',
                        order_id: orderId,
                        nonce: orderNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $detailContent.html(response.data.html);
                        } else {
                            $detailContent.html('<div class="order-error">' + (response.data.message || '<?php echo esc_js(__('Failed to load order details.', 'ggm-commerce')); ?>') + '</div>');
                        }
                    },
                    error: function() {
                        $detailContent.html('<div class="order-error"><?php echo esc_js(__('An error occurred while loading order details.', 'ggm-commerce')); ?></div>');
                    }
                });
            });

            // Back to Orders button click
            $(document).on('click', '.btn-back-to-orders', function(e) {
                e.preventDefault();
                const $ordersTab = $('#orders');
                const $listView = $ordersTab.find('.orders-list-view');
                const $detailView = $ordersTab.find('.order-detail-view');

                $detailView.hide();
                $listView.show();
            });

            // Print Invoice button click - opens centralized invoice template
            $(document).on('click', '.btn-print-invoice', function(e) {
                e.preventDefault();
                const $detailWrapper = $('.order-detail-wrapper');
                const orderId = $detailWrapper.data('order-id');

                if (!orderId) {
                    alert('<?php echo esc_js(__('Order not found', 'ggm-commerce')); ?>');
                    return;
                }

                // Request invoice URL from server (includes secure nonce)
                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_get_invoice_url',
                        order_id: orderId,
                        nonce: orderNonce
                    },
                    success: function(response) {
                        if (response.success && response.data.url) {
                            window.open(response.data.url, '_blank');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to generate invoice', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred', 'ggm-commerce')); ?>');
                    }
                });
            });

            // Popup template ID (from widget settings or default)
            const popupTemplateId = '<?php echo esc_js( ! empty( $settings['address_popup_template'] ) ? $settings['address_popup_template'] : get_option('ggm_commerce_address_popup_id', '') ); ?>';
            const useElementorPopup = <?php echo ( class_exists( '\ElementorPro\Plugin' ) && ! empty( get_option( 'ggm_commerce_address_popup_id' ) ) ) ? 'true' : 'false'; ?>;

            // Store form data to populate after popup opens
            let pendingFormData = null;

            // Popup functions — Elementor or native modal
            function openPopup(formData) {
                pendingFormData = formData;

                if (useElementorPopup && popupTemplateId) {
                    // Elementor popup path
                    const actionSettings = { id: popupTemplateId, toggle: false };
                    const actionHash = '#elementor-action:action=popup:open&settings=' + btoa(JSON.stringify(actionSettings));
                    const $link = $('<a>', { href: actionHash, style: 'display:none' }).appendTo('body');
                    $link[0].click();
                    setTimeout(() => $link.remove(), 100);
                } else {
                    // Native modal fallback
                    let $modal = $('#ggmc-address-modal-overlay');
                    if (!$modal.length) {
                        createNativeAddressModal();
                        $modal = $('#ggmc-address-modal-overlay');
                    }
                    $modal.addClass('active');
                    $('body').addClass('ggmc-modal-open');
                    if (pendingFormData) {
                        populateForm(pendingFormData);
                        pendingFormData = null;
                    }
                }
            }

            // Create native address modal (only when Elementor is not available)
            function createNativeAddressModal() {
                const html = '<div id="ggmc-address-modal-overlay" style="position:fixed;inset:0;z-index:100000;background:rgba(0,0,0,0.6);display:none;align-items:center;justify-content:center;">' +
                    '<div style="background:#fff;border-radius:8px;max-width:600px;width:90%;max-height:90vh;overflow-y:auto;padding:30px;position:relative;">' +
                        '<button id="ggmc-address-modal-close" style="position:absolute;top:12px;right:12px;background:none;border:none;font-size:24px;cursor:pointer;color:#666;line-height:1;">&times;</button>' +
                        '<h3 id="modal-title" style="margin:0 0 10px 0;">Edit Address</h3>' +
                        '<p id="address-type-display" style="margin:0 0 20px 0;color:#666;font-size:14px;"></p>' +
                        '<input type="hidden" id="address_id"><input type="hidden" id="address_type">' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Address Label</label><input type="text" id="address_label" placeholder="e.g., Home, Office" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div>' +
                        '<div style="display:flex;gap:12px;margin-bottom:16px;"><div style="flex:1;"><label style="display:block;margin-bottom:6px;font-weight:500;">First Name</label><input type="text" id="first_name" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div><div style="flex:1;"><label style="display:block;margin-bottom:6px;font-weight:500;">Last Name</label><input type="text" id="last_name" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div></div>' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Company</label><input type="text" id="company" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div>' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Address Line 1 <span style="color:red;">*</span></label><input type="text" id="address_1" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div>' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Address Line 2</label><input type="text" id="address_2" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div>' +
                        '<div style="display:flex;gap:12px;margin-bottom:16px;"><div style="flex:1;"><label style="display:block;margin-bottom:6px;font-weight:500;">City <span style="color:red;">*</span></label><input type="text" id="city" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div><div style="flex:1;"><label style="display:block;margin-bottom:6px;font-weight:500;">State <span style="color:red;">*</span></label><input type="text" id="state" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div><div style="flex:1;"><label style="display:block;margin-bottom:6px;font-weight:500;">Postcode <span style="color:red;">*</span></label><input type="text" id="postcode" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div></div>' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Country <span style="color:red;">*</span></label><select id="country" required style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"><option value="">Select Country</option><?php echo $country_options; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- built with esc_attr/esc_html above ?></select></div>' +
                        '<div style="margin-bottom:16px;"><label style="display:block;margin-bottom:6px;font-weight:500;">Phone</label><input type="tel" id="phone" style="width:100%;padding:10px;border:1px solid #ddd;border-radius:4px;box-sizing:border-box;"></div>' +
                        '<div style="margin-bottom:20px;"><label style="display:flex;align-items:center;gap:8px;"><input type="checkbox" id="is_default"> Set as default address</label></div>' +
                        '<div style="display:flex;gap:10px;justify-content:flex-end;"><button type="button" id="btn-cancel-address" style="padding:12px 24px;background:#f0f0f0;color:#333;border:none;border-radius:4px;cursor:pointer;font-weight:500;">Cancel</button><button type="button" id="btn-save-address" style="padding:12px 24px;background:#2563eb;color:#fff;border:none;border-radius:4px;cursor:pointer;font-weight:500;">Save Address</button></div>' +
                    '</div></div>';
                $('body').append(html);

                // Show on creation (flex for centering)
                const $modal = $('#ggmc-address-modal-overlay');
                $modal.css('display', 'flex');

                // Close handlers
                $('#ggmc-address-modal-close').on('click', closePopup);
                $modal.on('click', function(e) {
                    if ($(e.target).is($modal)) closePopup();
                });
            }

            // Listen for Elementor popup show event (only when using Elementor)
            if (useElementorPopup) {
                $(document).on('elementor/popup/show', function(event, id, instance) {
                    if (id == popupTemplateId && pendingFormData) {
                        populateForm(pendingFormData);
                        pendingFormData = null;
                    }
                });
            }

            // Function to populate form fields
            function populateForm(data) {
                $('#address_id').val(data.address_id || '');
                $('#address_type').val(data.address_type || '');
                $('#address_label').val(data.address_label || '');
                $('#first_name').val(data.first_name || '');
                $('#last_name').val(data.last_name || '');
                $('#company').val(data.company || '');
                $('#address_1').val(data.address_1 || '');
                $('#address_2').val(data.address_2 || '');
                $('#city').val(data.city || '');
                $('#state').val(data.state || '');
                $('#postcode').val(data.postcode || '');
                $('#country').val(data.country || '');
                $('#phone').val(data.phone || '');
                $('#is_default').prop('checked', data.is_default || false);

                // Update title and type display
                if (data.title) {
                    $('#modal-title').text(data.title);
                }
                if (data.type_display) {
                    $('#address-type-display').text(data.type_display);
                }
            }

            function closePopup() {
                if (useElementorPopup && popupTemplateId) {
                    // Elementor path
                    const actionHash = '#elementor-action:action=popup:close&settings=' + btoa(JSON.stringify({id: popupTemplateId}));
                    const $link = $('<a>', { href: actionHash, style: 'display:none' }).appendTo('body');
                    $link[0].click();
                    setTimeout(() => $link.remove(), 100);
                } else {
                    // Native modal path
                    const $modal = $('#ggmc-address-modal-overlay');
                    $modal.removeClass('active').css('display', 'none');
                    $('body').removeClass('ggmc-modal-open');
                }

                // Clear form after a short delay
                setTimeout(function() {
                    $('#address_id').val('');
                    $('#address_type').val('');
                    $('#address_label').val('');
                    $('#first_name').val('');
                    $('#last_name').val('');
                    $('#company').val('');
                    $('#address_1').val('');
                    $('#address_2').val('');
                    $('#city').val('');
                    $('#state').val('');
                    $('#postcode').val('');
                    $('#country').val('');
                    $('#phone').val('');
                    $('#is_default').prop('checked', false);
                }, 200);
            }

            // Handle cancel button in popup
            $(document).on('click', '#btn-cancel-address', function(e) {
                e.preventDefault();
                closePopup();
            });

            // Add new address
            $('.btn-add-address').on('click', function() {
                const addressType = $(this).data('type');
                const addressTypeLabel = addressType.charAt(0).toUpperCase() + addressType.slice(1);

                // Prepare form data for new address
                const formData = {
                    address_id: '',
                    address_type: addressType,
                    address_label: '',
                    first_name: '',
                    last_name: '',
                    company: '',
                    address_1: '',
                    address_2: '',
                    city: '',
                    state: '',
                    postcode: '',
                    country: '',
                    phone: '',
                    is_default: false,
                    title: 'Add New ' + addressTypeLabel + ' Address',
                    type_display: 'Adding a new ' + addressType + ' address'
                };

                // Open popup with form data
                openPopup(formData);
            });

            // Edit address
            $(document).on('click', '.btn-edit-address', function() {
                const addressId = $(this).data('address-id');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_get_address',
                        address_id: addressId,
                        nonce: addressNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            const address = response.data.address;
                            const addressTypeLabel = address.address_type.charAt(0).toUpperCase() + address.address_type.slice(1);

                            // Prepare form data from loaded address
                            const formData = {
                                address_id: address.id,
                                address_type: address.address_type,
                                address_label: address.address_label || '',
                                first_name: address.first_name || '',
                                last_name: address.last_name || '',
                                company: address.company || '',
                                address_1: address.address_1 || '',
                                address_2: address.address_2 || '',
                                city: address.city || '',
                                state: address.state || '',
                                postcode: address.postcode || '',
                                country: address.country || '',
                                phone: address.phone || '',
                                is_default: address.is_default == 1,
                                title: 'Edit ' + addressTypeLabel + ' Address',
                                type_display: 'Editing ' + address.address_type + ' address' + (address.address_label ? ': ' + address.address_label : '')
                            };

                            // Open popup with form data
                            openPopup(formData);
                        } else {
                            alert(response.data.message || 'Failed to load address');
                        }
                    },
                    error: function() {
                        alert('An error occurred while loading the address');
                    }
                });
            });

            // Save address
            $(document).on('click', '#btn-save-address', function(e) {
                e.preventDefault();

                const formData = {
                    action: 'ggm_commerce_save_address',
                    nonce: addressNonce,
                    address_id: $('#address_id').val(),
                    address_type: $('#address_type').val(),
                    address_label: $('#address_label').val(),
                    first_name: $('#first_name').val(),
                    last_name: $('#last_name').val(),
                    company: $('#company').val(),
                    address_1: $('#address_1').val(),
                    address_2: $('#address_2').val(),
                    city: $('#city').val(),
                    state: $('#state').val(),
                    postcode: $('#postcode').val(),
                    country: $('#country').val(),
                    phone: $('#phone').val(),
                    is_default: $('#is_default').is(':checked') ? 'true' : 'false'
                };

                // Basic validation (state is optional for EU countries)
                if (!formData.address_1 || !formData.city || !formData.postcode || !formData.country) {
                    alert('Please fill in all required fields (Address, City, Postcode, Country)');
                    return;
                }

                $(this).prop('disabled', true).text('Saving...');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            closePopup();
                            reloadToTab('addresses');
                        } else {
                            alert(response.data.message || 'Failed to save address');
                        }
                    },
                    error: function() {
                        alert('An error occurred while saving the address');
                    },
                    complete: function() {
                        $('#btn-save-address').prop('disabled', false).text('Save Address');
                    }
                });
            });

            // Delete address
            $(document).on('click', '.btn-delete-address', function() {
                if (!confirm('Are you sure you want to delete this address?')) {
                    return;
                }

                const addressId = $(this).data('address-id');
                const button = $(this);

                button.prop('disabled', true);

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_delete_address',
                        address_id: addressId,
                        nonce: addressNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            reloadToTab('addresses');
                        } else {
                            alert(response.data.message || 'Failed to delete address');
                            button.prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('An error occurred while deleting the address');
                        button.prop('disabled', false);
                    }
                });
            });

            // Set default address
            $(document).on('click', '.btn-set-default', function() {
                const addressId = $(this).data('address-id');
                const button = $(this);

                button.prop('disabled', true).text('Setting...');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_set_default_address',
                        address_id: addressId,
                        nonce: addressNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message);
                            reloadToTab('addresses');
                        } else {
                            alert(response.data.message || 'Failed to set default address');
                            button.prop('disabled', false).text('Set as Default');
                        }
                    },
                    error: function() {
                        alert('An error occurred while updating the default address');
                        button.prop('disabled', false).text('Set as Default');
                    }
                });
            });

            // Business Settings - Update Business Details
            $('.business-form').on('submit', function(e) {
                e.preventDefault();

                const form = $(this);
                const button = form.find('.btn-update-business');
                const originalText = button.text();

                button.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_update_business',
                        nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_business_nonce')); ?>',
                        company_name: form.find('input[name="company_name"]').val(),
                        tax_id: form.find('input[name="tax_id"]').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message || '<?php echo esc_js(__('Business details saved successfully.', 'ggm-commerce')); ?>');
                            reloadToTab('business');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to save business details.', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred while saving business details.', 'ggm-commerce')); ?>');
                    },
                    complete: function() {
                        button.prop('disabled', false).text(originalText);
                    }
                });
            });

            // Business Settings - Update Price Display Preference
            $('.price-preference-form').on('submit', function(e) {
                e.preventDefault();

                const form = $(this);
                const button = form.find('.btn-update-preference');
                const originalText = button.text();

                button.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_update_price_preference',
                        nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_price_preference_nonce')); ?>',
                        price_display: form.find('input[name="price_display"]:checked').val()
                    },
                    success: function(response) {
                        if (response.success) {
                            alert(response.data.message || '<?php echo esc_js(__('Price preference saved successfully.', 'ggm-commerce')); ?>');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to save price preference.', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred while saving price preference.', 'ggm-commerce')); ?>');
                    },
                    complete: function() {
                        button.prop('disabled', false).text(originalText);
                    }
                });
            });

            // ===== WISHLIST MANAGEMENT =====
            const wishlistNonce = '<?php echo esc_js(wp_create_nonce('ggm_commerce_nonce')); ?>';

            // Modal helpers
            function openModal($modal) {
                $modal.show();
                $('body').css('overflow', 'hidden');
            }

            function closeModal($modal) {
                $modal.hide();
                $('body').css('overflow', '');
            }

            // Close modals on overlay click or close button
            $(document).on('click', '.ggmc-modal-overlay, .ggmc-modal-close, .ggmc-modal .btn-cancel', function() {
                closeModal($(this).closest('.ggmc-modal'));
            });

            // Close modal on Escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    $('.ggmc-modal:visible').each(function() {
                        closeModal($(this));
                    });
                }
            });

            // Create Wishlist
            $(document).on('click', '.btn-create-wishlist', function() {
                $('#new-wishlist-name').val('');
                openModal($('.wishlist-create-modal'));
                setTimeout(() => $('#new-wishlist-name').focus(), 100);
            });

            $(document).on('click', '.wishlist-create-modal .btn-confirm', function() {
                const name = $('#new-wishlist-name').val().trim();
                if (!name) {
                    alert('<?php echo esc_js(__('Please enter a wishlist name.', 'ggm-commerce')); ?>');
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).text('<?php echo esc_js(__('Creating...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggmc_wishlist_create',
                        name: name,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            reloadToTab('wishlists');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to create wishlist.', 'ggm-commerce')); ?>');
                            $btn.prop('disabled', false).text('<?php echo esc_js(__('Create Wishlist', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Create Wishlist', 'ggm-commerce')); ?>');
                    }
                });
            });

            // Rename Wishlist
            $(document).on('click', '.btn-edit-wishlist', function() {
                const wishlistId = $(this).data('wishlist-id');
                const currentName = $(this).closest('.wishlist-card').find('.wishlist-card-name').text().trim().replace(/Default$/, '').trim();

                $('#rename-wishlist-id').val(wishlistId);
                $('#rename-wishlist-name').val(currentName);
                openModal($('.wishlist-rename-modal'));
                setTimeout(() => $('#rename-wishlist-name').focus().select(), 100);
            });

            $(document).on('click', '.wishlist-rename-modal .btn-confirm', function() {
                const wishlistId = $('#rename-wishlist-id').val();
                const name = $('#rename-wishlist-name').val().trim();

                if (!name) {
                    alert('<?php echo esc_js(__('Please enter a wishlist name.', 'ggm-commerce')); ?>');
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true).text('<?php echo esc_js(__('Saving...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggmc_wishlist_update',
                        wishlist_id: wishlistId,
                        name: name,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            reloadToTab('wishlists');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to rename wishlist.', 'ggm-commerce')); ?>');
                            $btn.prop('disabled', false).text('<?php echo esc_js(__('Save Changes', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Save Changes', 'ggm-commerce')); ?>');
                    }
                });
            });

            // Delete Wishlist
            $(document).on('click', '.btn-delete-wishlist', function() {
                const wishlistId = $(this).data('wishlist-id');
                const wishlistName = $(this).data('wishlist-name');

                $('#delete-wishlist-id').val(wishlistId);
                $('#delete-move-items').prop('checked', true);
                $('.delete-confirm-message').html(
                    '<?php echo esc_js(__('Are you sure you want to delete', 'ggm-commerce')); ?> <strong>' +
                    $('<div>').text(wishlistName).html() +
                    '</strong>?'
                );
                openModal($('.wishlist-delete-modal'));
            });

            $(document).on('click', '.wishlist-delete-modal .btn-confirm', function() {
                const wishlistId = $('#delete-wishlist-id').val();
                const moveItems = $('#delete-move-items').is(':checked');

                const $btn = $(this);
                $btn.prop('disabled', true).text('<?php echo esc_js(__('Deleting...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggmc_wishlist_delete',
                        wishlist_id: wishlistId,
                        move_to_default: moveItems ? 1 : 0,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            reloadToTab('wishlists');
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to delete wishlist.', 'ggm-commerce')); ?>');
                            $btn.prop('disabled', false).text('<?php echo esc_js(__('Delete Wishlist', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Delete Wishlist', 'ggm-commerce')); ?>');
                    }
                });
            });

            // Set Default Wishlist
            $(document).on('click', '.btn-set-default-wishlist', function() {
                const wishlistId = $(this).data('wishlist-id');
                const $btn = $(this);

                $btn.prop('disabled', true).text('<?php echo esc_js(__('Setting...', 'ggm-commerce')); ?>');

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'ggmc_wishlist_set_default',
                        wishlist_id: wishlistId,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response && response.success) {
                            reloadToTab('wishlists');
                        } else {
                            var msg = (response && response.data && response.data.message) ? response.data.message : '<?php echo esc_js(__('Failed to set default wishlist.', 'ggm-commerce')); ?>';
                            alert(msg);
                            $btn.prop('disabled', false).text('<?php echo esc_js(__('Set as Default', 'ggm-commerce')); ?>');
                        }
                    },
                    error: function(xhr) {
                        console.error('Set default wishlist AJAX error:', xhr.status, xhr.responseText);
                        alert('<?php echo esc_js(__('An error occurred. Please refresh the page and try again.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false).text('<?php echo esc_js(__('Set as Default', 'ggm-commerce')); ?>');
                    }
                });
            });

            // View Wishlist Items
            $(document).on('click', '.btn-view-wishlist', function() {
                const wishlistId = $(this).data('wishlist-id');
                const wishlistName = $(this).closest('.wishlist-card').find('.wishlist-card-name').contents().filter(function() {
                    return this.nodeType === 3;
                }).text().trim();

                const $listView = $('.wishlists-list-view');
                const $detailView = $('.wishlist-detail-view');
                const $detailContent = $detailView.find('.wishlist-detail-content');

                // Update title
                $detailView.find('.wishlist-detail-title').text(wishlistName);
                $detailView.attr('data-wishlist-id', wishlistId);

                // Show loading
                $detailContent.html('<div class="wishlist-loading"><span class="spinner"></span> <?php echo esc_js(__('Loading items...', 'ggm-commerce')); ?></div>');

                // Switch views
                $listView.hide();
                $detailView.show();

                // Load items via AJAX
                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggmc_wishlist_get_items_html',
                        wishlist_id: wishlistId,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            $detailContent.html(response.data.html);
                        } else {
                            $detailContent.html('<div class="wishlist-error">' + (response.data.message || '<?php echo esc_js(__('Failed to load wishlist items.', 'ggm-commerce')); ?>') + '</div>');
                        }
                    },
                    error: function() {
                        $detailContent.html('<div class="wishlist-error"><?php echo esc_js(__('An error occurred while loading wishlist items.', 'ggm-commerce')); ?></div>');
                    }
                });
            });

            // Back to Wishlists
            $(document).on('click', '.btn-back-to-wishlists', function() {
                $('.wishlist-detail-view').hide();
                $('.wishlists-list-view').show();
            });

            // Remove item from wishlist
            $(document).on('click', '.btn-remove-from-wishlist', function() {
                const $btn = $(this);
                const productId = $btn.data('product-id');
                const wishlistId = $btn.data('wishlist-id') || $('.wishlist-detail-view').data('wishlist-id');

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

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggmc_wishlist_remove',
                        product_id: productId,
                        wishlist_id: wishlistId,
                        nonce: wishlistNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            // Remove the item row (table layout) or card (grid layout)
                            const $item = $btn.closest('.ggmc-wishlist-item, .wishlist-item-card');
                            $item.fadeOut(300, function() {
                                $(this).remove();
                                // Check if empty - look for remaining items
                                const $remainingItems = $('.ggmc-wishlist-item, .wishlist-item-card');
                                if ($remainingItems.length === 0) {
                                    $('.wishlist-detail-content').html(
                                        '<div class="ggmc-wishlist-empty">' +
                                        '<i class="eicon-heart-o"></i>' +
                                        '<p><?php echo esc_js(__('This wishlist is empty.', 'ggm-commerce')); ?></p>' +
                                        '<p class="ggmc-wishlist-empty-hint"><?php echo esc_js(__('Browse products and add items to this wishlist.', 'ggm-commerce')); ?></p>' +
                                        '</div>'
                                    );
                                }
                            });
                        } else {
                            alert(response.data.message || '<?php echo esc_js(__('Failed to remove item.', 'ggm-commerce')); ?>');
                            $btn.prop('disabled', false);
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false);
                    }
                });
            });

            // Add to cart from wishlist
            $(document).on('click', '.btn-add-to-cart-from-wishlist', function() {
                const $btn = $(this);
                const productId = $btn.data('product-id');
                const $btnSpan = $btn.find('span');
                const originalHtml = $btn.html();

                $btn.prop('disabled', true);
                if ($btnSpan.length) {
                    $btnSpan.text('<?php echo esc_js(__('Adding...', 'ggm-commerce')); ?>');
                } else {
                    $btn.text('<?php echo esc_js(__('Adding...', 'ggm-commerce')); ?>');
                }

                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    type: 'POST',
                    data: {
                        action: 'ggm_commerce_add_to_cart',
                        product_id: productId,
                        quantity: 1,
                        nonce: '<?php echo esc_js(wp_create_nonce('ggm_commerce_nonce')); ?>'
                    },
                    success: function(response) {
                        if (response && response.success) {
                            // Show success state
                            if ($btnSpan.length) {
                                $btnSpan.text('<?php echo esc_js(__('Added!', 'ggm-commerce')); ?>');
                            } else {
                                $btn.text('<?php echo esc_js(__('Added!', 'ggm-commerce')); ?>');
                            }
                            // Trigger cart update event
                            $(document).trigger('ggmc_cart_updated', [response.data]);
                            // Reset after delay
                            setTimeout(function() {
                                $btn.prop('disabled', false).html(originalHtml);
                            }, 2000);
                        } else {
                            const msg = (response && response.data && response.data.message)
                                ? response.data.message
                                : '<?php echo esc_js(__('Failed to add to cart.', 'ggm-commerce')); ?>';
                            alert(msg);
                            $btn.prop('disabled', false).html(originalHtml);
                        }
                    },
                    error: function() {
                        alert('<?php echo esc_js(__('An error occurred.', 'ggm-commerce')); ?>');
                        $btn.prop('disabled', false).html(originalHtml);
                    }
                });
            });
        });
    </script>
    <?php
}
