<?php
/**
 * Template: account/dashboard.php
 *
 * My Account entry point. Login/register for guests, dashboard for logged-in users.
 *
 * Available variables (from StorefrontModule::build_template_data):
 *   $section, $logged_in, $customer, $orders, $addresses, $countries,
 *   $total_orders, $total_spent
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$base    = home_url( '/my-account/' );
$section = $section ?? 'dashboard';
$symbol  = \TitanCart\Services\CurrencyService::primary_symbol();

// ── Login POST handler ──────────────────────────────────────────────────
$tc_login_ok = ! empty( $_POST['tc_login_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tc_login_nonce'] ) ), 'tc_login' ); // WP.org R1 🅱2: sanitize nonce input.
if ( $tc_login_ok && ! \TitanCart\Extensions\RecaptchaExtension::passes( 'login' ) ) {
    $login_error = __( 'reCAPTCHA verification failed. Please try again.', 'titancart-lite' );
    $tc_login_ok = false;
}
if ( $tc_login_ok ) {
    $creds = [
        'user_login'    => sanitize_text_field( wp_unslash( $_POST['tc_email'] ?? '' ) ),
        'user_password' => wp_unslash( $_POST['tc_password'] ?? '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be sanitized (would corrupt legitimate characters); consumed only by wp_signon().
        'remember'      => ! empty( $_POST['tc_remember'] ),
    ];
    $login = wp_signon( $creds, is_ssl() );
    if ( ! is_wp_error( $login ) ) {
        // Check if customer account is disabled (awaiting admin activation).
        global $wpdb;
        $tc_p   = $wpdb->prefix . TITANCART_TABLE_PREFIX;
        $cust_status = $wpdb->get_var( $wpdb->prepare(
            "SELECT status FROM {$tc_p}customers WHERE wp_user_id = %d AND deleted_at IS NULL LIMIT 1",
            $login->ID
        ) );
        if ( $cust_status === 'disabled' ) {
            wp_logout();
            $login_error = __( 'Your account is pending approval. An administrator will activate it shortly.', 'titancart-lite' );
        } else {
            wp_safe_redirect( $base );
            exit;
        }
    } else {
        $login_error = $login->get_error_message();
    }
}

// ── Register POST handler ───────────────────────────────────────────────
//
// Two distinct nonce paths to defend against the order-received account-squat
// vector (P1 #4 from security scan):
//
//   1. Bound path — order-received form. The form generates its nonce with
//      action `tc_register_for_<sha256(billing_email)>`. The handler computes
//      the hash of the SUBMITTED email and verifies the nonce against that
//      bound action. If an attacker substitutes a different email after the
//      page renders, the recomputed hash won't match the nonce and verification
//      fails — they can no longer auto-prefill someone else's email and squat
//      the account.
//
//   2. Generic path — /my-account/ register form. User types their own email,
//      so the form uses the legacy `tc_register` action. This is the standard
//      open-registration flow and behaves as before. (Hardening this further
//      requires sending a confirmation email — out of scope for this triage,
//      tracked as a follow-up.)
$tc_reg_token_post = isset( $_POST['tc_reg_email_token'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['tc_reg_email_token'] ) ) : ''; // WP.org R1 🅱2: sanitized (sha256 hex — sanitize_text_field is shape-preserving; length+hash_equals gates below).
$tc_reg_email_post = sanitize_email( wp_unslash( $_POST['tc_reg_email'] ?? '' ) );

$tc_reg_nonce_ok = false;
if ( ! empty( $_POST['tc_register_nonce'] ) ) {
    if ( $tc_reg_token_post !== '' ) {
        // Bound path — recompute the hash and verify both that the supplied
        // token matches the submitted email AND that the nonce was issued for
        // that exact bound action. Both gates must pass.
        $tc_reg_expected_token = hash( 'sha256', strtolower( trim( $tc_reg_email_post ) ) );
        $tc_reg_token_match    = ( strlen( $tc_reg_token_post ) === 64
                                  && hash_equals( $tc_reg_expected_token, $tc_reg_token_post ) );
        if ( $tc_reg_token_match
             && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tc_register_nonce'] ) ), 'tc_register_for_' . $tc_reg_expected_token ) // WP.org R1 🅱2: sanitize nonce input.
        ) {
            $tc_reg_nonce_ok = true;
        }
    } else {
        // Generic path — legacy open-registration flow.
        if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['tc_register_nonce'] ) ), 'tc_register' ) ) { // WP.org R1 🅱2: sanitize nonce input.
            $tc_reg_nonce_ok = true;
        }
    }
}

if ( $tc_reg_nonce_ok && ! \TitanCart\Extensions\RecaptchaExtension::passes( 'register' ) ) {
    $register_error = __( 'reCAPTCHA verification failed. Please try again.', 'titancart-lite' );
    $tc_reg_nonce_ok = false;
}

if ( $tc_reg_nonce_ok ) {
    $reg_data = [
        'email'      => $tc_reg_email_post,
        'password'   => wp_unslash( $_POST['tc_reg_password'] ?? '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be sanitized; hashed by AccountManager::register().
        'first_name' => sanitize_text_field( wp_unslash( $_POST['tc_reg_first'] ?? '' ) ),
        'last_name'  => sanitize_text_field( wp_unslash( $_POST['tc_reg_last'] ?? '' ) ),
        'phone'      => sanitize_text_field( wp_unslash( $_POST['tc_reg_phone'] ?? '' ) ),
        'company'    => sanitize_text_field( wp_unslash( $_POST['tc_reg_company'] ?? '' ) ),
        'usergroup_id' => absint( $_POST['tc_reg_group'] ?? 0 ),
        // Custom (non-system) contact fields — extracted from any tc_cf_<id>
        // inputs admin has wired via the Customer Fields page (S127.C-1).
        'custom_fields' => ( new \TitanCart\Modules\Accounts\CustomerFieldsManager() )->extract_submitted( $_POST ),
    ];
    if ( wp_unslash( $_POST['tc_reg_password'] ?? '' ) !== wp_unslash( $_POST['tc_reg_confirm'] ?? '' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- equality check only; passwords must not be sanitized.
        $register_error = __( 'Passwords do not match.', 'titancart-lite' );
    } else {
        $mgr    = new \TitanCart\Modules\Accounts\AccountManager();
        $result = $mgr->register( $reg_data );
        if ( is_wp_error( $result ) ) {
            $register_error = $result->get_error_message();
        } else {
            // Newsletter opt-in (Phase 5 block B, S241) — enrol the new account into
            // any "Show on registration" lists they ticked. Validated against active
            // + show_on_registration lists (anti-spoof), source 'registration', double
            // opt-in still applies. Best-effort: wrapped so a subscribe hiccup can never
            // block account creation or the redirect. Fires before BOTH the
            // admin-activate and the auto-login/redirect branches below.
            // class_exists: Lite strips the Newsletters module (R1 §🅰) — the
            // opt-in checkboxes don't render there either; whole block skips.
            if (
                class_exists( \TitanCart\Modules\Newsletters\NewsletterManager::class )
                && \TitanCart\REST\Extensions\ExtensionsController::is_active( 'newsletters' )
                && \TitanCart\Services\SettingsService::bool( 'newsletters', 'show_subscribe_registration', true )
            ) {
                $tc_reg_optin = array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['newsletter_optin'] ?? [] ) ); // WP.org R1 🅱2: unslash+sanitize; intval-mapped below.
                if ( ! is_array( $tc_reg_optin ) ) {
                    $tc_reg_optin = [ $tc_reg_optin ];
                }
                $tc_reg_optin = array_values( array_unique( array_filter( array_map( 'intval', $tc_reg_optin ) ) ) );
                if ( ! empty( $tc_reg_optin ) ) {
                    try {
                        global $wpdb;
                        $tc_reg_eligible = array_map( 'intval', (array) $wpdb->get_col(
                            "SELECT id FROM {$wpdb->prefix}tc_subscriber_lists
                             WHERE status = 'active' AND show_on_registration = 1"
                        ) );
                        $tc_reg_target = array_values( array_intersect( $tc_reg_optin, $tc_reg_eligible ) );
                        if ( ! empty( $tc_reg_target ) ) {
                            ( new \TitanCart\Modules\Newsletters\NewsletterManager() )->create_subscriber( [
                                'email'      => $tc_reg_email_post,
                                'first_name' => sanitize_text_field( wp_unslash( $_POST['tc_reg_first'] ?? '' ) ),
                                'last_name'  => sanitize_text_field( wp_unslash( $_POST['tc_reg_last'] ?? '' ) ),
                                'status'     => 'active',
                                'source'     => 'registration',
                                'ip_address' => titancart_client_ip(), // WP.org R1 🅱2: validated capture.
                                'list_ids'   => $tc_reg_target,
                            ] );
                        }
                    } catch ( \Throwable $e ) {
                        \TitanCart\Core\LogService::warning( 'newsletters', 'registration_optin', 'Registration newsletter opt-in failed: ' . $e->getMessage() );
                    }
                }
            }

            $admin_activate = \TitanCart\Services\SettingsService::bool( 'general', 'customers_admin_activate', false );
            if ( $admin_activate ) {
                $register_success = __( 'Your account has been created and is pending admin approval. You will be notified once it is activated.', 'titancart-lite' );
            } else {
                wp_signon( [ 'user_login' => $reg_data['email'], 'user_password' => $reg_data['password'], 'remember' => true ], is_ssl() );
                wp_safe_redirect( $base );
                exit;
            }
        }
    }
}

// ── Helper: render an order table row ───────────────────────────────────
function titancart_render_order_row( $o, $base, $symbol, $show_view = true ) {
    $ourl   = $base . 'orders/?view=' . (int) $o['id'];
    $scolor = $o['status_color'] ?? '#71797E';
    $slabel = $o['status_label'] ?? ucfirst( $o['status_handle'] ?? '—' );
    $fi     = $o['first_item'] ?? null;
    ?>
    <tr>
        <td><a href="<?php echo esc_url( $ourl ); ?>" class="tc-order-num"><?php echo esc_html( $o['order_number'] ?? '#' . $o['id'] ); ?></a></td>
        <td><?php echo esc_html( titancart_format_date( $o['created_at'] ) ); ?></td>
        <td><span class="tc-status-dot" style="--dot:<?php echo esc_attr( $scolor ); ?>"><?php echo esc_html( $slabel ); ?></span></td>
        <td><?php echo esc_html( $symbol . number_format( (float) $o['total'], 2 ) ); ?></td>
        <td>
            <?php if ( $fi ) :
                // S93 image shape: $fi['product_image'] is array {url, thumb, alt} or null.
                $_fi_img = is_array( $fi['product_image'] ?? null ) ? $fi['product_image'] : null;
            ?>
            <div class="tc-order-product">
                <?php if ( $_fi_img && ! empty( $_fi_img['thumb'] ) ) : ?>
                    <img src="<?php echo esc_url( $_fi_img['thumb'] ); ?>"
                         width="40" height="40"
                         alt="<?php echo esc_attr( $_fi_img['alt'] ?? ( $fi['product_name'] ?? '' ) ); ?>">
                <?php else : ?>
                    <span class="tc-order-product__img-placeholder"><i class="bi bi-image"></i></span>
                <?php endif; ?>
                <div>
                    <span class="tc-order-product__name"><?php echo esc_html( $fi['product_name'] ?? '' ); ?></span>
                    <?php if ( ( $o['item_count'] ?? 0 ) > 1 ) : ?>
                        <span class="tc-order-product__more">+<?php echo (int) $o['item_count'] - 1; ?> more</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </td>
        <?php if ( $show_view ) : ?>
        <td><a href="<?php echo esc_url( $ourl ); ?>" class="tc-btn tc-btn--sm"><?php esc_html_e( 'View', 'titancart-lite' ); ?></a></td>
        <?php endif; ?>
    </tr>
    <?php
}
?>

<?php
// Redirect away from orders section if track orders is disabled
if ( ! empty( $logged_in ) && $section === 'orders'
     && ! \TitanCart\Services\SettingsService::bool( 'appearance', 'show_track_orders', true ) ) {
    wp_safe_redirect( home_url( '/my-account/' ) );
    exit;
}
// Redirect away from wishlist section if wishlist extension is disabled
if ( ! empty( $logged_in ) && $section === 'wishlist'
     && ! \TitanCart\REST\Extensions\ExtensionsController::is_active( 'wishlist' ) ) {
    wp_safe_redirect( home_url( '/my-account/' ) );
    exit;
}
// Redirect away from rewards section if rewards extension is disabled
if ( ! empty( $logged_in ) && $section === 'rewards'
     && ! \TitanCart\REST\Extensions\ExtensionsController::is_active( 'rewards' ) ) {
    wp_safe_redirect( home_url( '/my-account/' ) );
    exit;
}
?>

<?php get_header(); ?>

<?php
$_tc_is_theme = defined( 'TITANCART_THEME_ACTIVE' );
$_acct_section_labels = [ 'orders' => 'My Orders', 'wishlist' => 'Wishlist', 'rewards' => 'Reward Points', 'addresses' => 'Addresses', 'profile' => 'My Profile', 'subscriptions' => 'My Subscriptions' ];
$_acct_section_label  = ! empty( $logged_in ) && $section !== 'dashboard'
    ? ( $_acct_section_labels[ $section ] ?? ucfirst( $section ) )
    : '';
?>

<?php if ( $_tc_is_theme ) :
  $_b_cls = 'tc-shop__banner tc-shop__banner--theme';
  $_b_sty = ''; $_b_ov = '';
  $_b_img      = get_theme_mod( 'tct_shop_banner_image' );
  $_b_img_dark = get_theme_mod( 'tct_shop_banner_image_dark' );
  if ( $_b_img ) {
      $_b_url      = wp_get_attachment_image_url( (int) $_b_img, 'full' );
      $_b_url_dark = $_b_img_dark ? wp_get_attachment_image_url( (int) $_b_img_dark, 'full' ) : '';
      if ( $_b_url ) {
          $_b_pos = get_theme_mod( 'tct_shop_banner_position', 'center center' );
          $_b_ht  = get_theme_mod( 'tct_shop_banner_height', 280 );
          $_b_ov  = get_theme_mod( 'tct_shop_banner_overlay', 'rgba(0,0,0,0.45)' );
          $_b_sty = sprintf( 'background-image:url(%s);background-size:cover;background-position:%s;height:%dpx;',
              esc_url( $_b_url ), esc_attr( $_b_pos ), (int) $_b_ht );
          $_b_cls .= ' tc-shop__banner--has-image';
          // Dark-mode banner image: append --tc-banner-img-dark CSS variable
          // and add the dark-image class. Pairs with the rule in shop.css
          // (line ~264) that swaps background-image when [data-theme="dark"]
          // is active. Inline style is required because the light URL is
          // also inline — otherwise specificity wouldn't match. Mirrors the
          // pattern in archive.php / single.php exactly so PDP, shop, and
          // account pages share the same dark-banner customizer setting
          // (tct_shop_banner_image_dark). Pattern #97 from S150 R3.
          if ( $_b_url_dark ) {
              $_b_sty .= sprintf( '--tc-banner-img-dark:url(%s);', esc_url( $_b_url_dark ) );
              $_b_cls .= ' tc-shop__banner--has-dark-image';
          }
      }
  }
?>
<!-- ═══ Full-Width Page Header Banner (Theme) ═══ -->
<section class="<?php echo esc_attr( $_b_cls ); ?>" style="<?php echo esc_attr( $_b_sty ); ?>">
  <?php if ( $_b_ov ) : ?><div class="tc-shop__banner-overlay" style="background:<?php echo esc_attr( $_b_ov ); ?>;position:absolute;top:0;left:0;right:0;bottom:0;"></div><?php endif; ?>
  <div class="tc-shop__banner-inner">
    <h2 class="tc-shop__banner-title"><?php esc_html_e( 'My Account', 'titancart-lite' ); ?></h2>
    <nav class="tc-breadcrumb tc-breadcrumb--centered">
      <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
      <i class="bi bi-chevron-right"></i>
      <?php if ( $_acct_section_label ) : ?>
        <a href="<?php echo esc_url( home_url( '/my-account/' ) ); ?>">My Account</a>
        <i class="bi bi-chevron-right"></i>
        <span class="tc-breadcrumb__current"><?php echo esc_html( $_acct_section_label ); ?></span>
      <?php else : ?>
        <span class="tc-breadcrumb__current">My Account</span>
      <?php endif; ?>
    </nav>
  </div>
</section>
<?php endif; ?>

<div id="tc-account" class="tc-account">

<?php if ( empty( $logged_in ) ) : ?>
<!-- ═══ LOGIN / REGISTER ═══ -->

<?php if ( ! $_tc_is_theme ) : ?>
<div class="tc-account__banner">
    <div class="tc-account__banner-inner">
        <h1 class="tc-account__banner-title"><?php esc_html_e( 'My Account', 'titancart-lite' ); ?></h1>
        <nav class="tc-account__breadcrumb">
            <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
            <span class="tc-sep">›</span>
            <span>My Account</span>
        </nav>
    </div>
</div>
<?php endif; ?>

<div class="tc-account__auth-wrap">
    <div class="tc-account__auth-grid">

        <!-- Login -->
        <div class="tc-auth-card" id="tc-auth-login">
            <h3 class="tc-auth-card__title"><?php esc_html_e( 'Login', 'titancart-lite' ); ?></h3>
            <p class="tc-auth-card__subtitle">Don't have an account yet? <a href="#" class="tc-auth-toggle" data-show="register">Sign Up</a></p>
            <?php
            $tc_auth_error = sanitize_text_field( wp_unslash( $_GET['tc_auth_error'] ?? '' ) );
            if ( $tc_auth_error ) :
                $tc_auth_messages = [
                    'denied' => __( 'You cancelled the sign-in. Please try again.', 'titancart-lite' ),
                    'token'  => __( 'Could not complete sign-in. Please try again or use email/password.', 'titancart-lite' ),
                    'email'  => __( 'No email address was provided by the social account. Please use email/password.', 'titancart-lite' ),
                    'create' => __( 'Could not create your account. Please try registering with email/password.', 'titancart-lite' ),
                ];
                $tc_auth_msg = $tc_auth_messages[ $tc_auth_error ] ?? __( 'Social login failed. Please try again.', 'titancart-lite' );
            ?>
                <div class="tc-auth-msg tc-auth-msg--error"><?php echo esc_html( $tc_auth_msg ); ?></div>
            <?php endif; ?>
            <?php if ( ! empty( $login_error ) ) : ?>
                <div class="tc-auth-msg tc-auth-msg--error"><?php echo esc_html( $login_error ); ?></div>
            <?php endif; ?>
            <form method="post" class="tc-auth-form" id="tc-login-form">
                <?php wp_nonce_field( 'tc_login', 'tc_login_nonce' ); ?>
                <div class="tc-field">
                    <label for="tc-login-email">Email address</label>
                    <input type="email" id="tc-login-email" name="tc_email" required autocomplete="email"
                           value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['tc_email'] ?? '' ) ) ); ?>">
                </div>
                <div class="tc-field">
                    <label for="tc-login-pass">Password</label>
                    <div class="tc-field__pw-wrap">
                        <input type="password" id="tc-login-pass" name="tc_password" required autocomplete="current-password">
                        <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                    </div>
                </div>
                <div class="tc-field--row">
                    <label class="tc-checkbox">
                        <input type="checkbox" name="tc_remember" value="1">
                        <span>Remember me</span>
                    </label>
                    <a href="<?php echo esc_url( wp_lostpassword_url( $base ) ); ?>" class="tc-auth-link">Forgot Password?</a>
                </div>
                <?php do_action( 'titancart_recaptcha_field', 'login' ); ?>
                <button type="submit" class="tc-btn tc-btn--primary tc-btn--full tc-btn--large">Login</button>
            </form>
        </div>

        <!-- Register -->
        <div class="tc-auth-card tc-auth-card--hidden" id="tc-auth-register">
            <h3 class="tc-auth-card__title">Create an account</h3>
            <p class="tc-auth-card__subtitle">Already have an account? <a href="#" class="tc-auth-toggle" data-show="login">Sign In</a></p>
            <?php if ( ! empty( $register_error ) ) : ?>
                <div class="tc-auth-msg tc-auth-msg--error"><?php echo esc_html( $register_error ); ?></div>
            <?php endif; ?>
            <?php if ( ! empty( $register_success ) ) : ?>
                <div class="tc-auth-msg tc-auth-msg--success" style="background:#F0FDF4;color:#16A34A;border:1px solid #BBF7D0;padding:12px 16px;border-radius:8px;font-size:14px;margin-bottom:16px"><?php echo esc_html( $register_success ); ?></div>
            <?php endif; ?>
            <form method="post" class="tc-auth-form" id="tc-register-form">
                <?php wp_nonce_field( 'tc_register', 'tc_register_nonce' );
                $quick_reg      = \TitanCart\Services\SettingsService::bool( 'general', 'customers_quick_registration', true );
                $group_signup   = \TitanCart\Services\SettingsService::bool( 'general', 'customers_allow_group_signup', true );
                ?>
                <div class="tc-field--row-2col">
                    <div class="tc-field">
                        <label for="tc-reg-first">First name</label>
                        <input type="text" id="tc-reg-first" name="tc_reg_first" autocomplete="given-name"
                               value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['tc_reg_first'] ?? '' ) ) ); ?>">
                    </div>
                    <div class="tc-field">
                        <label for="tc-reg-last">Last name</label>
                        <input type="text" id="tc-reg-last" name="tc_reg_last" autocomplete="family-name"
                               value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['tc_reg_last'] ?? '' ) ) ); ?>">
                    </div>
                </div>
                <div class="tc-field">
                    <label for="tc-reg-email">Email address</label>
                    <input type="email" id="tc-reg-email" name="tc_reg_email" required autocomplete="email"
                           value="<?php echo esc_attr( sanitize_email( wp_unslash( $_POST['tc_reg_email'] ?? '' ) ) ); ?>">
                </div>
                <?php if ( ! $quick_reg ) : ?>
                <div class="tc-field--row-2col">
                    <div class="tc-field">
                        <label for="tc-reg-phone"><?php esc_html_e( 'Phone', 'titancart-lite' ); ?></label>
                        <input type="tel" id="tc-reg-phone" name="tc_reg_phone" autocomplete="tel"
                               value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['tc_reg_phone'] ?? '' ) ) ); ?>">
                    </div>
                    <div class="tc-field">
                        <label for="tc-reg-company"><?php esc_html_e( 'Company', 'titancart-lite' ); ?></label>
                        <input type="text" id="tc-reg-company" name="tc_reg_company" autocomplete="organization"
                               value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['tc_reg_company'] ?? '' ) ) ); ?>">
                    </div>
                </div>
                <?php endif; ?>
                <?php if ( $group_signup ) :
                    $_db = titancart_db();
                    // Exclude groups that require a paid subscription to join.
                    $_sub_gated_ids = [];
                    if ( defined( 'TCS_VERSION' ) ) {
                        $_sub_rows = $_db->getArray(
                            "SELECT DISTINCT usergroup_id FROM {$_db->table('subscription_plans')}
                             WHERE usergroup_id IS NOT NULL AND status = 'active'"
                        );
                        foreach ( $_sub_rows as $_sr ) {
                            $_sub_gated_ids[] = (int) $_sr['usergroup_id'];
                        }
                    }
                    $_exclude_sql = ! empty( $_sub_gated_ids )
                        ? " AND g.id NOT IN (" . implode( ',', array_map( 'intval', $_sub_gated_ids ) ) . ")"
                        : '';
                    $_groups = $_db->getArray(
                        "SELECT g.id, COALESCE(t.name, g.handle) AS name
                         FROM {$_db->table('usergroups')} g
                         LEFT JOIN {$_db->table('usergroup_translations')} t
                             ON t.group_id = g.id AND t.language_code = 'en'
                         WHERE g.status = 'active' AND g.handle <> 'guest'{$_exclude_sql}
                         ORDER BY g.id"
                    );
                    if ( ! empty( $_groups ) ) : ?>
                <div class="tc-field">
                    <label for="tc-reg-group"><?php esc_html_e( 'Customer group', 'titancart-lite' ); ?></label>
                    <select id="tc-reg-group" name="tc_reg_group" class="tc-input tc-select">
                        <option value=""><?php esc_html_e( '— None —', 'titancart-lite' ); ?></option>
                        <?php foreach ( $_groups as $_g ) : ?>
                        <option value="<?php echo esc_attr( $_g['id'] ); ?>" <?php selected( sanitize_text_field( wp_unslash( $_POST['tc_reg_group'] ?? '' ) ), $_g['id'] ); ?>><?php echo esc_html( $_g['name'] ); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; endif; ?>
                <?php
                // Custom (non-system) contact-section fields configured via
                // Customer Fields admin page (S127.C-1). Renders only when at
                // least one is_visible=1 non-system field exists. Submitted
                // values survive validation-failure re-renders via the
                // override map. Wrapper class matches the rest of dashboard.php's
                // form (tc-field, no tc-input class on the input itself).
                $_reg_fields_mgr = new \TitanCart\Modules\Accounts\CustomerFieldsManager();
                $_reg_cf_overrides = $_reg_fields_mgr->extract_submitted( $_POST );
                $_reg_cf_html = $_reg_fields_mgr->render_section_html( 'contact', 0, 'tc-reg-cf-', $_reg_cf_overrides, 'tc-field', '' );
                if ( $_reg_cf_html !== '' ) {
                    echo wp_kses( $_reg_cf_html, \TitanCart\Modules\Accounts\CustomerFieldsManager::form_kses_allowed() );
                }
                ?>
                <div class="tc-field">
                    <label for="tc-reg-pass">Password</label>
                    <div class="tc-field__pw-wrap">
                        <input type="password" id="tc-reg-pass" name="tc_reg_password" required minlength="6" autocomplete="new-password">
                        <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                    </div>
                </div>
                <div class="tc-field">
                    <label for="tc-reg-confirm">Confirm password</label>
                    <div class="tc-field__pw-wrap">
                        <input type="password" id="tc-reg-confirm" name="tc_reg_confirm" required minlength="6" autocomplete="new-password">
                        <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                    </div>
                </div>
                <label class="tc-checkbox">
                    <input type="checkbox" name="tc_agree" value="1" required>
                    <span>I agree to the Terms of Service and Privacy Policy</span>
                </label>
                <?php
                /**
                 * Newsletter opt-in (Phase 5 block B, S241).
                 *
                 * One unchecked opt-in checkbox per active subscriber list flagged
                 * "Show on registration". Submitted as newsletter_optin[] with this
                 * register form POST and honoured in the handler at the top of this
                 * template. Unchecked by default for consent compliance; re-checks
                 * itself on a validation-failure re-render. Uses the form's existing
                 * .tc-checkbox styling for visual consistency with the agree box.
                 */
                if (
                    \TitanCart\REST\Extensions\ExtensionsController::is_active( 'newsletters' )
                    && \TitanCart\Services\SettingsService::bool( 'newsletters', 'show_subscribe_registration', true )
                ) {
                    global $wpdb;
                    $tc_reg_lists = $wpdb->get_results(
                        "SELECT id, name FROM {$wpdb->prefix}tc_subscriber_lists
                         WHERE status = 'active' AND show_on_registration = 1
                         ORDER BY name ASC",
                        ARRAY_A
                    );
                    $tc_reg_posted = array_map( 'intval', (array) wp_unslash( $_POST['newsletter_optin'] ?? [] ) ); // WP.org R1 🅱2: unslash; intval is the sanitizer.
                    foreach ( (array) $tc_reg_lists as $tc_reg_list ) :
                        $tc_reg_list_label = ( (string) $tc_reg_list['name'] !== '' )
                            ? $tc_reg_list['name']
                            /* translators: %d: subscriber list ID (fallback label when the list has no name). */
                            : sprintf( __( 'List #%d', 'titancart-lite' ), (int) $tc_reg_list['id'] );
                        ?>
                        <label class="tc-checkbox">
                            <input type="checkbox" name="newsletter_optin[]"
                                   value="<?php echo (int) $tc_reg_list['id']; ?>"
                                   <?php checked( in_array( (int) $tc_reg_list['id'], $tc_reg_posted, true ) ); ?>>
                            <span><?php
                                /* translators: %s: subscriber list name */
                                echo esc_html( sprintf( __( 'Subscribe to %s', 'titancart-lite' ), $tc_reg_list_label ) );
                            ?></span>
                        </label>
                        <?php
                    endforeach;
                }
                ?>
                <?php do_action( 'titancart_recaptcha_field', 'register' ); ?>
                <button type="submit" class="tc-btn tc-btn--primary tc-btn--full tc-btn--large">Create an account</button>
            </form>
        </div>

        <!-- Benefits -->
        <div class="tc-auth-benefits">
            <div class="tc-auth-benefits__inner">
                <h3>Why create an account?</h3>
                <ul>
                    <li><i class="bi bi-bag-check"></i><div><strong>Track orders</strong><p>Follow your orders from purchase to delivery.</p></div></li>
                    <li><i class="bi bi-lightning"></i><div><strong>Faster checkout</strong><p>Save your addresses and pay in seconds.</p></div></li>
                    <?php if ( \TitanCart\REST\Extensions\ExtensionsController::is_active( 'wishlist' ) ) : ?>
                    <li><i class="bi bi-heart"></i><div><strong>Wishlist</strong><p>Save products you love and buy them later.</p></div></li>
                    <?php endif; ?>
                    <li><i class="bi bi-tag"></i><div><strong>Exclusive deals</strong><p>Members get early access to sales and promotions.</p></div></li>
                </ul>
            </div>
        </div>

    </div>
</div>


<?php else : ?>
<!-- ═══ LOGGED-IN ACCOUNT ═══ -->

<?php if ( ! $_tc_is_theme ) : ?>
<div class="tc-account__banner">
    <div class="tc-account__banner-inner">
        <h1 class="tc-account__banner-title">My Account</h1>
        <nav class="tc-account__breadcrumb">
            <a href="<?php echo esc_url( home_url( '/' ) ); ?>">Home</a>
            <span class="tc-sep">›</span>
            <?php if ( $section !== 'dashboard' ) : ?>
                <a href="<?php echo esc_url( $base ); ?>">My Account</a>
                <span class="tc-sep">›</span>
                <span><?php
                    $labels = [ 'orders' => 'My Orders', 'wishlist' => 'Wishlist', 'addresses' => 'Addresses', 'profile' => 'My Profile', 'subscriptions' => 'My Subscriptions' ];
                    echo esc_html( $labels[ $section ] ?? ucfirst( $section ) );
                ?></span>
            <?php else : ?>
                <span>My Account</span>
            <?php endif; ?>
        </nav>
    </div>
</div>
<?php endif; ?>

<div class="tc-account__layout">

    <!-- Sidebar -->
    <aside class="tc-account__sidebar">
        <button type="button" class="tc-account__sidebar-toggle" id="tc-sidebar-toggle">
            <i class="bi bi-list"></i> Account Menu
        </button>
        <nav class="tc-account__nav" id="tc-account-nav">
            <?php
            $show_orders = \TitanCart\Services\SettingsService::bool( 'appearance', 'show_track_orders', true );
            $nav = [
                'dashboard' => [ 'label' => 'Dashboard',  'icon' => 'bi-grid', 'group' => 'account' ],
            ];
            if ( $show_orders ) {
                $nav['orders'] = [ 'label' => 'My Orders',  'icon' => 'bi-bag-check', 'group' => 'account' ];
            }
            $nav['downloads'] = [ 'label' => 'Downloads', 'icon' => 'bi-download', 'group' => 'account' ];
            $_wishlist_on = \TitanCart\REST\Extensions\ExtensionsController::is_active( 'wishlist' );
            $nav_tail = [
                'addresses' => [ 'label' => 'Addresses',  'icon' => 'bi-geo-alt', 'group' => 'account' ],
                'profile'   => [ 'label' => 'My Profile', 'icon' => 'bi-person-square', 'group' => 'account' ],
            ];
            if ( $_wishlist_on ) {
                $nav['wishlist'] = [ 'label' => 'Wishlist', 'icon' => 'bi-heart', 'group' => 'account' ];
            }
            $nav += $nav_tail;
            // Allow extensions (e.g. Subscriptions, Affiliate, Marketplace) to add
            // nav items. Items may carry an optional 'group' key ('account' default,
            // plus 'affiliate' / 'vendor' for extension areas); items with no group
            // fall into 'account' so older extension items render unchanged.
            $nav = apply_filters( 'titancart_account_nav', $nav, $section );

            // Group the flat nav into ordered sections. Unknown groups (an
            // extension could invent its own) render after the known three, in
            // first-seen order. Empty groups render no heading.
            $group_labels = apply_filters( 'titancart_account_nav_groups', [
                'account'   => '',                 // no heading for the default group
                'affiliate' => __( 'Affiliate', 'titancart-lite' ),
                'vendor'    => __( 'Vendor', 'titancart-lite' ),
            ] );
            $grouped = [];
            foreach ( $nav as $slug => $item ) {
                $g = isset( $item['group'] ) && $item['group'] !== '' ? (string) $item['group'] : 'account';
                $grouped[ $g ][ $slug ] = $item;
            }
            // Render known groups first (in declared order), then any extras.
            $ordered_groups = array_keys( $group_labels );
            foreach ( array_keys( $grouped ) as $g ) {
                if ( ! in_array( $g, $ordered_groups, true ) ) {
                    $ordered_groups[] = $g;
                }
            }
            foreach ( $ordered_groups as $g ) :
                if ( empty( $grouped[ $g ] ) ) {
                    continue;
                }
                $g_label = $group_labels[ $g ] ?? ucfirst( $g );
            ?>
                <?php if ( $g_label !== '' ) : ?>
                <div class="tc-account__nav-heading"><?php echo esc_html( $g_label ); ?></div>
                <?php endif; ?>
                <?php foreach ( $grouped[ $g ] as $slug => $item ) :
                    $href   = $slug === 'dashboard' ? $base : $base . $slug . '/';
                    $active = ( $section === $slug ) ? ' tc-active' : '';
                ?>
                    <a href="<?php echo esc_url( $href ); ?>" class="tc-account__nav-item<?php echo esc_attr( $active ); ?>">
                        <i class="bi <?php echo esc_attr( $item['icon'] ); ?>"></i>
                        <span><?php echo esc_html( $item['label'] ); ?></span>
                    </a>
                <?php endforeach; ?>
            <?php endforeach; ?>
            <a href="<?php echo esc_url( wp_logout_url( home_url( '/' ) ) ); ?>" class="tc-account__nav-item tc-account__nav-item--logout">
                <i class="bi bi-box-arrow-left"></i>
                <span>Logout</span>
            </a>
        </nav>
    </aside>


    <!-- Content -->
    <main class="tc-account__content">

    <?php
    // ══════════════════════════════════════════════════════════════════════
    //  SECTION: Dashboard
    // ══════════════════════════════════════════════════════════════════════
    if ( $section === 'dashboard' ) :
        $fname = esc_html( $customer['first_name'] ?? '' );
        $name  = $fname ?: 'there';
    ?>
        <div class="tc-dash">
            <div class="tc-dash__welcome">
                <h2>Hello, <?php echo esc_html( $name ); ?>!</h2>
                <p>From your account dashboard you can view your recent orders, manage your shipping and billing addresses, and edit your profile.</p>
            </div>

            <div class="tc-dash__stats">
                <div class="tc-dash__stat">
                    <span class="tc-dash__stat-value"><?php echo esc_html( $total_orders ?? 0 ); ?></span>
                    <span class="tc-dash__stat-label">Total Orders</span>
                </div>
                <div class="tc-dash__stat">
                    <span class="tc-dash__stat-value"><?php echo esc_html( $symbol . number_format( (float) ( $total_spent ?? 0 ), 2 ) ); ?></span>
                    <span class="tc-dash__stat-label">Total Spent</span>
                </div>
                <?php if ( \TitanCart\REST\Extensions\ExtensionsController::is_active( 'rewards' ) ) : ?>
                <div class="tc-dash__stat">
                    <span class="tc-dash__stat-value"><?php echo esc_html( number_format( (int) ( $rewards_balance ?? 0 ) ) ); ?></span>
                    <span class="tc-dash__stat-label">Reward Points</span>
                </div>
                <?php endif; ?>
            </div>

            <div class="tc-dash__quicknav">
                <?php if ( $show_orders ) : ?>
                <a href="<?php echo esc_url( $base . 'orders/' ); ?>" class="tc-dash__card"><i class="bi bi-bag-check"></i><span>My Orders</span></a>
                <?php endif; ?>
                <?php if ( \TitanCart\REST\Extensions\ExtensionsController::is_active( 'rewards' ) ) : ?>
                <a href="<?php echo esc_url( $base . 'rewards/' ); ?>" class="tc-dash__card"><i class="bi bi-star"></i><span>Rewards</span></a>
                <?php endif; ?>
                <a href="<?php echo esc_url( $base . 'addresses/' ); ?>" class="tc-dash__card"><i class="bi bi-geo-alt"></i><span>Addresses</span></a>
                <a href="<?php echo esc_url( $base . 'profile/' ); ?>" class="tc-dash__card"><i class="bi bi-person-square"></i><span>Profile</span></a>
                <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-dash__card"><i class="bi bi-shop"></i><span>Continue Shopping</span></a>
            </div>

            <?php if ( $show_orders && ! empty( $orders ) ) : ?>
            <div class="tc-dash__section">
                <div class="tc-dash__section-head">
                    <h3>Recent Orders</h3>
                    <a href="<?php echo esc_url( $base . 'orders/' ); ?>" class="tc-link">View all →</a>
                </div>
                <div class="tc-orders-table-wrap">
                    <table class="tc-orders-table">
                        <thead><tr><th>Order</th><th>Date</th><th>Status</th><th>Total</th><th>Product</th><th></th></tr></thead>
                        <tbody>
                            <?php foreach ( array_slice( $orders, 0, 5 ) as $o ) { titancart_render_order_row( $o, $base, $symbol, true ); } ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php else : ?>
            <div class="tc-dash__empty">
                <i class="bi bi-bag-x"></i>
                <p>You haven't placed any orders yet.</p>
                <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-btn tc-btn--primary">Start Shopping</a>
            </div>
            <?php endif; ?>
        </div>

    <?php
    // ══════════════════════════════════════════════════════════════════════
    //  SECTION: Orders
    // ══════════════════════════════════════════════════════════════════════
    elseif ( $section === 'orders' && $show_orders ) :

        $order_detail = $order_detail ?? null;
    ?>

        <?php if ( $order_detail ) :
            // ── Single Order Detail View ─────────────────────────────────────
            $_od          = $order_detail;
            $_od_items    = $_od['items']    ?? [];
            $_od_notes    = $_od['notes']    ?? [];
            $_od_shipments = $_od['shipments'] ?? [];
            $_od_currency = $_od['currency'] ?? 'USD';
            $_od_scolor   = $_od['status_color'] ?? '#71797E';
            $_od_slabel   = $_od['status_label'] ?? ucfirst( $_od['status_handle'] ?? '—' );
        ?>
        <div class="tc-order-detail">

            <!-- Back link -->
            <a href="<?php echo esc_url( $base . 'orders/' ); ?>" class="tc-od__back">
                <i class="bi bi-arrow-left"></i> <?php esc_html_e( 'Back to My Orders', 'titancart-lite' ); ?>
            </a>

            <!-- Order heading -->
            <div class="tc-od__header">
                <div>
                    <h2 class="tc-od__title">
                        <?php
                        /* translators: %s: order number. */
                        printf( esc_html__( 'Order %s', 'titancart-lite' ), esc_html( $_od['order_number'] ?? '#' . $_od['id'] ) );
                        ?>
                    </h2>
                    <p class="tc-od__meta">
                        <?php esc_html_e( 'Placed:', 'titancart-lite' ); ?>
                        <?php echo esc_html( titancart_format_datetime( $_od['created_at'] ) ); ?>
                    </p>
                </div>
                <span class="tc-status-badge" style="--tc-status-color:<?php echo esc_attr( $_od_scolor ); ?>;">
                    <?php echo esc_html( $_od_slabel ); ?>
                </span>
            </div>

            <hr class="tc-od__divider">

            <!-- Items Ordered -->
            <h3 class="tc-od__section-title"><?php esc_html_e( 'Items Ordered', 'titancart-lite' ); ?></h3>
            <table class="tc-od__items">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Product', 'titancart-lite' ); ?></th>
                        <th style="text-align:center;"><?php esc_html_e( 'Qty', 'titancart-lite' ); ?></th>
                        <th style="text-align:right;"><?php esc_html_e( 'Total', 'titancart-lite' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $_od_items as $_item ) :
                        $_line_total = $_item['total'] ?? $_item['line_total'] ?? 0;
                        // S93 image shape: $_item['image'] is array {url, thumb, alt} or null
                        // (added at OrderManager::get_order S210). Legacy $_item['thumbnail']
                        // string URL kept by OrderManager for backward compat.
                        $_od_img = is_array( $_item['image'] ?? null ) ? $_item['image'] : null;
                    ?>
                    <tr>
                        <td class="tc-od__product-cell">
                            <?php if ( $_od_img && ! empty( $_od_img['thumb'] ) ) : ?>
                                <img src="<?php echo esc_url( $_od_img['thumb'] ); ?>"
                                     width="48" height="48"
                                     alt="<?php echo esc_attr( $_od_img['alt'] ?? ( $_item['name'] ?? '' ) ); ?>"
                                     class="tc-od__thumb">
                            <?php else : ?>
                                <span class="tc-od__thumb-placeholder"><i class="bi bi-image"></i></span>
                            <?php endif; ?>
                            <div>
                                <strong><?php echo esc_html( $_item['name'] ?? '' ); ?></strong>
                                <?php if ( ! empty( $_item['sku'] ) ) : ?>
                                    <br><small class="tc-muted"><?php echo esc_html( $_item['sku'] ); ?></small>
                                <?php endif; ?>
                                <?php if ( ! empty( $_item['options'] ) && is_array( $_item['options'] ) ) : ?>
                                    <br><small class="tc-muted">
                                        <?php
                                        $opt_parts = [];
                                        foreach ( $_item['options'] as $_opt ) {
                                            $opt_parts[] = ( $_opt['option_name'] ?? '' ) . ': ' . ( $_opt['variant_name'] ?? '' );
                                        }
                                        echo esc_html( implode( ', ', $opt_parts ) );
                                        ?>
                                    </small>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td style="text-align:center;"><?php echo (int) ( $_item['quantity'] ?? 0 ); ?></td>
                        <td style="text-align:right;font-weight:600;">
                            <?php echo esc_html( $symbol . number_format( (float) $_line_total, 2 ) ); ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Totals -->
            <div class="tc-od__totals">
                <?php if ( (float) ( $_od['subtotal'] ?? 0 ) > 0 ) : ?>
                <div class="tc-od__total-row">
                    <span><?php esc_html_e( 'Subtotal', 'titancart-lite' ); ?></span>
                    <span><?php echo esc_html( $symbol . number_format( (float) $_od['subtotal'], 2 ) ); ?></span>
                </div>
                <?php endif; ?>
                <?php if ( (float) ( $_od['discount'] ?? 0 ) > 0 ) : ?>
                <div class="tc-od__total-row">
                    <span><?php esc_html_e( 'Discount', 'titancart-lite' ); ?></span>
                    <span>&minus;<?php echo esc_html( $symbol . number_format( (float) $_od['discount'], 2 ) ); ?></span>
                </div>
                <?php endif; ?>
                <div class="tc-od__total-row">
                    <span><?php esc_html_e( 'Shipping', 'titancart-lite' ); ?></span>
                    <span><?php echo esc_html( $symbol . number_format( (float) ( $_od['shipping_cost'] ?? 0 ), 2 ) ); ?></span>
                </div>
                <?php if ( (float) ( $_od['tax_total'] ?? 0 ) > 0 ) : ?>
                <div class="tc-od__total-row">
                    <span><?php esc_html_e( 'Tax', 'titancart-lite' ); ?></span>
                    <span><?php echo esc_html( $symbol . number_format( (float) $_od['tax_total'], 2 ) ); ?></span>
                </div>
                <?php endif; ?>
                <?php if ( (float) ( $_od['tip_total'] ?? 0 ) > 0 ) : ?>
                <div class="tc-od__total-row">
                    <span><?php echo esc_html( apply_filters( 'titancart_tip_line_label', __( 'Tip', 'titancart-lite' ), $_od ) ); ?></span>
                    <span><?php echo esc_html( $symbol . number_format( (float) $_od['tip_total'], 2 ) ); ?></span>
                </div>
                <?php endif; ?>
                <div class="tc-od__total-row tc-od__total-row--grand">
                    <span><?php esc_html_e( 'Total', 'titancart-lite' ); ?></span>
                    <strong><?php echo esc_html( $symbol . number_format( (float) ( $_od['total'] ?? 0 ), 2 ) ); ?></strong>
                </div>
            </div>

            <?php
            /**
             * Gateway-specific post-checkout content slot for order detail.
             *
             * Offline gateways (Bank Transfer, Check) hook here to redisplay
             * their payment instructions so customers can refer back to
             * account details after leaving the order-received page.
             * Online gateways and COD emit nothing. Wired in PaymentsModule (S210).
             */
            do_action( 'titancart_order_detail_payment_section', $_od );
            ?>

            <hr class="tc-od__divider">

            <!-- Addresses -->
            <div class="tc-od__addresses">
                <div class="tc-od__address-card">
                    <h3 class="tc-od__section-title"><?php esc_html_e( 'Billing Address', 'titancart-lite' ); ?></h3>
                    <address>
                        <?php echo esc_html( trim( ( $_od['billing_first_name'] ?? '' ) . ' ' . ( $_od['billing_last_name'] ?? '' ) ) ); ?><br>
                        <?php if ( ! empty( $_od['billing_company'] ) ) : ?>
                            <?php echo esc_html( $_od['billing_company'] ); ?><br>
                        <?php endif; ?>
                        <?php echo esc_html( $_od['billing_address_1'] ?? '' ); ?><br>
                        <?php if ( ! empty( $_od['billing_address_2'] ) ) : ?>
                            <?php echo esc_html( $_od['billing_address_2'] ); ?><br>
                        <?php endif; ?>
                        <?php
                            echo esc_html( $_od['billing_city'] ?? '' );
                            if ( ! empty( $_od['billing_state'] ) ) echo ', ' . esc_html( $_od['billing_state'] );
                            echo ' ' . esc_html( $_od['billing_postcode'] ?? '' );
                        ?><br>
                        <?php echo esc_html( $_od['billing_country'] ?? '' ); ?><br>
                        <?php if ( ! empty( $_od['billing_phone'] ) ) : ?>
                            <span class="tc-muted"><?php echo esc_html( $_od['billing_phone'] ); ?></span><br>
                        <?php endif; ?>
                        <?php if ( ! empty( $_od['billing_email'] ) ) : ?>
                            <span class="tc-muted"><?php echo esc_html( $_od['billing_email'] ); ?></span>
                        <?php endif; ?>
                    </address>
                </div>
                <div class="tc-od__address-card">
                    <h3 class="tc-od__section-title"><?php esc_html_e( 'Shipping Address', 'titancart-lite' ); ?></h3>
                    <address>
                        <?php echo esc_html( trim( ( $_od['shipping_first_name'] ?? '' ) . ' ' . ( $_od['shipping_last_name'] ?? '' ) ) ); ?><br>
                        <?php if ( ! empty( $_od['shipping_company'] ) ) : ?>
                            <?php echo esc_html( $_od['shipping_company'] ); ?><br>
                        <?php endif; ?>
                        <?php echo esc_html( $_od['shipping_address_1'] ?? '' ); ?><br>
                        <?php if ( ! empty( $_od['shipping_address_2'] ) ) : ?>
                            <?php echo esc_html( $_od['shipping_address_2'] ); ?><br>
                        <?php endif; ?>
                        <?php
                            echo esc_html( $_od['shipping_city'] ?? '' );
                            if ( ! empty( $_od['shipping_state'] ) ) echo ', ' . esc_html( $_od['shipping_state'] );
                            echo ' ' . esc_html( $_od['shipping_postcode'] ?? '' );
                        ?><br>
                        <?php echo esc_html( $_od['shipping_country'] ?? '' ); ?>
                    </address>
                </div>
            </div>

            <?php if ( ! empty( $_od_shipments ) ) : ?>
            <hr class="tc-od__divider">
            <h3 class="tc-od__section-title"><?php esc_html_e( 'Shipments &amp; Tracking', 'titancart-lite' ); ?></h3>
            <div class="tc-od__shipments">
                <?php foreach ( $_od_shipments as $_sh ) :
                    $_sh_scolor   = $_sh['status_color'] ?? '#71797E';
                    $_sh_slabel   = $_sh['status_label'] ?? ucfirst( $_sh['status_handle'] ?? __( 'Pending', 'titancart-lite' ) );
                    $_sh_carrier  = trim( (string) ( $_sh['carrier'] ?? '' ) );
                    $_sh_tracking = trim( (string) ( $_sh['tracking_number'] ?? '' ) );
                    $_sh_trackurl = trim( (string) ( $_sh['tracking_url'] ?? '' ) );
                    // KI-22: only label a date "Shipped:" when shipped_at is actually
                    // set; an unshipped (pending) shipment falls back to its created_at
                    // under a neutral "Created:" label rather than implying it shipped.
                    $_sh_shipped  = ! empty( $_sh['shipped_at'] ) ? $_sh['shipped_at'] : '';
                    $_sh_date     = $_sh_shipped !== '' ? $_sh_shipped : ( $_sh['created_at'] ?? '' );
                    $_sh_date_lbl = $_sh_shipped !== '' ? __( 'Shipped:', 'titancart-lite' ) : __( 'Created:', 'titancart-lite' );
                ?>
                <div class="tc-od__shipment">
                    <div class="tc-od__shipment-head">
                        <span class="tc-status-badge" style="--tc-status-color:<?php echo esc_attr( $_sh_scolor ); ?>;">
                            <?php echo esc_html( $_sh_slabel ); ?>
                        </span>
                        <?php if ( $_sh_date ) : ?>
                            <span class="tc-od__shipment-date">
                                <?php echo esc_html( $_sh_date_lbl ); ?> <?php echo esc_html( titancart_format_date( $_sh_date ) ); ?>
                            </span>
                        <?php endif; ?>
                    </div>
                    <div class="tc-od__shipment-meta">
                        <?php if ( $_sh_carrier ) : ?>
                            <div><span class="tc-muted"><?php esc_html_e( 'Carrier:', 'titancart-lite' ); ?></span> <strong><?php echo esc_html( strtoupper( $_sh_carrier ) ); ?></strong></div>
                        <?php endif; ?>
                        <?php if ( $_sh_tracking ) : ?>
                            <div>
                                <span class="tc-muted"><?php esc_html_e( 'Tracking #:', 'titancart-lite' ); ?></span>
                                <?php if ( $_sh_trackurl ) : ?>
                                    <a href="<?php echo esc_url( $_sh_trackurl ); ?>" target="_blank" rel="noopener" class="tc-od__track-link"><?php echo esc_html( $_sh_tracking ); ?> <i class="bi bi-box-arrow-up-right"></i></a>
                                <?php else : ?>
                                    <strong class="tc-od__track-num"><?php echo esc_html( $_sh_tracking ); ?></strong>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        <?php if ( ! $_sh_carrier && ! $_sh_tracking ) : ?>
                            <div class="tc-muted"><?php esc_html_e( 'Tracking details will appear here once added.', 'titancart-lite' ); ?></div>
                        <?php endif; ?>
                    </div>
                    <?php if ( ! empty( $_sh['items'] ) ) : ?>
                    <ul class="tc-od__shipment-items">
                        <?php foreach ( $_sh['items'] as $_sit ) : ?>
                        <li>
                            <?php echo esc_html( $_sit['product_name'] ?? ( $_sit['product_code'] ?? __( 'Item', 'titancart-lite' ) ) ); ?>
                            <span class="tc-muted">&times; <?php echo (int) ( $_sit['quantity'] ?? 0 ); ?></span>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if ( ! empty( $_od_notes ) ) : ?>
            <hr class="tc-od__divider">
            <h3 class="tc-od__section-title"><?php esc_html_e( 'Order Notes', 'titancart-lite' ); ?></h3>
            <ul class="tc-od__notes">
                <?php foreach ( $_od_notes as $_note ) : ?>
                <li class="tc-od__note">
                    <p><?php echo wp_kses_post( $_note['note'] ?? '' ); ?></p>
                    <small class="tc-muted">
                        <?php echo esc_html( titancart_format_datetime( $_note['created_at'] ?? '' ) ); ?>
                    </small>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>

            <?php
            // Allow extensions (e.g. RMA) to add action buttons to the order detail page.
            do_action( 'titancart_order_detail_actions', $_od );
            ?>

        </div><!-- .tc-order-detail -->

        <?php else : ?>
        <!-- ── Orders List ────────────────────────────────────────────── -->
        <div class="tc-myorders">
            <h2 class="tc-myorders__title">My Orders</h2>
            <?php if ( ! empty( $orders ) ) : ?>
            <div class="tc-orders-table-wrap">
                <table class="tc-orders-table">
                    <thead><tr><th>Order#</th><th>Date</th><th>Status</th><th>Total</th><th>Product</th></tr></thead>
                    <tbody>
                        <?php foreach ( $orders as $o ) { titancart_render_order_row( $o, $base, $symbol, false ); } ?>
                    </tbody>
                </table>
            </div>
            <?php else : ?>
            <div class="tc-dash__empty">
                <i class="bi bi-bag-x"></i>
                <p>You haven't placed any orders yet.</p>
                <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-btn tc-btn--primary">Start Shopping</a>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    <?php
    // ══════════════════════════════════════════════════════════════════════
    //  SECTION: Wishlist
    // ══════════════════════════════════════════════════════════════════════
    elseif ( $section === 'wishlist' ) :
        $wl_items = $wishlist['items'] ?? [];
    ?>
        <div class="tc-wishlist">
            <div class="tc-wishlist__head">
                <h2>My Wishlist</h2>
                <?php if ( ! empty( $wl_items ) ) : ?>
                    <span class="tc-wishlist__count"><?php echo count( $wl_items ); ?> <?php echo count( $wl_items ) === 1 ? 'item' : 'items'; ?></span>
                <?php endif; ?>
            </div>

            <?php if ( ! empty( $wl_items ) ) : ?>
            <div class="tc-wishlist__grid">
                <?php foreach ( $wl_items as $wi ) :
                    $price      = (float) ( $wi['price'] ?? 0 );
                    $list_price = (float) ( $wi['list_price'] ?? 0 );
                    $has_sale   = $list_price > 0 && $list_price > $price;
                    $pname      = $wi['product_name'] ?? '';
                    $purl       = $wi['product_url'] ?? '#';
                    $thumb      = $wi['thumbnail_url'] ?? '';
                    $pid        = (int) ( $wi['product_id'] ?? 0 );
                    $status     = $wi['status'] ?? 'active';
                    $stock_st   = $wi['stock_status'] ?? 'in_stock';
                    $out        = ( $status !== 'active' || $stock_st === 'out_of_stock' );
                    $discount   = ( $has_sale && $list_price > 0 ) ? round( ( ( $list_price - $price ) / $list_price ) * 100 ) : 0;
                ?>
                <div class="product-card tc-wl-card" data-product-id="<?php echo (int) $pid; ?>">
                    <div class="product-card__image-wrap">
                        <a href="<?php echo esc_url( $purl ); ?>">
                            <?php if ( $thumb ) : ?>
                                <img src="<?php echo esc_url( $thumb ); ?>" alt="<?php echo esc_attr( $pname ); ?>" class="product-img" loading="lazy">
                            <?php else : ?>
                                <div class="product-img-placeholder"><i class="bi bi-image" style="font-size:2.5rem;color:#d4d4d4"></i></div>
                            <?php endif; ?>
                        </a>
                        <?php if ( $has_sale ) : ?>
                            <span class="product-card__badge">Sale</span>
                        <?php endif; ?>
                        <button type="button" class="tc-wl-card__remove" data-product-id="<?php echo (int) $pid; ?>" title="Remove from wishlist">
                            <i class="bi bi-trash"></i>
                        </button>
                        <?php if ( ! $out ) : ?>
                        <div class="product-card__cart-overlay">
                            <button type="button" class="product-card__cart-btn tc-wl-add-cart" data-product-id="<?php echo (int) $pid; ?>">Add to Cart</button>
                        </div>
                        <?php else : ?>
                        <div class="product-card__cart-overlay product-card__cart-overlay--notify">
                            <span class="product-card__cart-btn" style="opacity:.7;cursor:default">Unavailable</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="product-card__body">
                        <a href="<?php echo esc_url( $purl ); ?>" class="product-title"><?php echo esc_html( $pname ); ?></a>
                        <div class="product-card__price-grid">
                            <?php if ( $has_sale ) : ?>
                                <span class="product-card__old-price"><?php echo esc_html( $symbol . number_format( $list_price, 2 ) ); ?></span>
                            <?php endif; ?>
                            <span class="product-card__current-price"><?php echo esc_html( $symbol . number_format( $price, 2 ) ); ?></span>
                            <?php if ( $discount > 0 ) : ?>
                                <span class="product-card__discount">-<?php echo esc_html( $discount ); ?>%</span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else : ?>
            <div class="tc-dash__empty">
                <i class="bi bi-heart"></i>
                <p>Your wishlist is empty.</p>
                <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-btn tc-btn--primary">Browse Products</a>
            </div>
            <?php endif; ?>
        </div>

    <?php
    // ══════════════════════════════════════════════════════════════════════
    //  SECTION: Addresses
    // ══════════════════════════════════════════════════════════════════════
    elseif ( $section === 'addresses' ) :
        $countries_json = wp_json_encode( $countries ?? [] );
        $allow_multi = \TitanCart\Services\SettingsService::bool( 'general', 'customers_allow_multiple_profiles', false );
        $has_addresses = ! empty( $addresses );
        $show_add_btn  = $allow_multi || ! $has_addresses;
    ?>
        <div class="tc-addresses" data-countries='<?php echo esc_attr( $countries_json ); ?>'>
            <div class="tc-addresses__head">
                <h2>My Addresses</h2>
                <?php if ( $show_add_btn ) : ?>
                <button type="button" class="tc-btn tc-btn--primary tc-btn--sm" id="tc-add-address-btn">
                    <i class="bi bi-plus-lg"></i> Add New Address
                </button>
                <?php endif; ?>
            </div>

            <div id="tc-address-msg"></div>

            <div class="tc-addresses__list" id="tc-addresses-list">
                <?php if ( ! empty( $addresses ) ) :
                    foreach ( $addresses as $addr ) :
                        $is_def = ! empty( $addr['is_default'] );
                ?>
                <div class="tc-address-card" data-id="<?php echo (int) $addr['id']; ?>">
                    <div class="tc-address-card__head">
                        <h4><?php echo esc_html( ucfirst( $addr['type'] ?? 'shipping' ) ); ?></h4>
                        <?php if ( $is_def ) : ?><span class="tc-address-card__badge">Default</span><?php endif; ?>
                    </div>
                    <address class="tc-address-card__body">
                        <?php
                        echo esc_html( trim( ( $addr['first_name'] ?? '' ) . ' ' . ( $addr['last_name'] ?? '' ) ) );
                        if ( ! empty( $addr['company'] ) ) echo '<br>' . esc_html( $addr['company'] );
                        echo '<br>' . esc_html( $addr['address_1'] ?? '' );
                        if ( ! empty( $addr['address_2'] ) ) echo ', ' . esc_html( $addr['address_2'] );
                        echo '<br>' . esc_html( ( $addr['city'] ?? '' ) . ', ' . ( $addr['state'] ?? '' ) . ' ' . ( $addr['postcode'] ?? '' ) );
                        echo '<br>' . esc_html( $addr['country'] ?? '' );
                        if ( ! empty( $addr['phone'] ) ) echo '<br>' . esc_html( $addr['phone'] );
                        ?>
                    </address>
                    <div class="tc-address-card__actions">
                        <button type="button" class="tc-btn tc-btn--sm tc-btn--outline tc-addr-edit" data-id="<?php echo (int) $addr['id']; ?>">Edit</button>
                        <?php if ( ! $is_def ) : ?>
                        <button type="button" class="tc-btn tc-btn--sm tc-btn--outline tc-addr-default" data-id="<?php echo (int) $addr['id']; ?>">Set Default</button>
                        <?php endif; ?>
                        <button type="button" class="tc-btn tc-btn--sm tc-btn--outline tc-btn--danger tc-addr-delete" data-id="<?php echo (int) $addr['id']; ?>">Delete</button>
                    </div>
                </div>
                <?php endforeach;
                else : ?>
                <div class="tc-dash__empty tc-dash__empty--sm">
                    <i class="bi bi-geo-alt"></i>
                    <p>No saved addresses yet.</p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Address Modal -->
        <div class="tc-modal-overlay" id="tc-address-modal" style="display:none">
            <div class="tc-modal">
                <div class="tc-modal__head">
                    <h3 id="tc-address-modal-title">Add New Address</h3>
                    <button type="button" class="tc-modal__close" id="tc-address-modal-close">&times;</button>
                </div>
                <form id="tc-address-form" class="tc-modal__body">
                    <input type="hidden" id="tc-addr-id" value="">
                    <div class="tc-field--row-2col">
                        <div class="tc-field"><label for="tc-addr-first">First name *</label><input type="text" id="tc-addr-first" name="first_name" required></div>
                        <div class="tc-field"><label for="tc-addr-last">Last name *</label><input type="text" id="tc-addr-last" name="last_name" required></div>
                    </div>
                    <div class="tc-field"><label for="tc-addr-company">Company</label><input type="text" id="tc-addr-company" name="company"></div>
                    <div class="tc-field"><label for="tc-addr-address1">Address *</label><input type="text" id="tc-addr-address1" name="address_1" data-tc-autocomplete="account" required></div>
                    <div class="tc-field"><label for="tc-addr-address2">Address line 2</label><input type="text" id="tc-addr-address2" name="address_2"></div>
                    <div class="tc-field--row-2col">
                        <div class="tc-field"><label for="tc-addr-city">City *</label><input type="text" id="tc-addr-city" name="city" required></div>
                        <div class="tc-field"><label for="tc-addr-state">State / Province</label><input type="text" id="tc-addr-state" name="state"></div>
                    </div>
                    <div class="tc-field--row-2col">
                        <div class="tc-field"><label for="tc-addr-postcode">ZIP / Postal code *</label><input type="text" id="tc-addr-postcode" name="postcode" required></div>
                        <div class="tc-field">
                            <label for="tc-addr-country">Country *</label>
                            <select id="tc-addr-country" name="country" required>
                                <option value="">Select country</option>
                                <?php foreach ( ( $countries ?? [] ) as $c ) : ?>
                                    <option value="<?php echo esc_attr( $c['code'] ); ?>"><?php echo esc_html( $c['name'] ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="tc-field"><label for="tc-addr-phone">Phone</label><input type="tel" id="tc-addr-phone" name="phone"></div>
                    <div class="tc-field">
                        <label for="tc-addr-type">Address type</label>
                        <select id="tc-addr-type" name="type">
                            <option value="shipping">Shipping</option>
                            <option value="billing">Billing</option>
                        </select>
                    </div>
                    <div class="tc-modal__foot">
                        <button type="button" class="tc-btn tc-btn--outline" id="tc-address-modal-cancel">Cancel</button>
                        <button type="submit" class="tc-btn tc-btn--primary">Save Address</button>
                    </div>
                </form>
            </div>
        </div>

    <?php
    // ══════════════════════════════════════════════════════════════════════
    //  SECTION: Profile
    // ══════════════════════════════════════════════════════════════════════
    elseif ( $section === 'profile' ) :
    ?>
        <div class="tc-profile">
            <h2 class="tc-profile__title">My Profile</h2>
            <?php if ( isset( $_GET['password_expired'] ) ) : ?>
              <div style="background:#fef3c7;border:1px solid #d97706;color:#92400e;padding:12px 16px;border-radius:8px;margin-bottom:16px;font-size:14px">
                <strong>Password update required.</strong> Your password has expired or must be changed. Please set a new password below.
              </div>
            <?php endif; ?>
            <div id="tc-profile-msg"></div>

            <div class="tc-profile__card">
                <h4>Personal Information</h4>
                <form id="tc-profile-form" class="tc-profile__form">
                    <div class="tc-field--row-2col">
                        <div class="tc-field"><label for="tc-prof-first">First name</label><input type="text" id="tc-prof-first" name="first_name" value="<?php echo esc_attr( $customer['first_name'] ?? '' ); ?>"></div>
                        <div class="tc-field"><label for="tc-prof-last">Last name</label><input type="text" id="tc-prof-last" name="last_name" value="<?php echo esc_attr( $customer['last_name'] ?? '' ); ?>"></div>
                    </div>
                    <div class="tc-field--row-2col">
                        <div class="tc-field"><label for="tc-prof-email">Email</label><input type="email" id="tc-prof-email" name="email" value="<?php echo esc_attr( $customer['email'] ?? '' ); ?>"></div>
                        <div class="tc-field"><label for="tc-prof-phone">Phone</label><input type="tel" id="tc-prof-phone" name="phone" value="<?php echo esc_attr( $customer['phone'] ?? '' ); ?>"></div>
                    </div>
                    <?php
                    // Custom (non-system) contact fields (S127.C-1). Pre-fills
                    // from tc_customer_field_values for the current customer.
                    // Wrapper + input classes match dashboard.php's form styling.
                    $_prof_fields_mgr = new \TitanCart\Modules\Accounts\CustomerFieldsManager();
                    $_prof_cf_html    = $_prof_fields_mgr->render_section_html(
                        'contact',
                        (int) ( $customer['id'] ?? 0 ),
                        'tc-prof-cf-',
                        [],
                        'tc-field',
                        ''
                    );
                    if ( $_prof_cf_html !== '' ) {
                        echo wp_kses( $_prof_cf_html, \TitanCart\Modules\Accounts\CustomerFieldsManager::form_kses_allowed() );
                    }
                    ?>
                    <button type="submit" class="tc-btn tc-btn--primary">Save Changes</button>
                </form>
            </div>

            <div class="tc-profile__card">
                <h4>Change Password</h4>
                <form id="tc-password-form" class="tc-profile__form">
                    <div class="tc-field">
                        <label for="tc-pw-current">Current password</label>
                        <div class="tc-field__pw-wrap">
                            <input type="password" id="tc-pw-current" name="current_password" autocomplete="current-password">
                            <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                        </div>
                    </div>
                    <div class="tc-field--row-2col">
                        <div class="tc-field">
                            <label for="tc-pw-new">New password</label>
                            <div class="tc-field__pw-wrap">
                                <input type="password" id="tc-pw-new" name="new_password" minlength="6" autocomplete="new-password">
                                <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                            </div>
                        </div>
                        <div class="tc-field">
                            <label for="tc-pw-confirm">Confirm new password</label>
                            <div class="tc-field__pw-wrap">
                                <input type="password" id="tc-pw-confirm" name="confirm_password" minlength="6" autocomplete="new-password">
                                <button type="button" class="tc-pw-toggle" aria-label="Show password"><i class="bi bi-eye-slash"></i></button>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="tc-btn tc-btn--primary">Update Password</button>
                </form>
            </div>

            <?php
            $tc_gdpr_active    = \TitanCart\Extensions\GdprExtension::is_active();
            $tc_allow_export   = $tc_gdpr_active && \TitanCart\Extensions\GdprExtension::allow_data_export();
            $tc_allow_delete   = \TitanCart\Services\SettingsService::bool( 'general', 'customers_show_delete_account', false )
                                 || ( $tc_gdpr_active && \TitanCart\Extensions\GdprExtension::allow_data_deletion() );
            $tc_retention_days = \TitanCart\Extensions\GdprExtension::data_retention_days();
            ?>

            <?php if ( $tc_allow_export ) : ?>
            <div class="tc-profile__card">
                <h4>Your Data</h4>
                <p style="font-size:13px;color:#737373;margin:8px 0 16px">Download a copy of the personal data we hold about you — your profile, addresses, orders, and wishlist — as a JSON file.</p>
                <button type="button" id="tc-export-data-btn" class="tc-btn tc-btn--outline">Download my data</button>
            </div>
            <?php
            // WP.org R2: inline JS is built as a PHP nowdoc (no output buffering,
            // no markup literals) and attached via wp_add_inline_script (footer stub).
            $tc_export_js = <<<'JS'
            (function(){
                var btn = document.getElementById('tc-export-data-btn');
                if (!btn) return;
                btn.addEventListener('click', function() {
                    var orig = btn.textContent;
                    btn.disabled = true; btn.textContent = 'Preparing\u2026';
                    fetch(TitancartAccount.apiUrl + '/account/export', {
                        method: 'GET',
                        headers: { 'X-WP-Nonce': TitancartAccount.nonce }
                    }).then(function(r) {
                        if (!r.ok) throw new Error('export_failed');
                        return r.json();
                    }).then(function(d) {
                        var blob = new Blob([JSON.stringify(d, null, 2)], { type: 'application/json' });
                        var url = URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = 'titancart-my-data.json';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                        btn.disabled = false; btn.textContent = orig;
                    }).catch(function() {
                        alert('Could not export your data. Please try again or contact support.');
                        btn.disabled = false; btn.textContent = orig;
                    });
                });
            })();
JS;
            wp_register_script( 'titancart-account-inline', false, array(), TITANCART_VERSION, true );
            wp_enqueue_script( 'titancart-account-inline' );
            wp_add_inline_script( 'titancart-account-inline', $tc_export_js );
            ?>
            <?php endif; ?>

            <?php if ( $tc_allow_delete ) : ?>
            <div class="tc-profile__card" style="border:1px solid rgba(220,38,38,0.35);background:rgba(220,38,38,0.08)">
                <h4 style="color:#DC2626">Delete My Account</h4>
                <p style="font-size:13px;color:#737373;margin:8px 0 16px">This deactivates your account immediately and removes your profile, addresses, wishlist, and marketing data right away. For chargeback protection and legal record-keeping, the personal details attached to your past orders are kept for <?php echo (int) $tc_retention_days; ?> days after your most recent order, then permanently erased.</p>
                <button type="button" id="tc-delete-account-btn" class="tc-btn" style="background:#DC2626;color:#fff;border:none">Delete My Account</button>
            </div>
            <?php
            // WP.org R2: NOWDOC + strtr() slot, attached via wp_add_inline_script (footer stub).
            $tc_del_home = wp_json_encode( home_url( '/' ) );
            $tc_del_js   = <<<'JS'
            (function(){
                var btn = document.getElementById('tc-delete-account-btn');
                if (!btn) return;
                btn.addEventListener('click', function() {
                    if (!confirm('Are you sure you want to delete your account? This cannot be undone.')) return;
                    if (!confirm('This will deactivate your account and remove your personal data. Continue?')) return;
                    var p = prompt('Type DELETE to confirm account deletion:');
                    if (p !== 'DELETE') return;
                    fetch(TitancartAccount.apiUrl + '/account/delete', {
                        method: 'DELETE',
                        headers: { 'X-WP-Nonce': TitancartAccount.nonce }
                    }).then(function(r) { return r.json(); }).then(function(d) {
                        if (d.deleted) {
                            var msg = 'Your account has been deleted.';
                            if (d.erase_mode === 'scheduled' && d.erase_at) {
                                msg = 'Your account has been deactivated and your personal data removed. The details on your past orders will be permanently erased on ' + String(d.erase_at).substring(0,10) + '.';
                            }
                            alert(msg);
                            window.location.href = %%HOME%%;
                        } else {
                            alert(d.message || 'Could not delete account. Please contact support.');
                        }
                    }).catch(function() { alert('Something went wrong. Please try again.'); });
                });
            })();
JS;
            $tc_del_js = strtr( $tc_del_js, [ '%%HOME%%' => $tc_del_home ] );
            wp_register_script( 'titancart-account-inline', false, array(), TITANCART_VERSION, true );
            wp_enqueue_script( 'titancart-account-inline' );
            wp_add_inline_script( 'titancart-account-inline', $tc_del_js );
            ?>
            <?php endif; ?>

        </div>

    <?php else :
        // ══════════════════════════════════════════════════════════════════════
        //  SECTION: Downloads
        // ══════════════════════════════════════════════════════════════════════
        if ( $section === 'downloads' ) :
            $dl_keys = is_array( $downloads ?? null ) ? $downloads : [];
            $dl_nonce = wp_create_nonce( 'wp_rest' );
        ?>
        <div class="tc-myorders">
            <h2 class="tc-myorders__title">Downloads</h2>
            <?php if ( ! empty( $dl_keys ) ) : ?>
            <p class="tc-myorders__sub" style="color:#71797E;font-size:13px;margin:-8px 0 16px">
                Files from your purchases. Download links expire — grab them while they're active.
            </p>
            <div class="tc-orders-table-wrap">
                <table class="tc-orders-table tc-downloads-table">
                    <thead>
                        <tr>
                            <th>File</th>
                            <th>Product</th>
                            <th>Status</th>
                            <th>Remaining</th>
                            <th>Expires</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $dl_keys as $k ) :
                            $status     = $k['status'] ?? 'active';
                            $is_active  = $status === 'active';
                            $exp_raw    = $k['expires_at'] ?? null;
                            $exp_ts     = $exp_raw ? strtotime( $exp_raw ) : 0;
                            $is_expired = $exp_ts && $exp_ts < time();

                            // Status pill colors: active=green, expired=gray, revoked=red.
                            $effective_status = ( $is_active && $is_expired ) ? 'expired' : $status;
                            $pill_color = [
                                'active'  => '#16A34A',
                                'expired' => '#71797E',
                                'revoked' => '#DC2626',
                            ][ $effective_status ] ?? '#71797E';
                            $pill_label = ucfirst( $effective_status );

                            // Remaining downloads.
                            $count = (int) ( $k['download_count'] ?? 0 );
                            $max   = $k['max_downloads'] ?? null;
                            if ( $max === null ) {
                                $remaining_label = $count . ' / ∞';
                            } else {
                                $left = max( 0, (int) $max - $count );
                                $remaining_label = $left . ' of ' . (int) $max;
                            }

                            // Expiry display.
                            if ( ! $exp_ts ) {
                                $expires_label = 'Never';
                            } elseif ( $is_expired ) {
                                $expires_label = 'Expired ' . titancart_format_date( $exp_raw );
                            } else {
                                $expires_label = titancart_format_date( $exp_raw );
                            }

                            $can_download = $is_active && ! $is_expired
                                && ( $max === null || $count < (int) $max );

                            $stream_url = rest_url( 'titancart/v1/account/downloads/key/' . (int) $k['id'] . '/stream' ); // WP.org R1 🅲: rest_url() not home_url('/wp-json/…') — also correct on sites without pretty permalinks.
                            $stream_url = add_query_arg( '_wpnonce', $dl_nonce, $stream_url );
                        ?>
                        <tr>
                            <td>
                                <div class="tc-dl-file">
                                    <i class="bi bi-file-earmark-arrow-down" style="font-size:18px;color:#2563EB;margin-right:6px"></i>
                                    <span><?php echo esc_html( $k['file_original_name'] ?? '' ); ?></span>
                                    <?php if ( ! empty( $k['file_size'] ) ) : ?>
                                        <span style="color:#71797E;font-size:12px;margin-left:8px"><?php echo esc_html( size_format( (int) $k['file_size'] ) ); ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td><?php echo esc_html( $k['product_name'] ?: '—' ); ?></td>
                            <td><span class="tc-status-dot" style="--dot:<?php echo esc_attr( $pill_color ); ?>"><?php echo esc_html( $pill_label ); ?></span></td>
                            <td style="font-variant-numeric:tabular-nums"><?php echo esc_html( $remaining_label ); ?></td>
                            <td><?php echo esc_html( $expires_label ); ?></td>
                            <td>
                                <?php if ( $can_download ) : ?>
                                    <a href="<?php echo esc_url( $stream_url ); ?>" class="tc-btn tc-btn--sm tc-btn--primary" download>
                                        <i class="bi bi-download"></i> Download
                                    </a>
                                <?php else : ?>
                                    <button type="button" class="tc-btn tc-btn--sm" disabled style="opacity:.5;cursor:not-allowed"><i class="bi bi-download"></i> Download</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else : ?>
            <div class="tc-dash__empty">
                <i class="bi bi-cloud-download" style="font-size:48px;color:#71797E;display:block;margin-bottom:12px"></i>
                <p>You don't have any downloadable files yet.</p>
                <p style="color:#71797E;font-size:13px;margin-top:-4px">When you purchase a downloadable product, your files will appear here.</p>
                <a href="<?php echo esc_url( titancart_shop_url() ); ?>" class="tc-btn tc-btn--primary">Browse Products</a>
            </div>
            <?php endif; ?>
        </div>

    <?php else :
        // Allow extensions to render custom account sections (e.g. Subscriptions).
        do_action( 'titancart_account_section', $section, $customer ?? [] );
        endif;
    endif; ?>

    </main>
</div>

<?php endif; ?>

</div><!-- #tc-account -->

<?php get_footer(); ?>
