<?php
/**
 * GT BOGO Engine — Documentation v3.16.0
 * Complete reference covering all backend intelligence superpowers, 200 packs,
 * customer intelligence, email system, loyalty, referrals, and all admin pages.
 *
 * @package GT_BOGO_Engine
 * @since   3.12.0
 * @updated 3.16.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

$is_pro   = function_exists( 'gt_bogo_has_pro' ) ? gt_bogo_has_pro() : false;
$ver      = defined( 'GT_BOGO_VERSION' ) ? GT_BOGO_VERSION : '3.16.0';
$doc      = isset( $_GET['doc'] ) ? sanitize_key( $_GET['doc'] ) : 'overview';

// ── Section definitions ────────────────────────────────────────────────────────
$sections = [
    'overview'       => [ 'icon' => '📖', 'title' => 'Overview' ],
    'golive'         => [ 'icon' => '🚀', 'title' => 'Go Live Checklist' ],
    'rules'          => [ 'icon' => '⚡', 'title' => 'Rules & Packs' ],
    'superpowers'    => [ 'icon' => '💎', 'title' => 'Backend Intelligence Superpowers' ],
    'scheduler'      => [ 'icon' => '📅', 'title' => 'Campaign Scheduler' ],
    'segments'       => [ 'icon' => '🎯', 'title' => 'Customer Segments' ],
    'intelligence'   => [ 'icon' => '🧠', 'title' => 'Customer Intelligence' ],
    'loyalty'        => [ 'icon' => '👑', 'title' => 'Loyalty & VIP' ],
    'referrals'      => [ 'icon' => '🔗', 'title' => 'Referral Program' ],
    'emails'         => [ 'icon' => '📧', 'title' => 'Email System' ],
    'analytics'      => [ 'icon' => '📈', 'title' => 'Analytics' ],
    'abtesting'      => [ 'icon' => '🔬', 'title' => 'A/B Testing' ],
    'conditions'     => [ 'icon' => '⚙️', 'title' => 'Conditions & Targeting' ],
    'dealpage'       => [ 'icon' => '🏪', 'title' => 'Deal Page' ],
    'geo'            => [ 'icon' => '🌍', 'title' => 'Geo Targeting' ],
    'currency'       => [ 'icon' => '💱', 'title' => 'Multi-Currency' ],
    'whitelabel'     => [ 'icon' => '🏷️', 'title' => 'White Label' ],
    'integrations'   => [ 'icon' => '🔌', 'title' => 'Integrations' ],
    'restapi'        => [ 'icon' => '🔗', 'title' => 'REST API' ],
    'settings'       => [ 'icon' => '⚙️', 'title' => 'Settings Reference' ],
    'pricing'        => [ 'icon' => '💳', 'title' => 'Pricing & Licensing' ],
];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>

<div class="gt-page-header gt-animate-in">
  <div>
    <h1 class="gt-page-title">📖 Documentation</h1>
    <p class="gt-page-subtitle">Complete reference for GT BOGO Engine PRO v<?php echo esc_html( $ver ); ?> — 200 packs, backend intelligence superpowers, customer intelligence, and enterprise lifecycle emails</p>
  </div>
  <div class="gt-page-actions">
    <a href="https://graphictshirts.shop/bogo/" target="_blank" class="gt-btn gt-btn-ghost">Support →</a>
  </div>
</div>

<div style="display:grid;grid-template-columns:220px 1fr;gap:24px;align-items:start">

<!-- ── Sidebar ──────────────────────────────────────────────────────────── -->
<div class="gt-card gt-animate-in" style="padding:0;overflow:hidden;position:sticky;top:32px">
  <div style="padding:14px 18px;border-bottom:1px solid var(--gt-border)">
    <p style="margin:0;font-size:11px;font-weight:800;color:var(--gt-subtle);letter-spacing:.1em;text-transform:uppercase">Contents</p>
  </div>
  <nav style="padding:8px 0">
    <?php foreach ( $sections as $key => $s ):
      $active = $doc === $key; ?>
    <a href="?page=gt-bogo-engine&tab=documentation&doc=<?php echo esc_attr($key); ?>" data-doc="<?php echo esc_attr($key); ?>" class="gt-doc-nav-link"
       style="display:flex;align-items:center;gap:10px;padding:9px 18px;text-decoration:none;font-size:13px;font-weight:<?php echo esc_html( $active )?'700':'500'; ?>;color:<?php echo esc_html( $active )?'#ffffff':'var(--gt-soft)'; ?>;background:<?php echo esc_html( $active )?'rgba(225,0,0,0.12)':'transparent'; ?>;border-left:3px solid <?php echo esc_html( $active )?'#E10000':'transparent'; ?>;transition:all .15s">
      <span style="font-size:15px"><?php echo esc_html( $s['icon'] ); ?></span>
      <?php echo esc_html($s['title']); ?>
    </a>
    <?php endforeach; ?>
  </nav>
</div>

<!-- ── Content ──────────────────────────────────────────────────────────── -->
<div class="gt-animate-in" id="gt-doc-content">

<?php

// ══════════════════════════════════════════════════════════════════════════════
if ( $doc === 'overview' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">What is GT BOGO Engine PRO</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.75;margin:0 0 16px">GT BOGO Engine PRO is an enterprise-grade WooCommerce promotion plugin that replaces coupon codes with intelligent rule-based discount logic. Rules fire automatically at cart — no customer action required beyond adding qualifying items.</p>
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-top:20px">
    <?php foreach ([
      ['200','PRO Packs','across 19 industries','#E10000'],
      ['27','Superpowers','backend intelligence engines','#3b82f6'],
      ['10','Rule Types','per pack, enterprise grade','#22c55e'],
      ['19','Emails','automated lifecycle','#f59e0b'],
      ['150+','Currencies','global storefront ready','#8b5cf6'],
      ['26','Admin Pages','full plugin management','#06b6d4'],
    ] as $s): ?>
    <div style="background:var(--gt-card);border:1px solid var(--gt-border);border-radius:10px;padding:20px;text-align:center">
      <div style="font-size:32px;font-weight:900;color:<?php echo esc_html( $s[3] ); ?>;line-height:1;margin-bottom:6px"><?php echo esc_html( $s[0] ); ?></div>
      <div style="font-size:14px;font-weight:700;color:var(--gt-white);margin-bottom:4px"><?php echo esc_html( $s[1] ); ?></div>
      <div style="font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $s[2] ); ?></div>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Automated Customer Emails</h2></div>
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
    <div style="padding:16px;border:2px solid rgba(59,130,246,0.3);border-radius:10px;background:rgba(59,130,246,0.04)">
      <p style="margin:0 0 8px;font-size:13px;font-weight:800;color:#3b82f6;text-transform:uppercase;letter-spacing:.08em">19 Lifecycle Emails</p>
      <p style="margin:0 0 12px;font-size:12px;color:var(--gt-soft);line-height:1.6">Sent automatically to your customers using your store's own mail configuration. Fully white-labelled — your store name, logo, and chosen email theme. GT BOGO Engine is never visible to your customers.</p>
      <p style="margin:0;font-size:12px;color:var(--gt-subtle)">Enable in Settings · Choose a theme in Settings → Email Theme</p>
    </div>
    <div style="padding:16px;border:2px solid rgba(34,197,94,0.3);border-radius:10px;background:rgba(34,197,94,0.04)">
      <p style="margin:0 0 8px;font-size:13px;font-weight:800;color:#22c55e;text-transform:uppercase;letter-spacing:.08em">Fully Automatic</p>
      <p style="margin:0 0 12px;font-size:12px;color:var(--gt-soft);line-height:1.6">All 19 emails fire based on customer behaviour — orders, tier changes, streaks, referrals, VIP unlock, cart abandonment, and lifecycle events. No manual scheduling or triggers. Enable once and it runs on autopilot.</p>
      <p style="margin:0;font-size:12px;color:var(--gt-subtle)">Requires store name, logo, and WooCommerce from-email configured</p>
    </div>
  </div>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Quick Start</h2></div>
  <?php foreach ([
    ['1','Activate your PRO license','Go to GT BOGO Engine → License and enter your key. PRO unlocks all 200 packs and all backend intelligence superpowers.'],
    ['2','Import a Pro Pack','Go to PRO Rules → Browse the 200 packs by industry. Click Import on a pack and all 10 rules load instantly.'],
    ['3','Enable rules','Go to PRO Rules → Your Rules and toggle the rules you want active. Start with the entry deal (priority ~50) and one volume deal.'],
    ['4','Enable superpowers','Go to Superpowers Hub and enable Cart Progress Bar and Product Badges at minimum. These show customers how close they are to a deal.'],
    ['5','Go Live','Return to any page and click Go Live once all checklist items are green. The system confirms store name, logo, email config, active rules, and HTTPS before enabling.'],
  ] as $step): ?>
  <div style="display:flex;gap:16px;margin-bottom:20px;align-items:flex-start">
    <div style="width:32px;height:32px;border-radius:50%;background:#E10000;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:800;color:#fff;flex-shrink:0"><?php echo esc_html( $step[0] ); ?></div>
    <div>
      <p style="margin:0 0 4px;font-size:14px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $step[1] ); ?></p>
      <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $step[2] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'golive' ):
// ══════════════════════════════════════════════════════════════════════════════
$go_live_status = class_exists('GT_BOGO_Go_Live') ? GT_BOGO_Go_Live::instance()->get_status() : null;
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Go Live Checklist</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 20px">The Go Live system evaluates 11 checks across every critical system before enabling your store. All checks must pass and no rule conflicts may exist before the Go Live button appears. The traffic light indicator on every admin page shows your current status at a glance.</p>
  <?php if ( $go_live_status ): ?>
  <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
    <?php foreach ( $go_live_status['checks'] as $key => $chk ): ?>
    <div style="display:flex;gap:12px;align-items:flex-start;padding:14px;border-radius:8px;background:<?php echo esc_html( $chk['pass'] )?'rgba(34,197,94,0.05)':'rgba(239,68,68,0.05)'; ?>;border:1px solid <?php echo esc_html( $chk['pass'] )?'rgba(34,197,94,0.2)':'rgba(239,68,68,0.2)'; ?>">
      <div style="width:22px;height:22px;border-radius:50%;background:<?php echo esc_html( $chk['pass'] )?'rgba(34,197,94,.2)':'rgba(239,68,68,.2)'; ?>;border:1px solid <?php echo esc_html( $chk['pass'] )?'#22c55e':'#ef4444'; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;margin-top:1px">
        <?php if($chk['pass']): ?><svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 5L4 7L8 3" stroke="#22c55e" stroke-width="1.5" fill="none" stroke-linecap="round"/></svg>
        <?php else: ?><svg width="10" height="10" viewBox="0 0 10 10"><path d="M3 3L7 7M7 3L3 7" stroke="#ef4444" stroke-width="1.5" stroke-linecap="round"/></svg><?php endif; ?>
      </div>
      <div>
        <p style="margin:0 0 3px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html($chk['label']); ?></p>
        <p style="margin:0;font-size:12px;color:<?php echo esc_html( $chk['pass'] )?'var(--gt-subtle)':'#fca5a5'; ?>;line-height:1.5"><?php echo esc_html($chk['detail']); ?></p>
        <?php if(!$chk['pass']): ?><a href="<?php echo esc_url($chk['action']); ?>" style="display:inline-block;margin-top:6px;font-size:11px;font-weight:700;color:#E10000;text-decoration:none"><?php echo esc_html($chk['action_label']); ?> →</a><?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="margin-top:20px;padding:16px;background:var(--gt-card);border-radius:8px;border:1px solid var(--gt-border)">
    <p style="margin:0;font-size:14px;color:var(--gt-soft)">
      <strong style="color:var(--gt-white)"><?php echo esc_html( $go_live_status['passed'] ); ?> / <?php echo esc_html( $go_live_status['total'] ); ?></strong> checks passing &nbsp;·&nbsp;
      <strong style="color:<?php echo esc_html( $go_live_status['is_live'] )?'#22c55e':'#f59e0b'; ?>"><?php echo esc_html( $go_live_status['is_live'] )?'Store is live':'Not yet live'; ?></strong>
    </p>
  </div>
  <?php else: ?>
  <p style="color:var(--gt-soft);font-size:13px">Go Live system not available. Ensure the plugin is fully activated.</p>
  <?php endif; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Traffic Light Reference</h2></div>
  <?php foreach ([
    ['🔴 Red','Setup incomplete — fewer than 50% of checks passing. Configure your store name, logo, WooCommerce email, and activate your PRO license.'],
    ['🟡 Yellow','Conflicts detected — two or more active rules share the same priority. Go to the Conflicts page to resolve. Go Live is blocked until all conflicts are cleared.'],
    ['🟢 Green','Store is live — all 11 checks pass, no conflicts exist, and Go Live has been clicked. All systems are active.'],
  ] as $row): ?>
  <div style="display:flex;gap:14px;align-items:flex-start;margin-bottom:16px">
    <span style="font-size:22px;flex-shrink:0"><?php echo esc_html( $row[0][0] ); ?></span>
    <div>
      <p style="margin:0 0 4px;font-size:14px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( substr($row[0],3) ); ?></p>
      <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $row[1] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'rules' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Rule Architecture</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">Every rule has a priority number (1–100). Lower numbers fire first. When two rules qualify for the same cart, the one with the lower priority number wins. Rules from different packs can coexist as long as their priorities are unique — the Conflicts page detects and reports any collisions.</p>
  <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px">
    <?php foreach ([
      ['Entry Deal','Priority 48–55','Always-on deal for all customers. 20–30% off. No scheduling, no role requirements. This is the baseline deal that fires for every qualifying cart.'],
      ['Volume Deal','Priority 55–62','Buy 2 Get 1 FREE mechanics. apply_to=cheapest means the least expensive qualifying item gets the discount. discount_value=100 means completely free.'],
      ['Spend Threshold','Priority 56–65','min_cart set to a dollar value. Progress bar superpower shows customers how much more they need to spend to unlock the deal.'],
      ['Scheduled Seasonal','Priority 50–68','sched=True enables the countdown timer superpower. The Campaign Scheduler activates and deactivates this rule on your defined dates automatically.'],
      ['New Customer','Priority 50–55','ctype=new targets first-time buyers only. WooCommerce customer_type detection. 35–40% off to convert browsers into buyers.'],
      ['Returning Customer','Priority 48–53','ctype=returning targets repeat buyers. 20–25% off as a loyalty acknowledgement. Fires after the new customer deal in the priority stack.'],
      ['VIP / Role-Gated','Priority 60–67','roles=[vip_customer] restricts this deal to customers with that WP role. The Role Manager assigns vip_customer automatically when thresholds are met.'],
      ['Flash Urgency','Priority 68–73','sched=True with a 24–48 hour window. Countdown timer fires. 40–50% off. Creates urgency without permanently eroding margin.'],
      ['Loyalty / Subscription','Priority 57–65','roles=[subscriber_active] or similar. Buy 2 Get 1 or 30% off for subscribers. Fires alongside their regular deal for a stacked incentive.'],
      ['Maximum Flash Event','Priority 72–77','Buy 2 Get 2 FREE or Buy 3 Get 1 FREE. Highest urgency. Used for annual events, clearances, or major promotional windows.'],
    ] as $rt): ?>
    <div style="padding:14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:8px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
        <p style="margin:0;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $rt[0] ); ?></p>
        <span style="font-size:11px;background:rgba(225,0,0,0.12);color:#E10000;padding:2px 8px;border-radius:4px;font-weight:700"><?php echo esc_html( $rt[1] ); ?></span>
      </div>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $rt[2] ); ?></p>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">200 PRO Packs — 19 Industries</h2></div>
  <?php
  $industries = [
    'Software & Digital' => ['PACK-111','PACK-112','PACK-113','PACK-114','Freemium conversion, digital asset bundles, domain and hosting, digital bundle deals'],
    'Home & Garden' => ['PACK-115','PACK-116','PACK-117','PACK-118','PACK-119','PACK-120','PACK-121','PACK-123','PACK-124','PACK-126','Room bundles, installation services, moving, smart home, seasonal refresh, renovation, pool and spa, home security, cleaning supplies'],
    'Hardware & Print' => ['PACK-125','PACK-127','Online print and signage, hardware project bundles'],
    'Outdoor & Sports' => ['PACK-128','PACK-129','PACK-130','PACK-131','PACK-132','PACK-133','Outdoor rooms, team orders, season openers, equipment service, adventure gear, youth sports'],
    'Fitness' => ['PACK-134','PACK-135','PACK-136','PACK-137','PACK-138','PACK-139','Gym membership upgrade, personal training, class packs, corporate wellness, studio intro, class pack and membership'],
    'Golf' => ['PACK-140','PACK-141','PACK-142','PACK-143','Tee time bundles, lesson and round packages, twilight deals, junior golf programs'],
    'Cycling & Skiing' => ['PACK-144','PACK-145','PACK-147','PACK-148','Bike and accessories, bike service, lift passes, lesson and equipment rental'],
    'Martial Arts & Swimming' => ['PACK-149','PACK-150','PACK-151','Intro courses, grading and gear, swim lesson packs'],
    'B2B' => ['PACK-152','PACK-153','PACK-154','PACK-155','PACK-156','Contract pricing, trade accounts, reseller volumes, sample orders, MOQ discounts'],
    'Health' => ['PACK-157','PACK-158','PACK-159','PACK-160','PACK-161','Wellness packages, family health, chronic care loyalty, supplement stacks, subscribe and save'],
    'Education' => ['PACK-162','PACK-163','PACK-164','PACK-165','PACK-166','PACK-167','Course bundles, student exclusives, early enrollment, alumni loyalty, study kits, lesson packs'],
    'Travel & Hospitality' => ['PACK-146','PACK-168','PACK-169','PACK-170','PACK-171','PACK-172','Early booking, early bird, stay longer, room and extras, group travel, last minute'],
    'Events' => ['PACK-173','PACK-174','PACK-175','PACK-176','PACK-177','Early bird tickets, group bookings, season passes, VIP upgrades, merchandise bundles'],
    'Pets' => ['PACK-178','PACK-179','Grooming packages, boarding and training bundles'],
    'Kids & Baby' => ['PACK-180','PACK-181','PACK-182','Art and craft kits, toy age-up bundles, baby and newborn starter bundles'],
    'Gifts & Flowers' => ['PACK-183','PACK-184','PACK-185','PACK-186','PACK-187','Occasion gift bundles, gift card bonuses, mystery boxes, subscription flowers, occasion bouquets'],
    'Photography & Accessories' => ['PACK-188','PACK-189','PACK-190','PACK-191','PACK-192','Session and prints, album upgrades, handbag and leather care, second pair deals, frames and lenses'],
    'Apparel & Fragrance' => ['PACK-193','PACK-194','Size-up rewards, fragrance discovery sets'],
    'Hobby & Music & Books' => ['PACK-195','PACK-196','PACK-197','PACK-198','PACK-199','PACK-200','Mystery bundles, collector and hobby, tabletop, vinyl collections, music instruments, bookstore series'],
  ];
  foreach ( $industries as $name => $packs ):
    $desc = array_pop($packs);
  ?>
  <div style="margin-bottom:12px;padding:14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:8px">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
      <p style="margin:0;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html($name); ?></p>
      <span style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html( count($packs) ); ?> packs · <?php echo esc_html( $packs[0] ); ?>–<?php echo esc_html( end($packs) ); ?></span>
    </div>
    <p style="margin:0;font-size:12px;color:var(--gt-soft)"><?php echo esc_html($desc); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Import & Manage Rules</h2></div>
  <?php foreach ([
    ['Importing a Pack','Go to PRO Rules → Browse by industry or search by name. Click Import Pack. All 10 rules load with their pre-configured superpowers, messaging, priority values, and conditions. Rules import as inactive — review then enable the ones relevant to your store.'],
    ['Enabling Rules','Toggle the Active switch on any rule card. The engine picks up the change on the next cart load. No cache flush required — the rules transient clears automatically.'],
    ['Priority Conflicts','If two active rules share a priority number, the Conflicts page highlights them with the pack they came from and the exact priority clash. Adjust one rule\'s priority by 1 to resolve. The Go Live traffic light turns yellow when conflicts exist.'],
    ['Pack Config','Go to PRO Rules → Pack Config to override nudge messages, badge text, and email copy on a per-pack basis without modifying the underlying rule JSON. Changes save per-pack to wp_options.'],
    ['Free Rule','The Free Rule page lets non-PRO users configure one global BOGO rule with buy quantity, get quantity, discount type, and discount value. This rule applies sitewide to all products with no category or product filtering.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:14px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'superpowers' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Superpower Architecture</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">GT BOGO Engine superpowers are pure backend intelligence engines. They run silently on order hooks, WP-Cron, and cart filters. Zero frontend injection, zero theme conflicts, zero design dependency. Every superpower works identically across all WordPress themes.</p>
  <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
    <div style="padding:14px;background:rgba(225,0,0,0.06);border:1px solid rgba(225,0,0,0.2);border-radius:8px">
      <p style="margin:0 0 6px;font-size:12px;font-weight:800;color:#E10000;letter-spacing:.08em;text-transform:uppercase">Cart Intelligence</p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6">Cart Progress Bar, Savings Calculator, Deal Comparison, Cart Recommendations. All render inside WooCommerce cart and checkout hooks only. Never inject into product pages.</p>
    </div>
    <div style="padding:14px;background:rgba(59,130,246,0.06);border:1px solid rgba(59,130,246,0.2);border-radius:8px">
      <p style="margin:0 0 6px;font-size:12px;font-weight:800;color:#3b82f6;letter-spacing:.08em;text-transform:uppercase">Backend Intelligence</p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6">LTV Scoring, Inventory Intelligence, Revenue Guard, Webhook Triggers, Subscription Detection, Anniversary, Birthday, Post-Purchase Intelligence, Multi-Currency Optimizer, Geo Rules Engine. All run on order hooks and WP-Cron.</p>
    </div>
  </div>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Cart &amp; Checkout Superpowers</h2></div>
  <p style="font-size:13px;color:var(--gt-soft);line-height:1.7;margin:0 0 20px">These superpowers render inside the WooCommerce cart and checkout flow only. Zero injection on product pages, shop loops, or any other frontend location. WC Blocks and classic WooCommerce both supported from v3.16.0.</p>
  <?php foreach ( [
    [ 'Cart Progress Bar', 'Multi-tier threshold progress bar showing customers exactly how many items they need to add to unlock the active deal. Renders in cart totals and checkout order review. AJAX-refreshed on every cart update so the bar advances in real time. Three intensity settings: subtle (no animation, minimal height — luxury appropriate), moderate, and bold (animated spring bounce with cubic-bezier easing). Always reads from the highest-priority active rule. When the deal unlocks the bar transitions to a green completion state with the deal label. Supports the free rule and all 200 PRO pack rules. WC Blocks supported via the single MutationObserver frontend injector.' ],
    [ 'Savings Calculator', 'Real-time savings breakdown in cart totals. Shows original cart value, exact discount applied by the active rule, and amount saved as both a currency figure and percentage. Updates on every cart change via AJAX fragments so the display is always accurate. Three copy tiers: subtle ("Your saving — £24.00 with your offer"), moderate ("You saved £24.00 with your deal"), bold ("Saved £24.00 with deal"). Works with percentage discounts, fixed amount discounts, and free item (100%) rules. Renders in cart totals before order total and in checkout order review. WC Blocks supported.' ],
    [ 'Deal Comparison', 'Side-by-side effective price comparison in cart totals. Shows the customer their actual price per item with the deal applied versus the standard price. Includes savings percentage and absolute saving. Critical for bulk-buy deals where per-unit pricing drives conversion — a customer considering 4 tires sees "effective price £89.75 per tire instead of £119.00" and the psychology shifts from cost to value. Fires in cart totals area only. Three copy tiers: subtle ("Effective price when purchasing 4 — offer applied automatically"), bold ("Your price buying 4 — deal auto-applied"). WC Blocks supported.' ],
    [ 'Cart Recommendations', 'Suggests qualifying products inside the cart when the customer is one or two items away from unlocking a deal. Queries the WooCommerce product catalogue using the active rule category and product conditions. Randomised from the full matching catalogue so recommendations feel fresh on each visit. Shows product thumbnail, name, and price with a direct add-to-cart button. Fires after the cart table only — never on product pages or shop loops. Three copy tiers: "You may also like these pieces" (subtle/luxury) through "Add another — keep the deal" (bold/streetwear). WC Blocks supported.' ],
    [ 'Loyalty Widget', 'Shows the logged-in customer their loyalty tier, total lifetime spend, and how much more they need to spend to reach the next tier. Tier labels: Bronze, Silver, Gold, Platinum. For customers at the top tier a "You hold our highest standing" confirmation appears. Logged-in users only — hidden completely for guests and not queried. Fires in cart totals and on the WooCommerce account dashboard. Three copy tiers: subtle ("Silver Client — total spend"), moderate ("Silver Member — lifetime spend"), bold ("Silver Member — spent"). WC Blocks supported via frontend injector.' ],
    [ 'Savings History', 'Cumulative savings tracker in cart totals and account dashboard. Reads from the customer lifetime BOGO savings record in user meta. Shows total saved across all orders with a per-order breakdown of order number and saving. Logged-in customers only. The total savings figure builds long-term loyalty — a customer who has saved £340 across 12 orders is deeply invested in the store. Three copy tiers: "Your savings record" (subtle) through "Total saved with us" (bold). WC Blocks supported.' ],
  ] as $sp ): ?>
  <div style="margin-bottom:22px;padding-bottom:22px;border-bottom:1px solid var(--gt-border)">
    <p style="margin:0 0 8px;font-size:15px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $sp[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.8"><?php echo esc_html( $sp[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Sitewide &amp; Storefront Superpowers</h2></div>
  <p style="font-size:13px;color:var(--gt-soft);line-height:1.7;margin:0 0 20px">These superpowers fire via wp_footer, wp_body_open, or wp_enqueue_scripts. They operate across the full storefront but never inject content onto product pages. The 13 forbidden product page hooks are enforced at the injector level — no superpower can register them accidentally.</p>
  <?php foreach ( [
    [ 'Announcement Bar', 'Sitewide top banner via wp_body_open broadcasting the active deal to every visitor. Supports rotating messages — the bar cycles through multiple deal messages automatically on a configurable interval. Integrates with the Countdown Timer: when both are active the bar shows a live countdown to deal expiry alongside the deal message. Customers can dismiss the bar; dismissal is stored in a cookie so it does not reappear in the same session. Three copy tiers: "Purchase 2, receive 1 complimentary — applied at checkout" (subtle/luxury) through "Buy 2 Get 1 FREE — fires at checkout automatically" (bold). Configurable background color, text, CTA label, and CTA URL. Coordinates with the email system — if an email was sent for the same event in the last 30 minutes the bar will not fire, preventing double notification.' ],
    [ 'Countdown Timer', 'Real-time countdown clock tied directly to the active rule end_date. When the rule has a scheduled end date the timer counts down to that exact moment with hours, minutes, and seconds. If no end date is set the timer falls back to a session-based daily deal timer that resets at midnight — creating daily urgency without requiring manual scheduling. Multiple placement hooks. Three intensity levels control prominence and animation. Copy tiers: "Offer ends in" (subtle) through "Deal ends in" (bold). Pairs naturally with the Announcement Bar and Campaign Scheduler for fully automated timed campaigns that activate and deactivate without any manual intervention.' ],
    [ 'Nudge Messages', 'Two-part superpower. Cart nudge: renders above the WooCommerce cart table showing how many more items are needed to unlock the active deal. When the deal is already applied shows a green confirmation state. Shop nudge: injects a deal banner before the product grid on shop and category pages via wp_footer JavaScript. The JS insertion uses document.querySelector targeting ul.products and .wc-block-grid__products — compatible with all page builders and WC Blocks shop grids. Never uses PHP shop loop hooks. Three copy tiers. Checks active rule start and end date before rendering — respects scheduling automatically.' ],
    [ 'Scarcity Bar', 'Stock level urgency messaging fired via wp_enqueue_scripts. Three automatic urgency tiers based on current WooCommerce stock: under 5 units triggers maximum urgency ("Limited availability — 4 remaining"), under 10 triggers moderate ("Only 9 left at this price"), under 20 triggers low urgency. Uses WooCommerce stock management data directly — no manual stock entry. Copy adapts across intensity tiers from understated ("Limited availability") to high-energy ("left — deal ends when stock does"). Particularly powerful for flash sale and inventory clearance packs where genuine scarcity drives urgency.' ],
    [ 'Geo Banner', 'Location-specific deal messaging using WooCommerce native geolocation. Detects customer billing country and shows a matching deal banner. Pre-configured messages for US, UK, Canada, and Australia. Custom zones supported via the gtbogo_geo_zone_label filter. Simultaneously assigns geo zone WordPress user roles (geo_us, geo_gb, geo_ca, geo_au) to logged-in customers — these roles are used as rule conditions to target country-specific discounts. Three copy tiers: "Complimentary offer active for United States orders" (subtle) through "US orders — deal active at checkout" (bold). No IP lookup frontend injection.' ],
    [ 'Social Proof', 'Real-time purchase activity and viewer count signals. Pulls actual order data from the gtbogo_analytics table — "12 clients have claimed this offer recently" reflects real BOGO orders in the past 24 hours. Falls back to algorithmically realistic numbers when no real data exists yet, so new stores benefit from social proof from day one without fabrication. Viewer count creates parallel urgency. Three copy tiers: "X clients have claimed this offer recently" (subtle/luxury) through "X orders with this deal today" (bold). Update interval configurable. Fires via wp_enqueue_scripts.' ],
    [ 'VIP Badge', 'Status indicator shown in cart and checkout exclusively for customers holding active VIP roles: vip_customer, gold_vip, platinum_vip, whale_customer. Communicates that their exclusive deal is active and applied automatically. Three display styles: "Private Client" with contextual hint "Your private client offer is applied automatically at checkout" (subtle — luxury brand appropriate), "VIP Exclusive" (moderate), "VIP Deal" (bold). Only renders for logged-in customers with a VIP role — completely invisible to non-VIP customers. Zero product page injection.' ],
    [ 'Smart Popup', 'Contextual deal modal with four configurable triggers: (1) cart deal applied — fires when the BOGO discount first activates in the cart, (2) idle timer — fires after a configurable inactivity period, (3) scroll depth — fires when the customer has scrolled a configured percentage of the page, (4) page visits — fires after a configurable number of pages in the session. Frequency-capped: once per session by default, configurable. Shows active deal headline, sub-copy, and CTA. Three copy tiers. Fires via wp_footer.' ],
    [ 'Mobile Drawer', 'Bottom-sheet deal panel built specifically for mobile visitors. Desktop-hidden via CSS media query — only activates on viewports under 768px. Slides up from the bottom with the active deal details, savings amount, and a shop CTA. Does not interfere with the mobile WooCommerce cart drawer or any theme mobile navigation. Fires via wp_footer. Three copy tiers: "Your exclusive offer" / "Shop the offer" (subtle) through "Active deal" / "Shop now" (bold). Particularly effective for mobile-first stores where full-screen popups have lower engagement.' ],
    [ 'Exit Intent', 'Overlay triggered by cursor-leave-viewport event (desktop) with scroll-reversal fallback for mobile. Detects when the customer is about to leave and presents the active deal. Shows deal headline formatted to the active rule type, sub-copy explaining the deal fires automatically, and a return-to-shop CTA. Session-capped — fires once per session maximum. Three copy tiers: "Before you leave — Purchase 2, receive 1 at 30% off" (subtle) through "Your deal — Buy 2 Get 1 — 30% off" (bold). Fires via wp_footer.' ],
    [ 'Abandon Nudge', 'Multi-channel cart abandonment recovery. Three coordinated channels: (1) idle overlay — fires after a configurable idle period (default 90 seconds) when the cart has items, showing the active deal with a complete-purchase CTA; (2) browser tab title flash — alternates the page title between the deal message and the original title to recapture attention from other tabs; (3) push notification request — optionally prompts the customer to allow browser push for deal updates. Frequency-capped per session. Only fires when WC()->cart has items — never on empty-cart pages. Fires via wp_footer.' ],
  ] as $sp ): ?>
  <div style="margin-bottom:22px;padding-bottom:22px;border-bottom:1px solid var(--gt-border)">
    <p style="margin:0 0 8px;font-size:15px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $sp[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.8"><?php echo esc_html( $sp[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Bundle, Deal &amp; Social Superpowers</h2></div>
  <?php foreach ( [
    [ 'Bundle Spotlight', 'Frequently-bought-together display highlighting product combinations that together qualify for the active BOGO deal. Shows bundle composition with product thumbnails, individual prices, and the total price with deal savings applied. Particularly effective for complementary product deals (camera + memory card + case, for example). Add-all button adds the complete bundle to cart in one click. Three copy tiers: "Frequently selected together" / "Add selection to bag" (subtle) through "Buy together — deal applies" / "Add all to cart" (bold). Fires via wp_enqueue_scripts.' ],
    [ 'Bundle Configurator', 'Interactive bundle composition widget in cart totals. Validates that the cart meets bundle composition requirements before the discount fires. Shows which items are in the bundle, which slots are still empty, and what to add to complete it. Displays projected savings once the bundle is complete. Add-remaining button adds all outstanding required items in one click. Three copy tiers: "Add selection to bag" / "Add X more to complete your offer" (subtle) through "Add all — deal fires" / "Add X more — deal fires" (bold). WC Blocks supported.' ],
    [ 'Deal Unlock Toast', 'Animated confirmation notification that fires the moment a BOGO deal activates in the cart. Triggered by the woocommerce_cart_updated hook via JavaScript. Slides in from the edge of the screen, shows the deal label and savings amount, and auto-dismisses after 4 seconds. Creates a satisfying moment of confirmation the deal has been earned — proven to increase cart completion rates by reducing abandonment immediately after deal unlock. Three copy tiers: "Offer applied — your saving" (subtle) through "Deal locked in — saved £X" (bold).' ],
    [ 'Quick Add', 'Enhances add-to-cart buttons on WooCommerce shop loop pages. Fires via the woocommerce_loop_add_to_cart_link filter — shop loop pages only, no product page injection. Wraps the standard loop add-to-cart link with deal awareness: shows the deal label alongside the button, highlights qualifying products, and adds visual emphasis when adding this product would unlock a deal. Three copy tiers: "Add to bag" (subtle) through "Add to cart" (bold).' ],
    [ 'Deal Share', 'One-click deal sharing in cart totals. Uses the Web Share API on supported browsers (mobile Safari, Chrome for Android, modern desktop) with a clipboard copy fallback. Shares the current deal with the store URL and deal description formatted to the active rule. Three copy tiers: "Share this offer" / "Link copied" (subtle) through "Share the deal" / "Copied" (bold). Confirmation toast appears on successful clipboard copy.' ],
    [ 'Badge Generator', 'Deal badge displayed in the cart totals area showing the active deal format. Cart page only — the woocommerce_product_thumbnails hook is explicitly forbidden and removed. Badge text adapts to rule type: "Buy 2 Get 1 Complimentary" (subtle/luxury free rule), "Buy 2 Get 1 Free" (moderate), "Buy 2 Get 1 FREE" (bold), or percentage variants. Three aria-label intensity levels for accessibility. Fires via template_redirect routing — Blocks pages use the frontend injector, classic pages use woocommerce_before_cart_totals.' ],
    [ 'Referral Widget', 'Generates a personalised referral link for every logged-in customer. Displayed on the WooCommerce thank-you page and account dashboard. The link embeds a unique customer identifier as a URL parameter. When a referred visitor arrives via this link a tracking cookie is set for 30 days. On the referred customer\'s first purchase: the referral is attributed, the referral_champion role is assigned to the referrer, and both the referral reward email and the referred_customer role fire automatically. Tracks total referral count. Three copy tiers.' ],
    [ 'Email Notifications', 'White-labelled lifecycle email system triggered at order completion by BOGO events. Fires emails for: deal applied confirmation, loyalty tier upgrade, referral conversion, streak milestone, birthday deal, anniversary deal, and win-back campaign. All emails use the store own email address and branding — zero GT BOGO Engine branding visible to customers at any point. Email deduplication engine prevents the same customer receiving the same event notification twice within 24 hours. Coordinates with the Announcement Bar — if an email fired for the same event in the last 30 minutes the bar will not fire, preventing double notification. Nine pre-built HTML email templates, all white-labelled and intensity-aware.' ],
  ] as $sp ): ?>
  <div style="margin-bottom:22px;padding-bottom:22px;border-bottom:1px solid var(--gt-border)">
    <p style="margin:0 0 8px;font-size:15px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $sp[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.8"><?php echo esc_html( $sp[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">v3.16.0 — Architecture Upgrades</h2></div>
  <p style="font-size:13px;color:var(--gt-soft);line-height:1.7;margin:0 0 20px">v3.16.0 delivered four architectural upgrades that make GT BOGO Engine the most compatible and most flexible BOGO plugin for WooCommerce.</p>
  <?php foreach ( [
    [ 'WC Blocks Compatibility Layer', 'GT_BOGO_Blocks_Compat singleton detects WC Blocks via has_block() and post content scanning on template_redirect. Classic pages use standard PHP hooks unchanged. Blocks pages route through GT_BOGO_Frontend_Injector — a single MutationObserver that retries injection at 200ms, 500ms, 1s, 2s, and 4s after DOMContentLoaded, then watches for DOM mutations for 30 seconds to handle React re-renders. One observer for all 27 superpowers — zero per-superpower observers. Disconnects automatically after 30 seconds when React rendering has stabilised.' ],
    [ 'Theme Compatibility Matrix', '100+ WordPress themes across 20 CSS framework families. Salient, Divi, Elementor, Avada, BeTheme, Enfold, Flatsome, WoodMart, XStore, The7, Jupiter X, Total, X/Pro (Themeco), Uncode, Storefront, Genesis, Thrive/SeedProd, Crafto/agency themes, Twenty-series, and all lightweight block themes including Astra, Kadence, GeneratePress, Neve, Blocksy, OceanWP, Sydney, Zakra, and 20 more. Universal hardened CSS baseline uses html body prefix specificity and !important on all layout-critical properties. Developers register additional themes via the gtbogo_theme_compat_map filter — no plugin update required.' ],
    [ 'Storefront Appearance Settings', 'Store owners configure all superpower widget visuals from Settings → Storefront Appearance. Five CSS variables written to :root on wp_head: accent color, danger/urgency color, widget background, text color, and border radius. Changes apply to all 27 superpowers instantly. Works on every WordPress theme. Defaults are brand-neutral so the plugin works out of the box without any configuration.' ],
    [ 'Superpower Safety Wrapper', 'GT_BOGO_Frontend_Injector::is_allowed_page() blocks all injection on product pages at the architectural level. 13 forbidden hooks are documented as the $forbidden_hooks constant in the injector class — the full list: woocommerce_single_product_summary, woocommerce_before_single_product, woocommerce_after_add_to_cart_form, woocommerce_before_add_to_cart_button, woocommerce_after_add_to_cart_button, woocommerce_after_shop_loop_item, woocommerce_before_shop_loop_item, woocommerce_before_shop_loop, woocommerce_before_shop_loop_item_title, woocommerce_after_shop_loop_item_title, woocommerce_get_price_html, woocommerce_get_sale_price, woocommerce_get_regular_price. This guarantee makes GT BOGO Engine safe to deploy on luxury, premium, and corporate WooCommerce stores where every pixel of the product page is intentional.' ],
    [ 'Onboarding Wizard', 'Four-step sequential setup guide appearing on all GT BOGO Engine admin pages for new PRO users. Step 1: activate license (detects gtbogo_license_status = active). Step 2: import first pack (queries gtbogo_owned_packs count). Step 3: enable first rule (queries gtbogo_rules WHERE status = active). Step 4: complete Go Live checklist (checks gtbogo_is_live option). Each step detects completion automatically by querying the database — the wizard advances without the user returning to it. Dismissible. Auto-dismisses permanently once all four steps complete. Never shows again.' ],
  ] as $sp ): ?>
  <div style="margin-bottom:22px;padding-bottom:22px;border-bottom:1px solid var(--gt-border)">
    <p style="margin:0 0 8px;font-size:15px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $sp[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.8"><?php echo esc_html( $sp[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Role Manager — 23 Auto-Assigned Roles</h2></div>
  <p style="font-size:13px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The GT_BOGO_Role_Manager assigns custom WordPress user roles automatically based on purchase behaviour. These roles map directly to rule conditions — when a customer earns a role, the rules that target that role immediately start firing for them.</p>
  <?php
  $role_groups = [
    'Order Milestones' => ['order_3','order_5','order_10','order_15','order_20','order_25'],
    'Streak Tracking'  => ['streak_4','streak_8','streak_12','streak_52','streak_at_risk'],
    'Loyalty Tiers'    => ['silver_member','gold_member'],
    'Lifecycle'        => ['lapsed_90','anniversary_member','post_purchase','birthday_member'],
    'Referral'         => ['referrer_1','referrer_3','referrer_5','referred_customer'],
    'Subscription'     => ['subscriber_active','subscriber_at_risk'],
  ];
  foreach ($role_groups as $group => $roles): ?>
  <div style="margin-bottom:14px">
    <p style="margin:0 0 8px;font-size:12px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.08em"><?php echo esc_html( $group ); ?></p>
    <div style="display:flex;flex-wrap:wrap;gap:6px">
      <?php foreach ($roles as $role): ?>
      <code style="background:rgba(255,255,255,0.05);border:1px solid var(--gt-border);padding:3px 10px;border-radius:4px;font-size:12px;color:#fbbf24"><?php echo esc_html( $role ); ?></code>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Engagement Score</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">Every customer receives an engagement score computed from weighted superpower interactions. Score components:</p>
  <?php foreach ([
    ['Order completed with BOGO applied','30 points'],
    ['VIP tier reached','25 points'],
    ['Streak milestone achieved','20 points'],
    ['Referral converted','20 points'],
    ['Progress bar interaction','10 points'],
    ['Deal shared','10 points'],
    ['Nudge clicked','5 points'],
    ['Badge viewed (product page)','2 points'],
  ] as $row): ?>
  <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;border-radius:6px;margin-bottom:6px;background:var(--gt-card);border:1px solid var(--gt-border)">
    <span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $row[0] ); ?></span>
    <span style="font-size:13px;font-weight:700;color:#22c55e">+<?php echo esc_html( $row[1] ); ?></span>
  </div>
  <?php endforeach; ?>
  <p style="margin-top:14px;font-size:13px;color:var(--gt-subtle)">Scores are visible in the Customer Intelligence admin page and can be sorted to identify your highest-value, most engaged customers for targeted manual outreach.</p>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'loyalty' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Loyalty Tier System</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 20px">Four loyalty tiers are evaluated automatically on every completed order. Tier upgrades fire the <code style="color:#fbbf24">gtbogo_tier_upgraded</code> hook which triggers the tier upgrade email and assigns the corresponding WP role.</p>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px">
    <?php foreach ([
      ['Bronze','#cd7f32','$0+','0+ orders','Base tier. All customers start here. Standard deal access.'],
      ['Silver','#9ca3af','$200+ LTV','3+ orders','silver_member role assigned. 5% deal boost at checkout via Smart Checkout tier multiplier.'],
      ['Gold','#f59e0b','$500+ LTV','7+ orders','gold_member role assigned. 10% deal boost. VIP deals start becoming available.'],
      ['Platinum','#e2e8f0','$1,000+ LTV','12+ orders','15% deal boost. All VIP and platinum-targeted rules fire. Highest priority deal access.'],
    ] as $tier): ?>
    <div style="padding:16px;border-radius:10px;border:2px solid <?php echo esc_html( $tier[1] ); ?>22;background:<?php echo esc_html( $tier[1] ); ?>08;text-align:center">
      <div style="font-size:22px;margin-bottom:8px">🏆</div>
      <p style="margin:0 0 6px;font-size:15px;font-weight:800;color:<?php echo esc_html( $tier[1] ); ?>"><?php echo esc_html( $tier[0] ); ?></p>
      <p style="margin:0 0 4px;font-size:12px;color:var(--gt-soft)"><?php echo esc_html( $tier[2] ); ?></p>
      <p style="margin:0 0 10px;font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $tier[3] ); ?></p>
      <p style="margin:0;font-size:11px;color:var(--gt-soft);line-height:1.5"><?php echo esc_html( $tier[4] ); ?></p>
    </div>
    <?php endforeach; ?>
  </div>
</div>

<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">VIP Detection</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">VIP tiers are separate from loyalty tiers and are evaluated by <code style="color:#fbbf24">GT_BOGO_VIP_Detection</code> on every order completion. VIP roles unlock the highest-priority rules in any pack.</p>
  <?php foreach ([
    ['vip_customer','3+ orders AND $300+ LTV','Basic VIP. Access to VIP-gated rules in any pack.'],
    ['gold_vip','5+ orders AND $500+ LTV','Gold VIP. Extended deal access and 40%+ discount rules.'],
    ['platinum_vip','$1,000+ LTV','Platinum VIP. Buy 2 Get 2 and flash event access.'],
    ['whale_customer','$5,000+ LTV','Whale tier. Maximum discount rules and annual showcase deals.'],
    ['referral_champion','5+ successful referrals','Referral-based VIP. Earns through advocacy, not spend.'],
    ['lapsed_vip','Former VIP, inactive 90 days','Retention targeting. At-risk churn prevention rules fire for this role.'],
  ] as $vip): ?>
  <div style="display:flex;gap:14px;align-items:flex-start;margin-bottom:12px;padding:12px 14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:8px">
    <code style="font-size:12px;color:#fbbf24;background:rgba(255,255,255,0.05);padding:3px 8px;border-radius:4px;flex-shrink:0;white-space:nowrap;margin-top:2px"><?php echo esc_html( $vip[0] ); ?></code>
    <div>
      <p style="margin:0 0 3px;font-size:12px;font-weight:700;color:var(--gt-subtle)"><?php echo esc_html( $vip[1] ); ?></p>
      <p style="margin:0;font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $vip[2] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Streak Tracking</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">Purchase streaks are tracked per-customer as consecutive months with at least one qualifying order. Streaks are evaluated by the daily cron and by the Role Manager on every order completion.</p>
  <?php foreach ([
    ['streak_4','4 consecutive months','First milestone. Streak bonus email fires. streak_4 role assigned.'],
    ['streak_8','8 consecutive months','Second milestone. Enhanced deal access. Streak reward applied.'],
    ['streak_12','12 consecutive months','One year streak. Maximum streak deal tier.'],
    ['streak_52','52 consecutive weeks','Weekly streak variant for high-frequency stores.'],
    ['streak_at_risk','No order in 25+ days','At-risk detection. Winback email and retention rules fire automatically.'],
  ] as $s): ?>
  <div style="display:flex;gap:12px;align-items:flex-start;margin-bottom:12px">
    <code style="font-size:12px;color:#fbbf24;background:rgba(255,255,255,0.05);padding:3px 8px;border-radius:4px;flex-shrink:0;white-space:nowrap;margin-top:2px"><?php echo esc_html( $s[0] ); ?></code>
    <div>
      <p style="margin:0 0 2px;font-size:12px;font-weight:700;color:var(--gt-subtle)"><?php echo esc_html( $s[1] ); ?></p>
      <p style="margin:0;font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $s[2] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'referrals' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Referral Program</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The referral system creates a closed-loop customer acquisition channel. Every registered customer gets a unique referral link. When someone uses that link and completes their first purchase, the referrer earns a permanent WooCommerce coupon that never expires.</p>
  <?php foreach ([
    ['How customers get their referral link','The referral link is displayed in the My Rewards tab inside WooCommerce My Account. It is also included in the post-purchase email and the BOGO confirmation email. Customers can copy the link directly from any of these locations with a single click. The referral link format is: yourstoreurl.com/?ref=CUSTOMER_ID.'],
    ['Referral tracking','A 30-day cookie is set when any visitor lands on a page with a valid ?ref= parameter. If that visitor registers and completes a purchase within 30 days, the referral is attributed to the referring customer. The cookie is cleared after successful attribution.'],
    ['What the reward is','The referrer receives a WooCommerce percentage-off coupon. The default value is 10% off. The coupon has no expiry date — it is permanent. The store owner can configure the reward percentage and label at GT BOGO Engine → Settings → Referral Reward Value.'],
    ['Referral milestones','The Role Manager assigns referrer_1, referrer_3, and referrer_5 roles automatically as referral counts hit those thresholds. These roles can be used as rule conditions — e.g. a referrer_5 deal targeting customers who have referred 5 people with a Buy 2 Get 2 reward.'],
    ['referred_customer role','The referred customer (the person who was referred) receives the referred_customer WP role. This role can target first-purchase incentive rules specifically for referred customers, improving conversion of referred traffic.'],
    ['Referral Champion VIP','Customers who achieve 5 or more successful referrals are automatically assigned the referral_champion VIP role, unlocking the highest-tier deal access without requiring spend-based qualification.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:14px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Referral Emails</h2></div>
  <?php foreach ([
    ['Referral reward earned','Fires to the referrer when their referred contact completes their first purchase. Subject: "[Store]: You earned a referral reward". Shows the referred customer\'s name and the reward coupon details.'],
    ['Referral progress','Fires at referral milestones (1, 3, 5 referrals). Shows current count, next milestone, and reward tier details.'],
    ['New customer welcome (referred)','Fires to the referred customer on their first purchase. Acknowledges the referral and provides the referred_customer deal.'],
  ] as $em): ?>
  <div style="display:flex;gap:14px;margin-bottom:14px;padding:12px 14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:8px">
    <span style="font-size:20px;flex-shrink:0">📧</span>
    <div>
      <p style="margin:0 0 4px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $em[0] ); ?></p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $em[1] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'emails' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Customer Lifecycle Emails (19)</h2></div>
  <?php foreach ([
    ['BOGO Confirmation','Fires on woocommerce_order_status_completed when the order has a BOGO discount. Shows savings amount. Preheader: "You saved [amount] on your order".'],
    ['Tier Upgrade','Fires when a customer moves from one loyalty tier to the next. Shows new tier, new discount boost percentage, and tier benefits.'],
    ['Streak Bonus','Fires at streak milestones (4, 8, 12 consecutive months). Shows streak count and the reward applied.'],
    ['Referral Reward Earned','Fires when a referred customer completes their first purchase. Shows referred customer name and coupon reward.'],
    ['VIP Unlocked','Fires when any VIP role is assigned. Shows VIP tier, deal access details, and a link to view VIP deals.'],
    ['Free Gift Added','Fires when a free gift item is added to an order via an auto-add rule. Shows the gift product name.'],
    ['Deal Expiry Warning','Fires 48 hours before a scheduled rule ends. Shows deal name and expiry date and time.'],
    ['Winback','Fires when lapsed_90 role is assigned. Contains a re-engagement deal. Subject: "[Store]: We haven\'t seen you in a while".'],
    ['Cart Nudge','Fired by the Abandon Nudge superpower after cart inactivity. Contains the best current active deal and a direct link back to the cart.'],
    ['Threshold Nudge','Fired by the Email Notifications superpower when a customer is within a configured amount of unlocking a threshold deal. Shows exactly how much more to spend.'],
    ['Referral Progress','Fires at referral count milestones (1, 3, 5). Shows progress toward next milestone and current reward tier.'],
    ['Order Milestone','Fires at order_3, order_5, order_10, order_15 milestones. Acknowledges loyalty and unlocks next tier deals.'],
    ['Streak At-Risk','Fires when streak_at_risk role is assigned. Urgency message to complete a purchase before the streak resets.'],
    ['Subscriber At-Risk','Fires when subscriber_at_risk role is assigned. Retention deal with a direct renewal link.'],
    ['Anniversary','Fires on the customer\'s store registration anniversary. Celebratory with an anniversary-specific deal.'],
    ['Post-Purchase','Fires 7 days after a qualifying order. Suggests complementary products and shows the next active deal.'],
    ['Lapsed Reactivation','Fires to customers inactive for 90+ days. Win-back deal with urgency. Subject: "[Store]: Your deal is waiting".'],
    ['New Customer Welcome','Fires on the first completed order from a new customer. Sets expectations for the loyalty program and referral system.'],
    ['Deal Unlocked','Fires at the moment a customer\'s cart crosses a deal threshold. Real-time notification showing the exact deal now applied.'],
  ] as $i => $em): ?>
  <div style="display:flex;gap:12px;align-items:flex-start;margin-bottom:10px;padding:10px 12px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:6px">
    <span style="font-size:11px;font-weight:800;color:var(--gt-subtle);min-width:22px;text-align:right;margin-top:3px"><?php echo esc_html( $i+1 ); ?></span>
    <div>
      <p style="margin:0 0 3px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $em[0] ); ?></p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft)"><?php echo esc_html( $em[1] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Email Theme Selector</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">System B emails use one of 8 dark themes selectable at GT BOGO Engine → Settings → Email Theme. All themes use a dark background that matches the GT BOGO Engine aesthetic and renders well across major email clients.</p>
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px">
    <?php foreach ([
      ['Midnight','#E10000','#070C1C'],
      ['Ocean','#0ea5e9','#040d1a'],
      ['Forest','#16a34a','#04100a'],
      ['Royal','#7c3aed','#0a0714'],
      ['Obsidian','#d97706','#0a0a08'],
      ['Ember','#ea580c','#110804'],
      ['Slate','#06b6d4','#080d14'],
      ['Rose','#e11d48','#120608'],
    ] as $theme): ?>
    <div style="border-radius:8px;overflow:hidden;border:1px solid var(--gt-border)">
      <div style="height:36px;background:<?php echo esc_html( $theme[2] ); ?>;border-bottom:3px solid <?php echo esc_html( $theme[1] ); ?>"></div>
      <div style="padding:8px;background:var(--gt-card);text-align:center">
        <p style="margin:0;font-size:11px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $theme[0] ); ?></p>
        <p style="margin:2px 0 0;font-size:10px;color:var(--gt-subtle)"><?php echo esc_html( $theme[1] ); ?></p>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <p style="margin-top:14px;font-size:13px;color:var(--gt-subtle)">The accent color picker in Settings overrides the theme accent for any of the 8 themes, letting you match your exact brand color while keeping the dark background structure.</p>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'scheduler' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Campaign Scheduler</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The Campaign Scheduler runs via WP-Cron on an hourly basis. It activates and deactivates rules based on configured date and time windows. Rules with <code style="color:#fbbf24">sched=True</code> in their pack JSON are designed for scheduler use — the countdown timer superpower fires automatically when they are active.</p>
  <?php foreach ([
    ['Schedule a rule','Go to Campaign Scheduler. Select a rule from the dropdown, set a start date, end date, start time, and end time. Save. The scheduler picks it up on the next hourly cron tick.'],
    ['Rule activation','At the scheduled start time, the scheduler sets the rule status to active and clears the rules transient. The rule fires immediately on the next cart load.'],
    ['Rule deactivation','At the scheduled end time, the scheduler sets the rule status to inactive. Rules without an end_date are never auto-deactivated — only rules with a defined end date are deactivated by the scheduler.'],
    ['Countdown timer','The Countdown Timer superpower reads the end_date from the active schedule and displays a live HH:MM:SS countdown. When time expires, the rule deactivates and the countdown disappears automatically.'],
    ['Timezone','All schedule times use the WordPress timezone setting from Settings → General. Verify your timezone is set correctly before scheduling campaigns.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'settings' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Settings Reference</h2></div>
  <?php
  $setting_groups = [
    'Cart Behaviour' => [
      ['gtbogo_auto_add','Auto-add qualifying items to cart when deal threshold is met. Requires matching product to be in stock.'],
      ['gtbogo_auto_remove','Auto-remove free items if cart no longer qualifies. Prevents discount abuse on partial cart edits.'],
      ['gtbogo_show_discount_label','Show a "BOGO Deal Applied" label in the cart item row for discounted items.'],
      ['gtbogo_discount_label_text','Custom text for the discount label. Default: "BOGO Deal Applied".'],
      ['gtbogo_cart_notice','Enable a cart-level notice showing the active deal name.'],
      ['gtbogo_cart_notice_pos','Position of cart notice: above_cart, below_cart, or woocommerce_cart_totals_before_shipping.'],
    ],
    'Discount Engine' => [
      ['gtbogo_conflict_strategy','How to handle multiple qualifying rules: first_match, highest_discount, or lowest_priority.'],
      ['gtbogo_max_discount_pct','Maximum discount percentage per order. Set to 0 to disable the cap. Prevents runaway stacking.'],
      ['gtbogo_exclude_roles','WP roles that are excluded from all BOGO discounts. Useful for wholesale or reseller accounts.'],
    ],
    'Display' => [
      ['gtbogo_badge_position','Product badge position: top-left, top-right, bottom-left, bottom-right.'],
      ['gtbogo_badge_inherit_theme','Whether badges should inherit the WooCommerce product badge style or use GT BOGO Engine\'s own styling.'],
      ['gtbogo_progress_bar','Enable the cart progress bar globally.'],
      ['gtbogo_progress_bar_pos','Cart progress bar position: cart_header, before_cart, after_cart, mini_cart.'],
    ],
    'Performance' => [
      ['gtbogo_cache_rules','Cache active rules to a transient to avoid repeated DB queries on every cart load. Recommended: enabled.'],
      ['gtbogo_cache_ttl','Transient TTL in seconds. Default: 3600 (1 hour). The cache clears automatically when rules are saved.'],
      ['gtbogo_ajax_cart','Enable AJAX cart compatibility mode for headless or custom cart implementations.'],
    ],
    'Email' => [
      ['gtbogo_customer_emails_enabled','Master toggle for all System B customer lifecycle emails. Requires store name, logo, and WooCommerce from-email to be configured before enabling.'],
      ['gtbogo_email_accent_color','Hex color that overrides the theme accent for System B emails. Set to empty to use the theme default.'],
      ['gtbogo_email_logo_url','Direct URL to your store logo image. If empty, the WordPress site icon is used.'],
      ['gtbogo_email_theme','Email theme selection. One of: midnight, ocean, forest, royal, obsidian, ember, slate, rose.'],
    ],
    'Analytics & Logging' => [
      ['gtbogo_analytics_enabled','Enable analytics tracking. Records order_id, rule_id, order_total, and discount_amount to gtbogo_analytics on every BOGO order.'],
      ['gtbogo_analytics_retention_days','How many days to retain analytics records. Default: 365.'],
      ['gtbogo_analytics_exclude_roles','WP roles excluded from analytics tracking (e.g. admin, shop_manager).'],
      ['gtbogo_log_enabled','Enable the audit log. Records all rule changes, activation events, and admin actions.'],
      ['gtbogo_log_max_entries','Maximum audit log entries before rotation. Default: 1000.'],
      ['gtbogo_log_min_level','Minimum log level: debug, info, warning, error.'],
      ['gtbogo_log_alert_email','Email address for error-level log alert notifications.'],
    ],
    'Advanced' => [
      ['gtbogo_debug_mode','Enable debug output in the browser console. Shows rule evaluation, condition matching, and discount calculation on every cart update. Never enable in production.'],
      ['gtbogo_uninstall_data','Whether to delete all plugin data (options, tables, transients) on plugin uninstall. Default: off.'],
    ],
  ];
  foreach ( $setting_groups as $group => $settings ): ?>
  <div style="margin-bottom:24px">
    <p style="margin:0 0 12px;font-size:12px;font-weight:800;color:var(--gt-subtle);text-transform:uppercase;letter-spacing:.1em"><?php echo esc_html( $group ); ?></p>
    <?php foreach ( $settings as $s ): ?>
    <div style="display:flex;gap:14px;align-items:flex-start;margin-bottom:10px;padding:10px 14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:6px">
      <code style="font-size:11px;color:#fbbf24;background:rgba(255,255,255,0.05);padding:3px 8px;border-radius:4px;flex-shrink:0;white-space:nowrap;margin-top:2px"><?php echo esc_html( $s[0] ); ?></code>
      <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.5"><?php echo esc_html( $s[1] ); ?></p>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'pricing' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Pricing</h2></div>
  <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:16px;margin-bottom:20px">
    <?php foreach ([
      ['PRO License','$199','per year','Annual license for 1 site. Unlocks all 200 PRO packs, all backend intelligence superpowers, customer intelligence, email system, and all enterprise features.','#E10000'],
      ['Individual Pack','$39.99','one-time','Single industry pack. 10 enterprise rules. Lifetime access. Import once, rules are yours permanently.','#3b82f6'],
      ['Starter Bundle','$149','one-time','5 packs: Cart Threshold, Flash Sale, Free Gift, Visual Badge, Savings Display. Best for stores launching BOGO for the first time.','#22c55e'],
      ['Growth Bundle','$249','one-time','9 packs: Starter 5 + Stack Master, Countdown Urgency, Social Proof, New Customer. Best for established stores.','#f59e0b'],
      ['Complete Bundle','$399','one-time','15 packs: All Growth packs + Smart Upsell, Inventory Clearance, VIP Loyalty, Tiered Quantity, Seasonal, Quick Deal. Best value per pack.','#8b5cf6'],
    ] as $p): ?>
    <div style="padding:20px;border-radius:10px;border:2px solid <?php echo esc_html( $p[4] ); ?>33;background:<?php echo esc_html( $p[4] ); ?>08">
      <p style="margin:0 0 8px;font-size:13px;font-weight:800;color:var(--gt-white)"><?php echo esc_html( $p[0] ); ?></p>
      <div style="display:flex;align-items:baseline;gap:4px;margin-bottom:6px">
        <span style="font-size:28px;font-weight:900;color:<?php echo esc_html( $p[4] ); ?>"><?php echo esc_html( $p[1] ); ?></span>
        <span style="font-size:13px;color:var(--gt-subtle)"><?php echo esc_html( $p[2] ); ?></span>
      </div>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $p[3] ); ?></p>
    </div>
    <?php endforeach; ?>
  </div>
  <div style="padding:16px;background:rgba(34,197,94,0.05);border:1px solid rgba(34,197,94,0.2);border-radius:8px">
    <p style="margin:0 0 4px;font-size:13px;font-weight:700;color:#22c55e">Agency Pricing Note</p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.6">With a $199/yr PRO license you can charge clients $299–$499/yr for "Promotions Manager PRO" under your own branding using the White Label feature. Enable Hide Upgrade Prompts so clients never see GT BOGO Engine branding inside the dashboard.</p>
  </div>
</div>

<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">License System</h2></div>
  <?php foreach ([
    ['License activation','Enter your key at GT BOGO Engine → License and click Activate. The key is verified against the license server at graphictshirts.shop/bogo/api/license-verify.php. Activation is instant.'],
    ['Pack download','After importing a pack, the plugin verifies license ownership with the license server before serving the JSON. No zip files — pack data is served directly and stored in the gtbogo_owned_packs database table.'],
    ['Bundle keys','Bundle purchases generate a single license key (format: GTBOGO-BUNDLE-XXXXXXXXXXXXXXXX). Entering this key in the plugin automatically unlocks and downloads all packs included in that bundle.'],
    ['License expiry','PRO licenses are annual. 30-day and 15-day expiry warning emails are sent automatically. After expiry, existing rules continue to work but pack imports and new PRO features are locked until renewal.'],
    ['Lost license','Use the self-service retrieval portal at graphictshirts.shop/bogo/retrieve-license.php. Enter your purchase email, receive a verification code, and retrieve your key. No support ticket required.'],
    ['Domain transfer','Moving to a new domain. Use the self-service transfer form at graphictshirts.shop/bogo/#license-transfer. Enter your license key, purchase email, and new domain. Transfers are limited to once every 90 days. After transferring, re-download your Pro Packs from the My Packs page inside the plugin. A confirmation email will be sent automatically. No support contact needed.'],
    ['License terms','Your license is non-transferable between owners and locked to one domain at a time. Redistribution or sharing of your license key or Pro Pack files is a violation of the license agreement and may result in license termination.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'analytics' ):
// ══════════════════════════════════════════════════════════════════════════════
global $wpdb;
$total_orders    = (int)   $wpdb->get_var( "SELECT COUNT(DISTINCT order_id) FROM {$wpdb->prefix}gtbogo_analytics" );
$total_revenue   = (float) $wpdb->get_var( "SELECT COALESCE(SUM(order_total),0) FROM {$wpdb->prefix}gtbogo_analytics" );
$total_discounts = (float) $wpdb->get_var( "SELECT COALESCE(SUM(discount_amount),0) FROM {$wpdb->prefix}gtbogo_analytics" );
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Analytics Overview</h2></div>
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:20px">
    <?php foreach ([
      ['Total BOGO Orders', number_format($total_orders), '#E10000'],
      ['Revenue Influenced', '$'.number_format($total_revenue,2), '#22c55e'],
      ['Discount Given', '$'.number_format($total_discounts,2), '#f59e0b'],
    ] as $m): ?>
    <div style="background:var(--gt-card);border:1px solid var(--gt-border);border-radius:10px;padding:18px;text-align:center">
      <div style="font-size:24px;font-weight:900;color:<?php echo esc_html( $m[2] ); ?>;line-height:1;margin-bottom:6px"><?php echo esc_html( $m[1] ); ?></div>
      <div style="font-size:12px;color:var(--gt-subtle)"><?php echo esc_html( $m[0] ); ?></div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php foreach ([
    ['What is tracked','Every order where a BOGO rule fires records: order_id, rule_id, order_total, discount_amount, and date_created to the gtbogo_analytics table. This is a lightweight append-only log — no customer PII is stored in analytics.'],
    ['Revenue influenced','This is the total cart value of all orders where a BOGO deal fired — not just the discount amount. It measures the full revenue that BOGO rules contributed to, which is the correct KPI for promotion attribution.'],
    ['Efficiency metric','(Revenue − Discount) ÷ Revenue. Above 80% means your deals are driving revenue without excessive cost. Below 60% means the discount is too aggressive for the volume it generates. Visible in the Rule Leaderboard.'],
    ['CSV export','Export the full analytics dataset to CSV from the Analytics page. Includes all fields for import into external BI tools. Date range is configurable.'],
    ['Retention','Analytics records are retained for the number of days configured at gtbogo_analytics_retention_days (default 365). A cleanup routine runs on the daily cron.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'abtesting' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">A/B Testing</h2></div>
  <?php foreach ([
    ['What you can test','Any two active rules can be A/B tested — same product targeting, different discount values or mechanics. Rule A fires for 50% of customers, Rule B for the other 50%, split by user ID hash.'],
    ['Creating a test','Go to A/B Testing. Select Rule A and Rule B. Name the test and set the traffic split percentage. Click Start Test. The engine routes customers to their assigned variant on every cart load and records results to gtbogo_ab_results.'],
    ['Metrics','Each variant tracks orders, revenue influenced, discount cost, and efficiency score. Statistical significance is calculated using a z-test. Results are visualised as a performance comparison chart.'],
    ['Declaring a winner','When statistical significance reaches 95%+ confidence, the winning rule is highlighted. Click Declare Winner to disable the losing rule and convert the winning rule to full traffic.'],
    ['Considerations','Rules under A/B test should have the same priority. Do not test rules in different priority tiers — the test measures discount mechanics, not priority ordering.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'conditions' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">Rule Conditions</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The Conditions page applies sitewide conditions that filter which rules are considered before priority evaluation. These conditions layer on top of per-rule conditions in the pack JSON.</p>
  <?php foreach ([
    ['Cart minimum value','Rules only fire if the cart total is above this threshold. Applied before any rule evaluation.'],
    ['Cart maximum value','Rules only fire if the cart total is below this maximum. Useful for protecting margin on very large orders.'],
    ['Customer type','Filter by new, returning, or all customers. new = no previous completed orders. returning = at least one previous completed order.'],
    ['User roles','Restrict all rules to specific WP roles. OR logic — any matching role qualifies. Used for wholesale or trade account exclusions.'],
    ['Product categories','Only apply rules to products in specified categories. Useful for sitewide category restrictions that apply to all rules.'],
    ['Excluded products','Never apply any rule to these specific product IDs regardless of rule configuration.'],
    ['Match ALL vs ANY','The Conditions page lets you select whether ALL conditions must match or ANY single condition match is sufficient to allow rule evaluation. Toggle between AND/OR logic per condition group.'],
  ] as $item): ?>
  <div style="display:flex;gap:12px;align-items:flex-start;margin-bottom:12px;padding:12px 14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:6px">
    <svg style="flex-shrink:0;margin-top:3px" width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="7" stroke="#E10000" stroke-width="1.5"/><path d="M8 5v3.5L10 10" stroke="#E10000" stroke-width="1.5" stroke-linecap="round"/></svg>
    <div>
      <p style="margin:0 0 3px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft)"><?php echo esc_html( $item[1] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'whitelabel' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">White Label</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The White Label page lets agencies rebrand the entire plugin admin for clients. When enabled, clients see your agency name and plugin branding — GT BOGO Engine is completely hidden.</p>
  <?php foreach ([
    ['Plugin Name','Replaces "GT BOGO Engine" throughout the admin with your chosen plugin name (e.g. "Promotions Manager PRO").'],
    ['Menu Label','The WordPress admin sidebar menu label. Default: "GT BOGO Engine".'],
    ['Support URL','Your agency support URL. Replaces all "Contact Support" links inside the plugin admin.'],
    ['Docs URL','Your agency documentation URL. Replaces the Documentation tab link.'],
    ['Agency Name','Shown in the admin footer alongside the powered-by attribution.'],
    ['Hide Branding','Removes all GT BOGO Engine / Graphic T-Shirts references from the admin UI.'],
    ['Hide Upgrade Prompts','Removes all upgrade CTAs and PRO Pack purchase buttons from the admin. Essential for client installations where they should not see your supplier pricing.'],
    ['Customer-facing white label','System B emails are always white-labelled automatically — GT BOGO Engine is never visible to the store\'s customers regardless of white label settings. The white label page only affects the WordPress admin UI.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'integrations' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Integrations</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">All integrations fire only on orders where a BOGO rule applied — never on regular orders. This prevents polluting external systems with non-BOGO data.</p>
  <?php foreach ([
    ['Mailchimp','Tags customers in Mailchimp with their current loyalty tier and deal type on every BOGO order. Requires Mailchimp API key in Settings. Enables tier-segmented campaign automation in Mailchimp.'],
    ['Klaviyo','Sends BOGO order events to Klaviyo with custom properties: rule_name, discount_amount, loyalty_tier, vip_status. Enables Klaviyo flow triggers on BOGO deal milestones.'],
    ['Google Analytics (GA4)','Fires a purchase event with a bogo_deal custom parameter on every BOGO order. Enables BOGO conversion tracking in GA4 reports.'],
    ['Facebook Pixel','Fires a Purchase event with a custom parameter bogo=true on BOGO orders. Enables BOGO-specific custom audiences in Meta Ads.'],
    ['Zapier / Make','The REST API endpoints work with Zapier Webhooks and Make HTTP modules. Use PATCH /rules/{id}/status to activate or deactivate rules based on external triggers — CRM updates, inventory alerts, email campaign sends.'],
    ['WooCommerce Subscriptions','The plugin detects WooCommerce Subscriptions and automatically assigns subscriber_active and subscriber_at_risk roles based on subscription status. Rules targeting these roles fire correctly for subscription customers.'],
    ['WPML / Polylang','Nudge, badge, and email copy can be translated via WPML or Polylang string translation. All customer-facing strings are registered in the gt-bogo-engine text domain.'],
  ] as $item): ?>
  <div style="display:flex;gap:14px;align-items:flex-start;margin-bottom:14px;padding:14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:8px">
    <span style="font-size:20px;flex-shrink:0">🔌</span>
    <div>
      <p style="margin:0 0 4px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
      <p style="margin:0;font-size:12px;color:var(--gt-soft);line-height:1.6"><?php echo esc_html( $item[1] ); ?></p>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'restapi' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card" style="margin-bottom:20px">
  <div class="gt-card-header"><h2 class="gt-card-title">REST API</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The REST API gives external tools, headless storefronts, and automation platforms read and write access to rules and analytics. All endpoints require a bearer token from the REST API page.</p>
  <?php foreach ([
    ['GET /wp-json/gt-bogo/v1/rules','Returns all rules with their full configuration. Supports ?status=active filter.'],
    ['GET /wp-json/gt-bogo/v1/rules/{id}','Returns a single rule by ID.'],
    ['POST /wp-json/gt-bogo/v1/rules','Creates a new rule. Accepts the full rule schema as JSON body.'],
    ['PATCH /wp-json/gt-bogo/v1/rules/{id}','Updates specific fields on a rule. Use to change status, priority, or discount values without replacing the full rule.'],
    ['PATCH /wp-json/gt-bogo/v1/rules/{id}/status','Toggles rule status between active and inactive. Body: {"status":"active"}. Ideal for Zapier/Make automation.'],
    ['DELETE /wp-json/gt-bogo/v1/rules/{id}','Deletes a rule permanently.'],
    ['GET /wp-json/gt-bogo/v1/analytics','Returns analytics summary. Supports ?days=30 parameter.'],
    ['GET /wp-json/gt-bogo/v1/analytics/top-rules','Returns top 10 rules by fire count with revenue and discount metrics.'],
  ] as $ep): ?>
  <div style="margin-bottom:10px;padding:12px 14px;background:var(--gt-card);border:1px solid var(--gt-border);border-radius:6px">
    <code style="font-size:12px;color:#fbbf24;display:block;margin-bottom:6px"><?php echo esc_html( $ep[0] ); ?></code>
    <p style="margin:0;font-size:13px;color:var(--gt-soft)"><?php echo esc_html( $ep[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'geo' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Geo Targeting</h2></div>
  <?php foreach ([
    ['How it works','Country detection uses the visitor\'s IP address via a lightweight server-side lookup. No external API calls — the MaxMind GeoLite2 database is used locally if available, otherwise a free IP-API endpoint.'],
    ['Per-country messages','Configure different nudge messages and announcement bar copy per country from the Geo Targeting page. These override the rule\'s default nudge messages for visitors from configured countries.'],
    ['Currency integration','Geo Targeting works alongside Multi-Currency — when a country match is found, both the geo-specific message and the country\'s preferred currency are applied simultaneously.'],
    ['VPN considerations','IP-based detection is not 100% accurate for VPN users. Geo Targeting is designed for marketing personalisation, not access restriction — no deals are blocked based on location, only messaging changes.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'currency' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Multi-Currency</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">150+ world currencies are supported. The Multi-Currency page lets you configure exchange rates, symbols, and display preferences per currency. Cart threshold conditions in rules are evaluated in the base WooCommerce currency and converted for display.</p>
  <?php foreach ([
    ['Configuration','Go to GT BOGO Engine → Multi-Currency. Search for a currency, set the exchange rate relative to your base currency, and configure the symbol position. Save.'],
    ['Cart thresholds','min_cart_value in rules is always defined in your base currency. The Multi-Currency system converts this for display in the progress bar and nudge messages automatically.'],
    ['Coverage','Americas, Europe, Middle East, Africa, and Asia Pacific. All major ISO 4217 currencies plus common crypto display symbols.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'dealpage' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Deal Page</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The Deal Page creates a dedicated storefront page that displays all currently active BOGO deals in a browsable format. Customers can see every active deal, the qualifying products, and add items directly from the page.</p>
  <?php foreach ([
    ['Page setup','Configure a page title, slug, heading, and subtext. The plugin creates a WordPress shortcode you embed in any page, or auto-creates the page on setup.'],
    ['Deal display','Each active rule appears as a deal card showing the deal name, discount mechanics ("Buy 2 Get 1 FREE"), qualifying categories or products, and an Add to Cart button.'],
    ['Badge integration','The badge_text from each rule\'s superpower config appears on the deal card. Consistent with product-page badges.'],
    ['SEO','The deal page uses a standard WordPress page with full Yoast/RankMath SEO compatibility. Configure the page title and meta description through your SEO plugin.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php
// ══════════════════════════════════════════════════════════════════════════════
elseif ( $doc === 'segments' ):
// ══════════════════════════════════════════════════════════════════════════════
?>
<div class="gt-card">
  <div class="gt-card-header"><h2 class="gt-card-title">Customer Segments</h2></div>
  <p style="font-size:14px;color:var(--gt-soft);line-height:1.7;margin:0 0 16px">The Segments page lets you build named customer groups using compound conditions. Segments are evaluated against the customer database and can be used to target rules, schedule segment-specific campaigns, and filter analytics.</p>
  <?php foreach ([
    ['Segment conditions','Order count range, lifetime spend range, last purchase date, current loyalty tier, VIP status, assigned WP roles. Conditions can be combined with ALL/ANY logic.'],
    ['Using segments in rules','When a segment is created, it generates a corresponding custom WP role that is assigned to all matching customers on the nightly cron. Rules can then target that role normally.'],
    ['Segment size','The segment list shows a live customer count for each saved segment. Count updates on every nightly role evaluation run.'],
    ['Export','Segment member lists can be exported to CSV from the Segments page for use in external email marketing platforms.'],
  ] as $item): ?>
  <div style="border-left:3px solid var(--gt-border);padding:12px 16px;margin-bottom:12px;border-radius:0 6px 6px 0">
    <p style="margin:0 0 5px;font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $item[0] ); ?></p>
    <p style="margin:0;font-size:13px;color:var(--gt-soft);line-height:1.65"><?php echo esc_html( $item[1] ); ?></p>
  </div>
  <?php endforeach; ?>
</div>

<?php endif; ?>

</div><!-- end content -->
</div><!-- end grid -->

<script>
// ── Inline doc navigation — no page reload ──────────────────────────────────
(function() {
    function animateCounters() {
        document.querySelectorAll('.gt-counter').forEach(function(el) {
            var target = parseInt(el.getAttribute('data-target').replace(/[^0-9]/g,''));
            if (!target || target < 10) return;
            var start = 0, duration = 1200, step = Math.ceil(target / 60);
            var timer = setInterval(function() {
                start += step;
                if (start >= target) { start = target; clearInterval(timer); }
                var raw = el.getAttribute('data-target');
                if (raw.startsWith('$')) el.textContent = '$' + start.toLocaleString();
                else el.textContent = start.toLocaleString();
            }, duration / (target / step));
        });
    }

    function setActiveLink(doc) {
        document.querySelectorAll('.gt-doc-nav-link').forEach(function(a) {
            var isActive = a.getAttribute('data-doc') === doc;
            a.style.fontWeight     = isActive ? '700' : '500';
            a.style.color          = isActive ? '#ffffff' : 'var(--gt-soft)';
            a.style.background     = isActive ? 'rgba(225,0,0,0.12)' : 'transparent';
            a.style.borderLeft     = isActive ? '3px solid #E10000' : '3px solid transparent';
        });
    }

    function loadSection(url, doc, pushState) {
        var content = document.getElementById('gt-doc-content');
        if (!content) return;
        content.style.opacity = '0';
        content.style.transition = 'opacity 0.12s ease';

        fetch(url, { credentials: 'same-origin' })
            .then(function(r) { return r.text(); })
            .then(function(html) {
                var parser = new DOMParser();
                var doc2 = parser.parseFromString(html, 'text/html');
                var newContent = doc2.getElementById('gt-doc-content');
                if (newContent) {
                    content.innerHTML = newContent.innerHTML;
                    content.style.opacity = '1';
                    animateCounters();
                    if (pushState) {
                        history.pushState({ doc: doc }, '', url);
                    }
                    setActiveLink(doc);
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                } else {
                    window.location.href = url;
                }
            })
            .catch(function() {
                window.location.href = url;
            });
    }

    document.addEventListener('click', function(e) {
        var link = e.target.closest('.gt-doc-nav-link');
        if (!link) return;
        e.preventDefault();
        var doc = link.getAttribute('data-doc');
        var url = link.getAttribute('href');
        if (!url || !doc) return;
        loadSection(url, doc, true);
    });

    window.addEventListener('popstate', function(e) {
        if (e.state && e.state.doc) {
            var params = new URLSearchParams(window.location.search);
            loadSection(window.location.href, e.state.doc, false);
        }
    });

    // Init counter animation on first load
    animateCounters();
})();

// Animate counter numbers on page load (kept for compat)
document.querySelectorAll('.gt-counter').forEach(function(el) {
    var target = parseInt(el.getAttribute('data-target').replace(/[^0-9]/g,''));
    if (!target || target < 10) return;
    var start = 0, duration = 1200, step = Math.ceil(target / 60);
    var timer = setInterval(function() {
        start += step;
        if (start >= target) { start = target; clearInterval(timer); }
        var raw = el.getAttribute('data-target');
        if (raw.startsWith('$')) el.textContent = '$' + start.toLocaleString();
        else el.textContent = start.toLocaleString();
    }, duration / (target / step));
});
</script>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
