<?php
declare(strict_types=1);
require_once '/var/www/_shared/i18n/engine.php';
$lang  = i18n_boot(__DIR__ . '/_i18n');
$h     = i18n_head('/check', 'https://gsm-security.com');

// Inject all wizard strings into JS
$wiz = json_encode([
    // Step labels (cycling progress messages)
    'step_of'         => t('wiz.step_of'),
    // S1
    's1_q_name'       => t('wiz.s1.q.name'),
    's1_f_name'       => t('wiz.s1.f.name'),
    // S2
    's2_card'         => t('wiz.s2.card'),
    's2_btc'          => t('wiz.s2.btc'),
    's2_secure'       => t('wiz.s2.secure'),
    's2_btc_note'     => t('wiz.s2.btc_note'),
    's2_email'        => t('wiz.s2.email'),
    's2_pass'         => t('wiz.s2.pass'),
    's2_do_signin'    => t('wiz.s2.do_signin'),
    's2_create'       => t('wiz.s2.create'),
    's2_amount'       => t('wiz.s2.amount'),
    // S3
    's3_format_err'   => t('wiz.s3.format_err'),
    // S4 probe messages
    's4_p'            => [t('wiz.s4.p1'), t('wiz.s4.p2'), t('wiz.s4.p3'), t('wiz.s4.p4'), t('wiz.s4.p5')],
    // Results
    'r_safe_label'    => t('wiz.r.safe.label'),
    'r_safe_short'    => t('wiz.r.safe.short'),
    'r_safe_long1'    => t('wiz.r.safe.long1'),
    'r_safe_long2'    => t('wiz.r.safe.long2'),
    'r_safe_expand'   => t('wiz.r.safe.expand'),
    'r_med_label'     => t('wiz.r.med.label'),
    'r_med_short'     => t('wiz.r.med.short'),
    'r_med_long1'     => t('wiz.r.med.long1'),
    'r_med_long2'     => t('wiz.r.med.long2'),
    'r_med_expand'    => t('wiz.r.med.expand'),
    'r_med_cta'       => t('wiz.r.med.cta'),
    'r_med_cta2'      => t('wiz.r.med.cta2'),
    'r_high_label'    => t('wiz.r.high.label'),
    'r_high_short'    => t('wiz.r.high.short'),
    'r_high_long1'    => t('wiz.r.high.long1'),
    'r_high_long2'    => t('wiz.r.high.long2'),
    'r_high_expand'   => t('wiz.r.high.expand'),
    'r_high_cta'      => t('wiz.r.high.cta'),
    'r_high_cta2'     => t('wiz.r.high.cta2'),
    'r_tmo_label'     => t('wiz.r.tmo.label'),
    'r_tmo_short'     => t('wiz.r.tmo.short'),
    'r_tmo_long1'     => t('wiz.r.tmo.long1'),
    'r_tmo_long2'     => t('wiz.r.tmo.long2'),
    'r_tmo_expand'    => t('wiz.r.tmo.expand'),
    'r_tmo_cta'       => t('wiz.r.tmo.cta'),
    'r_err_bal_label' => t('wiz.r.err.balance.label'),
    'r_err_bal_body'  => t('wiz.r.err.balance.body'),
    'r_err_bal_cta'   => t('wiz.r.err.balance.cta'),
    'r_err_sub_label' => t('wiz.r.err.sub.label'),
    'r_err_sub_body'  => t('wiz.r.err.sub.body'),
    'r_err_sub_cta'   => t('wiz.r.err.sub.cta'),
    'r_err_net_label' => t('wiz.r.err.net.label'),
    'r_err_net_body'  => t('wiz.r.err.net.body'),
    'r_err_net_cta'   => t('wiz.r.err.net.cta'),
    'r_err_gen_label' => t('wiz.r.err.generic.label'),
    'r_err_gen_body'  => t('wiz.r.err.generic.body'),
    'r_err_gen_cta'   => t('wiz.r.err.generic.cta'),
    'r_share'         => t('wiz.r.share'),
    'r_back'          => t('wiz.r.back'),
    'r_contact'       => t('wiz.r.contact'),
    'r_full_report'   => t('wiz.r.full_report'),
    // Auth / payment flow reuse strings from index.php logic
    'connecting'      => t('js.connecting'),
    'net_err'         => t('js.net_err'),
    'net_err2'        => t('js.net_err2'),
    'auth_signing_in' => t('js.auth.signing_in'),
    'auth_creating'   => t('js.auth.creating'),
    'auth_failed'     => t('js.auth.failed'),
    'btc_creating'    => t('js.btc_creating'),
    'btc_failed'      => t('js.btc_failed'),
    'checkout_start'  => t('js.checkout_start'),
    'checkout_failed' => t('js.checkout_failed'),
    'balance_prefix'  => t('js.balance_prefix'),
    'balance_suffix'  => t('js.balance_suffix'),
    'sub_info'        => t('js.sub_info'),
    'preflight_ok'    => t('js.preflight_ok'),
    'submitting'      => t('js.submitting'),
    'preflight_timeout' => t('js.preflight_timeout'),
    'net_probe_err'   => t('js.net_probe_err'),
    'check_failed'    => t('js.check_failed'),
    // check detail labels for result
    'check_routing'      => t('js.check.routing'),
    'check_identity'     => t('js.check.identity'),
    'check_bypass'       => t('js.check.bypass'),
    'check_home_routing' => t('js.check.home_routing'),
    'check_network'      => t('js.check.network'),
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);
?>
<!doctype html>
<html lang="<?= $h['lang'] ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars(t('wiz.title'), ENT_QUOTES) ?></title>
<meta name="description" content="<?= htmlspecialchars(t('wiz.meta'), ENT_QUOTES) ?>">
<meta name="robots" content="index, follow">
<?= $h['hreflang'] ?>
<meta property="og:type" content="website">
<meta property="og:url" content="<?= htmlspecialchars($h['canonical'], ENT_QUOTES) ?>">
<meta property="og:title" content="<?= htmlspecialchars(t('wiz.title'), ENT_QUOTES) ?>">
<meta property="og:description" content="<?= htmlspecialchars(t('wiz.meta'), ENT_QUOTES) ?>">
<meta property="og:site_name" content="GSM Security">
<meta property="og:locale" content="<?= $h['og_locale'] ?>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --bg:       #0B0F17;
  --surface:  #131926;
  --surface2: #1a2338;
  --accent:   #06B6D4;
  --accent-hi:#22D3EE;
  --text:     #F8FAFC;
  --muted:    #94A3B8;
  --dim:      #64748B;
  --border:   rgba(255,255,255,0.06);
  --border-hi:rgba(6,182,212,0.4);
  --red:      #F87171;
  --amber:    #FBBF24;
  --green:    #34D399;
  --font:     'Inter',system-ui,-apple-system,sans-serif;
  --radius:   12px;
  --max:      480px;
}
html,body{min-height:100%;background:var(--bg);color:var(--text);font-family:var(--font);-webkit-font-smoothing:antialiased}
a{color:var(--accent);text-decoration:none}
a:hover{color:var(--accent-hi)}

/* ── Layout ── */
.wiz-wrap{min-height:100vh;display:flex;flex-direction:column;align-items:center;padding:0 20px 60px}
.wiz-nav{width:100%;max-width:var(--max);padding:24px 0 0;display:flex;align-items:center;justify-content:space-between}
.wiz-logo{font-size:15px;font-weight:600;color:var(--text);letter-spacing:-.2px}
.wiz-logo span{color:var(--accent)}
.wiz-back{font-size:13px;color:var(--dim)}
.wiz-back:hover{color:var(--muted)}

/* ── Progress dots ── */
.wiz-progress{display:flex;align-items:center;gap:6px;margin:32px 0 0;width:100%;max-width:var(--max)}
.prog-dot{width:8px;height:8px;border-radius:50%;background:var(--surface2);transition:.2s}
.prog-dot.done{background:var(--accent)}
.prog-dot.active{background:transparent;box-shadow:0 0 0 2px var(--accent);width:10px;height:10px}
.prog-line{flex:1;height:1px;background:var(--border);transition:.2s}
.prog-line.done{background:rgba(6,182,212,.35)}
.prog-label{font-size:11px;color:var(--dim);margin-top:8px;margin-bottom:24px;width:100%;max-width:var(--max)}

/* ── Card ── */
.wiz-card{width:100%;max-width:var(--max);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:32px}

/* ── Typography ── */
.wiz-h1{font-size:21px;font-weight:700;letter-spacing:-.4px;margin-bottom:8px;line-height:1.25}
.wiz-sub{font-size:14px;color:var(--muted);line-height:1.6;margin-bottom:28px}

/* ── Tier cards ── */
.tier-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:24px}
@media(max-width:420px){.tier-grid{grid-template-columns:1fr}}
.tier-card{border:1px solid var(--border);border-radius:10px;padding:20px 16px;cursor:pointer;transition:.15s;position:relative;display:flex;flex-direction:column}
.tier-card:hover{border-color:var(--border-hi);background:var(--surface2)}
.tier-card.featured{border-color:rgba(6,182,212,.25);background:rgba(6,182,212,.04)}
.tier-badge{font-size:10px;font-weight:700;color:var(--accent);letter-spacing:.5px;text-transform:uppercase;margin-bottom:8px}
.tier-price{font-size:28px;font-weight:700;color:var(--text);line-height:1;margin-bottom:2px}
.tier-unit{font-size:12px;color:var(--dim);margin-bottom:12px}
.tier-name{font-size:13px;font-weight:600;color:var(--muted);margin-bottom:12px}
.tier-bullets{list-style:none;display:flex;flex-direction:column;gap:6px;margin-bottom:16px;flex:1}
.tier-bullets li{font-size:12.5px;color:var(--muted);line-height:1.45;padding-left:18px;position:relative}
.tier-bullets li::before{content:'';position:absolute;left:0;top:6px;width:6px;height:6px;border-radius:50%;background:var(--accent);opacity:.7}
.tier-btn{width:100%;padding:11px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;transition:.15s;border:none;font-family:var(--font)}
.tier-btn-primary{background:var(--accent);color:#0B0F17}
.tier-btn-primary:hover{background:var(--accent-hi)}
.tier-btn-secondary{background:transparent;border:1px solid var(--border-hi);color:var(--accent)}
.tier-btn-secondary:hover{background:rgba(6,182,212,.08)}
.tier-already{font-size:12.5px;color:var(--dim);text-align:center}
.tier-already a{color:var(--accent)}

/* ── Payment step ── */
.pay-summary{background:var(--surface2);border-radius:8px;padding:14px 16px;margin-bottom:20px;font-size:13px}
.pay-summary-label{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
.pay-summary-value{font-size:15px;font-weight:600}
.pay-btns{display:flex;flex-direction:column;gap:10px;margin-bottom:16px}
.pay-secure{font-size:11.5px;color:var(--dim);text-align:center;line-height:1.5}
.pay-change{display:inline-block;font-size:12px;color:var(--dim);margin-top:12px;cursor:pointer}
.pay-change:hover{color:var(--muted)}

/* ── Auth section within payment step ── */
.auth-divider{display:flex;align-items:center;gap:10px;margin:20px 0}
.auth-divider::before,.auth-divider::after{content:'';flex:1;height:1px;background:var(--border)}
.auth-divider span{font-size:11px;color:var(--dim)}
.auth-section{margin-top:4px}
.auth-section-title{font-size:13px;font-weight:600;margin-bottom:4px}
.auth-section-sub{font-size:12px;color:var(--dim);margin-bottom:14px}

/* ── Form elements ── */
.wiz-label{display:block;font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.4px;margin-bottom:6px;margin-top:14px}
.wiz-label:first-child{margin-top:0}
.wiz-input{width:100%;padding:13px 14px;background:var(--surface2);border:1px solid var(--border);border-radius:8px;font-size:16px;color:var(--text);font-family:var(--font);outline:none;transition:.15s;-webkit-appearance:none}
.wiz-input:focus{border-color:var(--border-hi);background:#1e2d46}
.wiz-input::placeholder{color:var(--dim)}
select.wiz-input{font-size:14px;cursor:pointer}
.wiz-privacy{font-size:12px;color:var(--dim);line-height:1.55;margin-top:12px;padding:10px 12px;background:rgba(255,255,255,.025);border-radius:6px;border-left:2px solid var(--border)}
.wiz-msg{font-size:13px;min-height:18px;margin:10px 0 4px;line-height:1.4}
.wiz-msg.error{color:var(--red)}
.wiz-msg.info{color:var(--accent)}

/* ── Buttons ── */
.btn-primary{width:100%;padding:14px;background:var(--accent);color:#0B0F17;font-size:14px;font-weight:700;border:none;border-radius:8px;cursor:pointer;font-family:var(--font);transition:.15s;margin-top:4px}
.btn-primary:hover{background:var(--accent-hi)}
.btn-primary:disabled{opacity:.5;cursor:not-allowed}
.btn-outline{width:100%;padding:13px;background:transparent;color:var(--accent);font-size:13px;font-weight:600;border:1px solid var(--border-hi);border-radius:8px;cursor:pointer;font-family:var(--font);transition:.15s}
.btn-outline:hover{background:rgba(6,182,212,.08)}
.btn-ghost{background:none;border:none;color:var(--dim);font-size:12.5px;cursor:pointer;font-family:var(--font);padding:8px 0;text-align:center;width:100%;margin-top:4px}
.btn-ghost:hover{color:var(--muted)}

/* ── Running step ── */
.run-spinner{display:block;width:40px;height:40px;border:3px solid rgba(6,182,212,.2);border-top-color:var(--accent);border-radius:50%;animation:spin 1s linear infinite;margin:0 auto 20px}
@keyframes spin{to{transform:rotate(360deg)}}
.run-status{font-size:14px;color:var(--muted);text-align:center;min-height:20px;margin-bottom:12px}
.run-log{display:flex;flex-direction:column;gap:4px;margin:0 auto;max-width:340px}
.run-log-item{font-size:12px;color:var(--dim);padding:3px 0;display:flex;align-items:center;gap:8px}
.run-log-item::before{content:'✓';color:var(--accent);font-size:11px;flex-shrink:0}

/* ── Result step ── */
.result-icon{width:48px;height:48px;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 16px}
.result-icon.safe{background:rgba(52,211,153,.12)}
.result-icon.medium{background:rgba(251,191,36,.12)}
.result-icon.high{background:rgba(248,113,113,.12)}
.result-icon.timeout{background:rgba(148,163,184,.1)}
.result-icon.error{background:rgba(248,113,113,.08)}
.result-heading{font-size:19px;font-weight:700;text-align:center;margin-bottom:8px;line-height:1.25}
.result-heading.safe{color:var(--green)}
.result-heading.medium{color:var(--amber)}
.result-heading.high{color:var(--red)}
.result-heading.timeout{color:var(--muted)}
.result-heading.error{color:var(--red)}
.result-short{font-size:13.5px;color:var(--muted);text-align:center;line-height:1.6;margin-bottom:20px}
.result-divider{height:1px;background:var(--border);margin:20px 0}
.result-accordion summary{font-size:13px;font-weight:600;color:var(--accent);cursor:pointer;list-style:none;padding:10px 0;display:flex;align-items:center;gap:6px;user-select:none}
.result-accordion summary::-webkit-details-marker{display:none}
.result-accordion summary::after{content:'›';transition:.2s;display:inline-block;margin-left:auto;opacity:.6}
.result-accordion[open] summary::after{transform:rotate(90deg)}
.result-accordion-body{font-size:13px;color:var(--muted);line-height:1.7;padding-bottom:8px}
.result-accordion-body p+p{margin-top:10px}
.result-checks{list-style:none;display:flex;flex-direction:column;gap:6px;margin:16px 0}
.result-checks li{font-size:12.5px;display:flex;align-items:center;gap:10px;color:var(--muted)}
.result-checks li .chk-icon{width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:10px;font-weight:700}
.chk-icon.bad{background:rgba(248,113,113,.15);color:var(--red)}
.chk-icon.good{background:rgba(52,211,153,.12);color:var(--green)}
.chk-icon.neutral{background:rgba(100,116,139,.15);color:var(--dim)}
.result-meta{font-size:11px;color:var(--dim);margin-top:10px;padding:8px 10px;background:rgba(255,255,255,.025);border-radius:6px}
.result-actions{display:flex;flex-direction:column;gap:8px;margin-top:20px}
.result-actions .btn-primary,.result-actions .btn-outline,.result-actions .btn-ghost{margin-top:0}

/* ── Deposit inline section ── */
.deposit-row{display:flex;gap:8px;margin-top:8px}
.deposit-row .wiz-input{margin-top:0;flex:1}
.deposit-row .btn-inline{padding:13px 16px;background:var(--accent);color:#0B0F17;border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;font-family:var(--font);white-space:nowrap;flex-shrink:0}
.deposit-row .btn-inline:hover{background:var(--accent-hi)}

/* ── Steps visibility ── */
.wiz-step{display:none}
.wiz-step.active{display:block}
</style>
</head>
<body>
<div class="wiz-wrap">

  <!-- Nav -->
  <nav class="wiz-nav" aria-label="wizard navigation">
    <a class="wiz-logo" href="/">GSM<span>Security</span></a>
    <a class="wiz-back" href="/"><?= htmlspecialchars(t('wiz.back_home'), ENT_QUOTES) ?></a>
  </nav>

  <!-- Progress -->
  <div class="wiz-progress" id="wiz-progress" role="progressbar" aria-valuemin="1" aria-valuemax="4" aria-valuenow="1">
    <div class="prog-dot active" id="pd1"></div>
    <div class="prog-line" id="pl1"></div>
    <div class="prog-dot" id="pd2"></div>
    <div class="prog-line" id="pl2"></div>
    <div class="prog-dot" id="pd3"></div>
    <div class="prog-line" id="pl3"></div>
    <div class="prog-dot" id="pd4"></div>
  </div>
  <p class="prog-label" id="prog-label"><?= sprintf(htmlspecialchars(t('wiz.step_of'), ENT_QUOTES), 1) ?></p>

  <!-- ── Step 1: Choose tier ── -->
  <section class="wiz-step active" id="step-tier" role="group" aria-label="step 1 choose tier">
    <div class="wiz-card">
      <h1 class="wiz-h1"><?= htmlspecialchars(t('wiz.s1.title'), ENT_QUOTES) ?></h1>
      <p class="wiz-sub"><?= htmlspecialchars(t('wiz.s1.sub'), ENT_QUOTES) ?></p>
      <div class="tier-grid">

        <div class="tier-card" onclick="pickTier('quick')">
          <div class="tier-price"><?= htmlspecialchars(t('wiz.s1.q.price'), ENT_QUOTES) ?></div>
          <div class="tier-unit"><?= htmlspecialchars(t('wiz.s1.q.unit'), ENT_QUOTES) ?></div>
          <div class="tier-name"><?= htmlspecialchars(t('wiz.s1.q.name'), ENT_QUOTES) ?></div>
          <ul class="tier-bullets">
            <li><?= htmlspecialchars(t('wiz.s1.q.b1'), ENT_QUOTES) ?></li>
            <li><?= htmlspecialchars(t('wiz.s1.q.b2'), ENT_QUOTES) ?></li>
            <li><?= htmlspecialchars(t('wiz.s1.q.b3'), ENT_QUOTES) ?></li>
          </ul>
          <button class="tier-btn tier-btn-secondary" type="button"><?= htmlspecialchars(t('wiz.s1.q.btn'), ENT_QUOTES) ?></button>
        </div>

        <div class="tier-card featured" onclick="pickTier('full')">
          <div class="tier-badge"><?= htmlspecialchars(t('wiz.s1.f.badge'), ENT_QUOTES) ?></div>
          <div class="tier-price"><?= htmlspecialchars(t('wiz.s1.f.price'), ENT_QUOTES) ?></div>
          <div class="tier-unit"><?= htmlspecialchars(t('wiz.s1.f.unit'), ENT_QUOTES) ?></div>
          <div class="tier-name"><?= htmlspecialchars(t('wiz.s1.f.name'), ENT_QUOTES) ?></div>
          <ul class="tier-bullets">
            <li><?= htmlspecialchars(t('wiz.s1.f.b1'), ENT_QUOTES) ?></li>
            <li><?= htmlspecialchars(t('wiz.s1.f.b2'), ENT_QUOTES) ?></li>
            <li><?= htmlspecialchars(t('wiz.s1.f.b3'), ENT_QUOTES) ?></li>
          </ul>
          <button class="tier-btn tier-btn-primary" type="button"><?= htmlspecialchars(t('wiz.s1.f.btn'), ENT_QUOTES) ?></button>
        </div>

      </div>
      <p class="tier-already"><?= htmlspecialchars(t('wiz.s1.already'), ENT_QUOTES) ?> <a href="#" onclick="pickTier('quick');return false;"><?= htmlspecialchars(t('wiz.s1.signin'), ENT_QUOTES) ?></a></p>
    </div>
  </section>

  <!-- ── Step 2: Auth / Payment ── -->
  <section class="wiz-step" id="step-pay" role="group" aria-label="step 2 payment">
    <div class="wiz-card">
      <h1 class="wiz-h1" id="s2-title"><?= htmlspecialchars(t('wiz.s2.title'), ENT_QUOTES) ?></h1>
      <p class="wiz-sub" id="s2-sub"></p>

      <!-- Signed-in with balance: nothing to do, auto-advance -->

      <!-- Not signed in: sign in / create account -->
      <div id="s2-auth" style="display:none">
        <div class="auth-section">
          <div class="auth-section-title" id="s2-auth-title"><?= htmlspecialchars(t('wiz.s2.signin.title'), ENT_QUOTES) ?></div>
          <div class="auth-section-sub"><?= htmlspecialchars(t('wiz.s2.signin.sub'), ENT_QUOTES) ?></div>
          <label class="wiz-label" for="s2-email"><?= htmlspecialchars(t('wiz.s2.email'), ENT_QUOTES) ?></label>
          <input type="email" class="wiz-input" id="s2-email" autocomplete="email" inputmode="email">
          <label class="wiz-label" for="s2-pass"><?= htmlspecialchars(t('wiz.s2.pass'), ENT_QUOTES) ?></label>
          <input type="password" class="wiz-input" id="s2-pass" autocomplete="current-password" onkeydown="if(event.key==='Enter')doWizAuth('login')">
          <div class="wiz-msg" id="s2-auth-msg"></div>
          <button class="btn-primary" type="button" onclick="doWizAuth('login')"><?= htmlspecialchars(t('wiz.s2.do_signin'), ENT_QUOTES) ?></button>
          <button class="btn-ghost" type="button" onclick="doWizAuth('signup')"><?= htmlspecialchars(t('wiz.s2.create'), ENT_QUOTES) ?></button>
        </div>
      </div>

      <!-- Signed in, need deposit -->
      <div id="s2-deposit" style="display:none">
        <div class="pay-summary">
          <div class="pay-summary-label"><?= htmlspecialchars(t('wiz.s2.deposit.title'), ENT_QUOTES) ?></div>
          <div class="pay-summary-sub" id="s2-deposit-sub" style="font-size:12px;color:var(--muted);margin-top:4px"><?= htmlspecialchars(t('wiz.s2.deposit.sub'), ENT_QUOTES) ?></div>
          <div id="s2-bal-info" style="font-size:12px;color:var(--dim);margin-top:6px"></div>
        </div>
        <label class="wiz-label" for="s2-deposit-amt"><?= htmlspecialchars(t('wiz.s2.amount'), ENT_QUOTES) ?></label>
        <div class="deposit-row">
          <input type="number" class="wiz-input" id="s2-deposit-amt" value="10" min="5" step="1">
          <button class="btn-inline" type="button" onclick="doWizDeposit('card')"><?= htmlspecialchars(t('wiz.s2.card'), ENT_QUOTES) ?></button>
        </div>
        <div class="wiz-msg" id="s2-deposit-msg"></div>
        <button class="btn-outline" type="button" style="margin-top:10px" onclick="doWizDeposit('btc')"><?= htmlspecialchars(t('wiz.s2.btc'), ENT_QUOTES) ?></button>
        <p class="pay-secure" style="margin-top:12px"><?= htmlspecialchars(t('wiz.s2.secure'), ENT_QUOTES) ?></p>
      </div>

      <!-- Signed in, need subscription -->
      <div id="s2-sub" style="display:none">
        <div class="pay-summary">
          <div class="pay-summary-label"><?= htmlspecialchars(t('wiz.s1.f.name'), ENT_QUOTES) ?></div>
          <div class="pay-summary-value" id="s2-sub-price">€45 / <?= htmlspecialchars(t('wiz.s1.f.unit'), ENT_QUOTES) ?></div>
        </div>
        <div class="pay-btns">
          <button class="btn-primary" type="button" onclick="doWizSubscribe('card')"><?= htmlspecialchars(t('wiz.s2.card'), ENT_QUOTES) ?></button>
          <button class="btn-outline" type="button" onclick="doWizSubscribe('btc')"><?= htmlspecialchars(t('wiz.s2.btc'), ENT_QUOTES) ?></button>
        </div>
        <div class="wiz-msg" id="s2-sub-msg"></div>
        <p class="pay-secure"><?= htmlspecialchars(t('wiz.s2.secure'), ENT_QUOTES) ?></p>
      </div>

      <a href="#" class="pay-change" id="s2-change" onclick="goWizStep('tier');return false;">← <?= htmlspecialchars(t('wiz.s2.change'), ENT_QUOTES) ?></a>
    </div>
  </section>

  <!-- ── Step 3: Enter number ── -->
  <section class="wiz-step" id="step-number" role="group" aria-label="step 3 enter number">
    <div class="wiz-card">
      <h1 class="wiz-h1"><?= htmlspecialchars(t('wiz.s3.title'), ENT_QUOTES) ?></h1>
      <p class="wiz-sub"><?= htmlspecialchars(t('wiz.s3.sub'), ENT_QUOTES) ?></p>

      <label class="wiz-label" for="s3-country"><?= htmlspecialchars(t('wiz.s3.country'), ENT_QUOTES) ?></label>
      <select class="wiz-input" id="s3-country" onchange="applyCountryPrefix()">
        <option value="">—</option>
        <option value="+45">🇩🇰 Denmark (+45)</option>
        <option value="+46">🇸🇪 Sweden (+46)</option>
        <option value="+47">🇳🇴 Norway (+47)</option>
        <option value="+49">🇩🇪 Germany (+49)</option>
        <option value="+44">🇬🇧 United Kingdom (+44)</option>
        <option value="+1">🇺🇸 United States (+1)</option>
        <option value="+33">🇫🇷 France (+33)</option>
        <option value="+31">🇳🇱 Netherlands (+31)</option>
        <option value="+34">🇪🇸 Spain (+34)</option>
        <option value="+39">🇮🇹 Italy (+39)</option>
        <option value="+358">🇫🇮 Finland (+358)</option>
        <option value="+41">🇨🇭 Switzerland (+41)</option>
        <option value="+43">🇦🇹 Austria (+43)</option>
        <option value="+32">🇧🇪 Belgium (+32)</option>
        <option value="+351">🇵🇹 Portugal (+351)</option>
        <option value="+48">🇵🇱 Poland (+48)</option>
        <option value="+61">🇦🇺 Australia (+61)</option>
        <option value="+81">🇯🇵 Japan (+81)</option>
        <option value="+82">🇰🇷 South Korea (+82)</option>
        <option value="+86">🇨🇳 China (+86)</option>
        <option value="+91">🇮🇳 India (+91)</option>
        <option value="+971">🇦🇪 UAE (+971)</option>
        <option value="+966">🇸🇦 Saudi Arabia (+966)</option>
        <option value="+65">🇸🇬 Singapore (+65)</option>
        <option value="+852">🇭🇰 Hong Kong (+852)</option>
        <option value="+7">🇷🇺 Russia (+7)</option>
        <option value="+55">🇧🇷 Brazil (+55)</option>
        <option value="+52">🇲🇽 Mexico (+52)</option>
        <option value="+27">🇿🇦 South Africa (+27)</option>
        <option value="+234">🇳🇬 Nigeria (+234)</option>
        <option value="+20">🇪🇬 Egypt (+20)</option>
        <option value="+62">🇮🇩 Indonesia (+62)</option>
      </select>

      <label class="wiz-label" for="s3-phone" style="margin-top:14px"><?= htmlspecialchars(t('wiz.s3.label'), ENT_QUOTES) ?></label>
      <input type="tel" class="wiz-input" id="s3-phone" placeholder="<?= htmlspecialchars(t('wiz.s3.placeholder'), ENT_QUOTES) ?>" autocomplete="tel" inputmode="tel">
      <div class="wiz-msg" id="s3-msg"></div>
      <button class="btn-primary" type="button" onclick="submitWizPhone()" style="margin-top:12px"><?= htmlspecialchars(t('wiz.s3.run'), ENT_QUOTES) ?></button>
      <div class="wiz-privacy"><?= htmlspecialchars(t('wiz.s3.privacy'), ENT_QUOTES) ?></div>
    </div>
  </section>

  <!-- ── Step 4: Running ── -->
  <section class="wiz-step" id="step-running" role="group" aria-label="step 4 running check">
    <div class="wiz-card" style="text-align:center;padding:40px 32px">
      <span class="run-spinner"></span>
      <h1 class="wiz-h1" style="font-size:18px"><?= htmlspecialchars(t('wiz.s4.title'), ENT_QUOTES) ?></h1>
      <p class="wiz-sub" style="margin-bottom:24px"><?= htmlspecialchars(t('wiz.s4.sub'), ENT_QUOTES) ?></p>
      <p class="run-status" id="run-status-wiz"></p>
      <div class="run-log" id="run-log-wiz"></div>
    </div>
  </section>

  <!-- ── Step 5: Result ── -->
  <section class="wiz-step" id="step-result" role="group" aria-label="step 5 result">
    <div class="wiz-card" id="result-card">
      <!-- Populated dynamically -->
    </div>
  </section>

</div><!-- /wiz-wrap -->

<!-- ── JavaScript ── -->
<script>
var _w = <?= $wiz ?>;
var PORTAL = 'https://lbs-int.com';
var NANO_PER_LOOKUP = 10000000;
var MIN_DEPOSIT = 5;

var WS = {
  tier:   'quick',
  msisdn: '',
  csrf:   '',
  me:     null,
  portalToken: ''
};

// ── Navigation ────────────────────────────────────────────────────────────────

var STEPS = ['tier','pay','number','running','result'];
var STEP_NUMS = {tier:1, pay:2, number:3, running:4};

function goWizStep(name) {
  STEPS.forEach(function(s) {
    var el = document.getElementById('step-' + s);
    if (el) el.classList.toggle('active', s === name);
  });
  var prog = document.getElementById('wiz-progress');
  var label = document.getElementById('prog-label');
  var n = STEP_NUMS[name];
  if (n) {
    prog.style.display = 'flex';
    label.style.display = 'block';
    prog.setAttribute('aria-valuenow', n);
    label.textContent = _w.step_of.replace('%d', n);
    for (var i = 1; i <= 4; i++) {
      var dot  = document.getElementById('pd' + i);
      var line = document.getElementById('pl' + i);
      if (dot) {
        dot.className = 'prog-dot' + (i < n ? ' done' : i === n ? ' active' : '');
      }
      if (line) {
        line.className = 'prog-line' + (i < n ? ' done' : '');
      }
    }
  } else {
    // result step — hide progress
    prog.style.display = 'none';
    label.style.display = 'none';
  }
}

// ── Step 1: tier selection ─────────────────────────────────────────────────

function pickTier(tier) {
  WS.tier = tier;
  // Check auth/balance first
  var msg = document.getElementById('prog-label');
  goWizStep('pay');
  getWizMe().then(function(j) {
    if (!j.signed_in) {
      showPayStep('auth');
      return;
    }
    checkWizBalance();
  }).catch(function() {
    showPayStep('auth');
  });
}

// ── Auth / me ─────────────────────────────────────────────────────────────

function apiFetch(url, data) {
  return fetch(url, {
    method: 'POST', credentials: 'include', cache: 'no-store',
    headers: {'Content-Type':'application/json','Accept':'application/json'},
    body: JSON.stringify(data)
  }).then(function(r) { return r.json().then(function(j) { j._status = r.status; return j; }); });
}

function getWizMe() {
  return fetch(PORTAL + '/portal/me.php', {credentials:'include', cache:'no-store'})
    .then(function(r) { return r.json(); })
    .then(function(j) {
      WS.csrf        = j.csrf         || '';
      WS.portalToken = j.portal_token || '';
      WS.me          = j.signed_in ? j : null;
      return j;
    });
}

function hasBalance()   { return WS.me && WS.me.user && (WS.me.user.balance_nano || 0) >= NANO_PER_LOOKUP; }
function hasUnlimited() { return WS.me && WS.me.user && WS.me.user.hlr_unlimited_active; }

function checkWizBalance() {
  if (WS.tier === 'full') {
    if (!hasUnlimited()) { showPayStep('sub'); return; }
  } else {
    if (!hasBalance()) { showPayStep('deposit'); return; }
  }
  // Already cleared — skip to number entry
  goWizStep('number');
}

function showPayStep(type) {
  var auth    = document.getElementById('s2-auth');
  var deposit = document.getElementById('s2-deposit');
  var subSec  = document.getElementById('s2-sub');
  auth.style.display    = 'none';
  deposit.style.display = 'none';
  subSec.style.display  = 'none';

  var sub = document.getElementById('s2-sub-desc');
  var tierName = WS.tier === 'full' ? _w.s1_f_name : _w.s1_q_name;
  document.getElementById('s2-sub').style.display = 'none';

  if (type === 'auth') {
    auth.style.display = 'block';
    document.getElementById('s2-email').focus();
  } else if (type === 'deposit') {
    deposit.style.display = 'block';
    var bal = WS.me && WS.me.user ? (WS.me.user.balance_eur || 0).toFixed(2) : '0.00';
    document.getElementById('s2-bal-info').textContent = _w.balance_prefix + bal + _w.balance_suffix;
  } else if (type === 'sub') {
    subSec.style.display = 'block';
  }
}

function setWizMsg(id, text, cls) {
  var el = document.getElementById(id);
  if (!el) return;
  el.textContent = text;
  el.className = 'wiz-msg ' + (cls || '');
}
function clearWizMsg(id) { setWizMsg(id, '', ''); }

function doWizAuth(mode) {
  var email = document.getElementById('s2-email').value.trim();
  var pass  = document.getElementById('s2-pass').value;
  if (!email || !pass) { setWizMsg('s2-auth-msg', _w.auth_failed, 'error'); return; }
  setWizMsg('s2-auth-msg', mode === 'login' ? _w.auth_signing_in : _w.auth_creating, 'info');
  apiFetch(PORTAL + '/portal/quick-auth.php', {mode:mode, email:email, password:pass, csrf:WS.csrf})
    .then(function(j) {
      if (!j.ok) { setWizMsg('s2-auth-msg', j.message || j.error || _w.auth_failed, 'error'); return; }
      WS.csrf = j.csrf || WS.csrf;
      return getWizMe().then(function() {
        clearWizMsg('s2-auth-msg');
        checkWizBalance();
      });
    })
    .catch(function() { setWizMsg('s2-auth-msg', _w.net_err2, 'error'); });
}

function retWizUrl(tag) {
  return location.href.split('?')[0] + '?gsc_return=' + tag + '&gsc_msisdn=' + encodeURIComponent(WS.msisdn) + '&gsc_tier=' + WS.tier;
}

function doWizDeposit(method) {
  var amt = parseFloat(document.getElementById('s2-deposit-amt').value) || MIN_DEPOSIT;
  if (amt < MIN_DEPOSIT) amt = MIN_DEPOSIT;
  if (method === 'btc') {
    setWizMsg('s2-deposit-msg', _w.btc_creating, 'info');
    apiFetch(PORTAL + '/portal/start-btc-deposit.php', {amount_eur:amt, csrf:WS.csrf})
      .then(function(j) {
        if (!j.ok || !j.url) { setWizMsg('s2-deposit-msg', j.message || j.error || _w.btc_failed, 'error'); return; }
        var url = String(j.url || '');
        if (url.startsWith('/')) url = PORTAL + url;
        location.href = url;
      }).catch(function() { setWizMsg('s2-deposit-msg', _w.net_err2, 'error'); });
    return;
  }
  setWizMsg('s2-deposit-msg', _w.checkout_start, 'info');
  apiFetch(PORTAL + '/portal/start-deposit.php', {amount_eur:amt, csrf:WS.csrf, external_return_url:retWizUrl('deposit')})
    .then(function(j) {
      if (!j.ok) { setWizMsg('s2-deposit-msg', j.message || j.error || _w.checkout_failed, 'error'); return; }
      location.href = j.url;
    }).catch(function() { setWizMsg('s2-deposit-msg', _w.net_err2, 'error'); });
}

function doWizSubscribe(method) {
  if (method === 'btc') {
    setWizMsg('s2-sub-msg', _w.btc_creating, 'info');
    apiFetch(PORTAL + '/portal/start-hlr-personal-subscription-btc.php', {csrf:WS.csrf})
      .then(function(j) {
        if (!j.ok || !j.url) { setWizMsg('s2-sub-msg', j.message || j.error || _w.btc_failed, 'error'); return; }
        location.href = j.url;
      }).catch(function() { setWizMsg('s2-sub-msg', _w.net_err2, 'error'); });
    return;
  }
  setWizMsg('s2-sub-msg', _w.checkout_start, 'info');
  apiFetch(PORTAL + '/portal/start-hlr-personal-subscription.php', {csrf:WS.csrf, external_return_url:retWizUrl('sub')})
    .then(function(j) {
      if (!j.ok) { setWizMsg('s2-sub-msg', j.message || j.error || _w.checkout_failed, 'error'); return; }
      location.href = j.url;
    }).catch(function() { setWizMsg('s2-sub-msg', _w.net_err2, 'error'); });
}

// ── Step 3: enter number ──────────────────────────────────────────────────

function applyCountryPrefix() {
  var sel = document.getElementById('s3-country');
  var inp = document.getElementById('s3-phone');
  var prefix = sel.value;
  if (!prefix) return;
  var cur = inp.value.trim();
  if (!cur || cur === '+') {
    inp.value = prefix + ' ';
    inp.focus();
  } else if (!cur.startsWith('+')) {
    inp.value = prefix + ' ' + cur.replace(/^\+\d+\s*/, '');
    inp.focus();
  }
}

function submitWizPhone() {
  var raw   = document.getElementById('s3-phone').value.trim();
  var phone = raw.replace(/[\s\-\(\)]/g, '');
  if (!phone.startsWith('+')) phone = '+' + phone;
  phone = phone.replace(/[^\d+]/g, '');
  if (phone.length < 8) {
    setWizMsg('s3-msg', _w.s3_format_err, 'error');
    return;
  }
  clearWizMsg('s3-msg');
  WS.msisdn = phone;
  runWizCheck();
}

// ── Step 4: running probe ─────────────────────────────────────────────────

function runWizCheck() {
  goWizStep('running');
  var statusEl = document.getElementById('run-status-wiz');
  var logEl    = document.getElementById('run-log-wiz');
  logEl.innerHTML = '';
  var msgs = _w.s4_p;
  var si   = 0;
  statusEl.textContent = msgs[0];
  var iv = setInterval(function() {
    if (si < msgs.length) {
      if (si > 0) {
        var item = document.createElement('div');
        item.className = 'run-log-item';
        item.textContent = msgs[si - 1];
        logEl.appendChild(item);
      }
      statusEl.textContent = msgs[si];
      si++;
    }
  }, 950);

  var body = {msisdn: WS.msisdn, mode: WS.tier === 'full' ? 'checkup' : 'quick', terms_accepted: true};
  if (WS.portalToken) body.portal_token = WS.portalToken;

  var preCtrl  = new AbortController();
  var preTimer = setTimeout(function() { preCtrl.abort(); }, 4000);

  fetch(PORTAL + '/hlr-imsi-signal-check.php', {
    method: 'POST', credentials: 'include', cache: 'no-store',
    headers: {'Content-Type':'application/json','Accept':'application/json'},
    signal: preCtrl.signal,
    body: JSON.stringify({msisdn:'00000000', mode:'quick', terms_accepted:true, preflight:true})
  })
  .then(function(r) { return r.json().catch(function() { return {}; }); })
  .then(function() {
    clearTimeout(preTimer);
    return fetch(PORTAL + '/hlr-imsi-signal-check.php', {
      method: 'POST', credentials: 'include', cache: 'no-store',
      headers: {'Content-Type':'application/json','Accept':'application/json'},
      body: JSON.stringify(body)
    });
  })
  .then(function(r) { return r.json().then(function(j) { j._status = r.status; return j; }); })
  .then(function(j) {
    clearInterval(iv);
    if (!j.ok) {
      var e = j.error || '';
      if (e === 'insufficient_balance' || e === 'low_balance' || e === 'insufficient_hlr_nano') {
        showWizErrorResult('balance'); return;
      }
      if (e === 'subscription_required_for_checkup') {
        showWizErrorResult('sub'); return;
      }
      if (e === 'probe_timeout' || e === 'session_timeout' || e === 'msisdn_unreachable' || (j.signal||'') === 'timeout') {
        showWizTimeoutResult(); return;
      }
      showWizErrorResult('generic', j.message || j.error); return;
    }
    if ((j.signal||'') === 'timeout' || (j.signal||'') === 'probe_timeout') {
      showWizTimeoutResult(); return;
    }
    showWizResult(j);
  })
  .catch(function(e) {
    clearInterval(iv);
    var isAbort = e && e.name === 'AbortError';
    showWizErrorResult('net', isAbort ? _w.preflight_timeout : _w.net_probe_err);
  });
}

// ── Step 5: result rendering ──────────────────────────────────────────────

function svgIcon(type) {
  var icons = {
    safe:    '<svg viewBox="0 0 24 24" fill="none" stroke="#34D399" stroke-width="2.5" width="24" height="24"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><polyline points="9 12 11 14 15 10"/></svg>',
    medium:  '<svg viewBox="0 0 24 24" fill="none" stroke="#FBBF24" stroke-width="2.5" width="24" height="24"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
    high:    '<svg viewBox="0 0 24 24" fill="none" stroke="#F87171" stroke-width="2.5" width="24" height="24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',
    timeout: '<svg viewBox="0 0 24 24" fill="none" stroke="#94A3B8" stroke-width="2" width="24" height="24"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>',
    error:   '<svg viewBox="0 0 24 24" fill="none" stroke="#F87171" stroke-width="2" width="24" height="24"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>'
  };
  return icons[type] || icons.error;
}

function buildResultCard(type, heading, short, long1, long2, expandLabel, actionsHtml) {
  goWizStep('result');
  document.getElementById('result-card').innerHTML =
    '<div class="result-icon ' + type + '">' + svgIcon(type) + '</div>' +
    '<h1 class="result-heading ' + type + '">' + escHtml(heading) + '</h1>' +
    '<p class="result-short">' + escHtml(short) + '</p>' +
    '<details class="result-accordion">' +
      '<summary>' + escHtml(expandLabel) + '</summary>' +
      '<div class="result-accordion-body">' +
        '<p>' + escHtml(long1) + '</p>' +
        '<p>' + escHtml(long2) + '</p>' +
      '</div>' +
    '</details>' +
    '<div class="result-divider"></div>' +
    actionsHtml;
}

function escHtml(s) {
  return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

function backBtn() {
  return '<button class="btn-ghost" onclick="goWizStep(\'tier\')">' + escHtml(_w.r_back) + '</button>';
}

function showWizResult(j) {
  var checks = j.checks || {};
  var sig    = j.signal || '';
  var hrSafe = (sig === 'home_routed_masked_imsi_safe' || sig === 'home_routed_protected') && !checks.deep_bypass_found;
  var highKeys   = ['routing_exposed','identity_traceable','bypass_possible','deep_bypass_found'];
  var highCount  = highKeys.filter(function(k) { return checks[k]; }).length;

  var type, heading, short, long1, long2, expand, actions;

  if (hrSafe) {
    type = 'safe'; heading = _w.r_safe_label; short = _w.r_safe_short;
    long1 = _w.r_safe_long1; long2 = _w.r_safe_long2; expand = _w.r_safe_expand;
    actions = backBtn();
  } else if (highCount >= 2) {
    type = 'high'; heading = _w.r_high_label; short = _w.r_high_short;
    long1 = _w.r_high_long1; long2 = _w.r_high_long2; expand = _w.r_high_expand;
    actions =
      '<div class="result-actions">' +
        '<a class="btn-primary" href="/" onclick="event.preventDefault();goWizStep(\'tier\');WS.tier=\'full\';">' + escHtml(_w.r_high_cta) + '</a>' +
        '<a class="btn-outline" href="mailto:security@lbs-int.com">' + escHtml(_w.r_high_cta2) + '</a>' +
        backBtn() +
      '</div>';
  } else if (highCount === 1) {
    type = 'medium'; heading = _w.r_med_label; short = _w.r_med_short;
    long1 = _w.r_med_long1; long2 = _w.r_med_long2; expand = _w.r_med_expand;
    actions =
      '<div class="result-actions">' +
        '<a class="btn-primary" href="/" onclick="event.preventDefault();goWizStep(\'tier\');WS.tier=\'full\';">' + escHtml(_w.r_med_cta) + '</a>' +
        backBtn() +
      '</div>';
  } else {
    type = 'safe'; heading = _w.r_safe_label; short = _w.r_safe_short;
    long1 = _w.r_safe_long1; long2 = _w.r_safe_long2; expand = _w.r_safe_expand;
    actions = backBtn();
  }

  // Build check details list
  var checkItems = [
    {key:'routing_exposed',       lbl: _w.check_routing,      bad:true},
    {key:'identity_traceable',    lbl: _w.check_identity,     bad:true},
    {key:'bypass_possible',       lbl: _w.check_bypass,       bad:true},
    {key:'home_routing_detected', lbl: _w.check_home_routing, bad:false},
    {key:'network_responded',     lbl: _w.check_network,      bad:false},
  ].filter(function(it) { return checks[it.key] != null; });

  var checksHtml = '';
  if (checkItems.length) {
    checksHtml = '<ul class="result-checks">';
    checkItems.forEach(function(it) {
      var v = checks[it.key];
      var cls = it.bad ? (v ? 'bad' : 'good') : (v ? 'good' : 'neutral');
      var icon = it.bad ? (v ? '✕' : '✓') : (v ? '✓' : '–');
      checksHtml += '<li><span class="chk-icon ' + cls + '">' + icon + '</span>' + escHtml(it.lbl) + '</li>';
    });
    checksHtml += '</ul>';
    actions = checksHtml + actions;
  }

  var meta = (j.mcc && j.mnc) ? '<div class="result-meta">MCC ' + escHtml(j.mcc) + ' · MNC ' + escHtml(j.mnc) + (j.summary ? ' · ' + escHtml(j.summary.substring(0,60)) : '') + '</div>' : '';

  buildResultCard(type, heading, short, long1, long2, expand, meta + actions);
}

function showWizTimeoutResult() {
  buildResultCard(
    'timeout', _w.r_tmo_label, _w.r_tmo_short,
    _w.r_tmo_long1, _w.r_tmo_long2, _w.r_tmo_expand,
    '<div class="result-actions">' +
      '<a class="btn-primary" href="https://lbs-int.com/contact.html" target="_blank" rel="noopener">' + escHtml(_w.r_tmo_cta) + '</a>' +
      backBtn() +
    '</div>'
  );
}

function showWizErrorResult(kind, customMsg) {
  var label, body, cta, ctaHref = '#', ctaClick = '';
  if (kind === 'balance') {
    label = _w.r_err_bal_label; body = _w.r_err_bal_body; cta = _w.r_err_bal_cta;
    ctaClick = 'onclick="goWizStep(\'pay\');showPayStep(\'deposit\');return false;"';
  } else if (kind === 'sub') {
    label = _w.r_err_sub_label; body = _w.r_err_sub_body; cta = _w.r_err_sub_cta;
    ctaClick = 'onclick="goWizStep(\'pay\');showPayStep(\'sub\');return false;"';
  } else if (kind === 'net') {
    label = _w.r_err_net_label; body = customMsg || _w.r_err_net_body; cta = _w.r_err_net_cta;
    ctaClick = 'onclick="goWizStep(\'number\');return false;"';
  } else {
    label = _w.r_err_gen_label; body = customMsg || _w.r_err_gen_body; cta = _w.r_err_gen_cta;
    ctaClick = 'onclick="goWizStep(\'number\');return false;"';
  }
  goWizStep('result');
  document.getElementById('result-card').innerHTML =
    '<div class="result-icon error">' + svgIcon('error') + '</div>' +
    '<h1 class="result-heading error">' + escHtml(label) + '</h1>' +
    '<p class="result-short">' + escHtml(body) + '</p>' +
    '<div class="result-divider"></div>' +
    '<div class="result-actions">' +
      '<a class="btn-primary" href="' + ctaHref + '" ' + ctaClick + '>' + escHtml(cta) + '</a>' +
      backBtn() +
    '</div>';
}

// ── URL return handling (after Stripe/BTC redirect) ──────────────────────

(function() {
  var sp     = new URLSearchParams(location.search);
  var ret    = sp.get('gsc_return');
  var msisdn = sp.get('gsc_msisdn');
  var tier   = sp.get('gsc_tier');
  if (!ret) {
    goWizStep('tier');
    return;
  }
  // Clean URL
  sp.delete('gsc_return'); sp.delete('gsc_msisdn'); sp.delete('gsc_tier');
  history.replaceState(null, '', location.pathname + (sp.toString() ? '?' + sp.toString() : ''));
  if (msisdn) WS.msisdn = msisdn;
  if (tier)   WS.tier   = tier;
  // Re-check session then decide where to land
  setTimeout(function() {
    getWizMe().then(function(j) {
      if (!j.signed_in) { goWizStep('tier'); return; }
      if (WS.msisdn) {
        // Has number from before payment — go run it
        checkWizBalanceAndRun();
      } else {
        checkWizBalance();
      }
    }).catch(function() { goWizStep('tier'); });
  }, 400);
})();

function checkWizBalanceAndRun() {
  if (WS.tier === 'full') {
    if (!hasUnlimited()) { goWizStep('pay'); showPayStep('sub'); return; }
  } else {
    if (!hasBalance()) { goWizStep('pay'); showPayStep('deposit'); return; }
  }
  goWizStep('number');
  document.getElementById('s3-phone').value = WS.msisdn;
  // Auto-run if we already have the number
  setTimeout(runWizCheck, 300);
}
</script>
<?php @include $_SERVER['DOCUMENT_ROOT'] . '/_lbs_analytics.php'; ?>
</body>
</html>
