<?php
/**
 * Archive Template: stb_encyclopedia
 * URL: /encyclopedia/
 */
$lang = stb_lang();
$is_fa = ($lang === 'fa');
get_header();

// ── Translations ──────────────────────────────────────────────────────────────
$T = [
  'hero_kicker'   => 'TRADING ENCYCLOPEDIA',
  'hero_title'    => 'STB <em>Encyclopedia</em>',
  'hero_desc'     => $is_fa ? 'راهنمای جامع اصطلاحات، مفاهیم و اصول بازارهای مالی. هر آنچه یک معامله‌گر باید بداند.' : 'Your complete guide to financial market terms, concepts and principles. Everything a trader needs to know.',
  'search_ph'     => $is_fa ? 'جستجو در اصطلاحات...' : 'Search terms...',
  'cat_all'       => $is_fa ? 'همه' : 'All',
  'diff_all'      => $is_fa ? 'همه سطوح' : 'All Levels',
  'diff_beg'      => $is_fa ? 'مبتدی' : 'Beginner',
  'diff_int'      => $is_fa ? 'متوسط' : 'Intermediate',
  'diff_adv'      => $is_fa ? 'پیشرفته' : 'Advanced',
  'results'       => $is_fa ? 'نتیجه' : 'results',
  'no_results'    => $is_fa ? 'نتیجه‌ای یافت نشد. کلمه دیگری امتحان کنید.' : 'No results found. Try a different keyword.',
  'read_more'     => $is_fa ? 'بیشتر بخوانید' : 'Read more',
  'cta_title'     => $is_fa ? 'آماده اعمال این مفاهیم هستید؟' : 'Ready to apply these concepts?',
  'cta_desc'      => $is_fa ? 'یک حساب دمو رایگان باز کنید و استراتژی‌هایتان را بدون ریسک آزمایش کنید.' : 'Open a free demo account and test your strategies with zero risk.',
  'cta_btn1'      => $is_fa ? 'افتتاح حساب واقعی' : 'Open Live Account',
  'cta_btn2'      => $is_fa ? 'شبیه‌ساز رایگان' : 'Free Demo',
  'terms_count'   => $is_fa ? 'اصطلاح' : 'terms',
];

// ── Category labels ───────────────────────────────────────────────────────────
$cat_labels_fa = ['forex'=>'فارکس','technical'=>'تحلیل تکنیکال','risk'=>'مدیریت ریسک','platform'=>'پلتفرم','economics'=>'اقتصاد','orders'=>'انواع سفارش','psychology'=>'روانشناسی'];

// ── Fetch ALL terms ───────────────────────────────────────────────────────────
$all_terms = get_posts([
    'post_type'      => 'stb_encyclopedia',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'orderby'        => 'title',
    'order'          => 'ASC',
]);
$total = count($all_terms);

// ── Get categories ────────────────────────────────────────────────────────────
$categories = get_terms(['taxonomy'=>'ency_category','hide_empty'=>true,'orderby'=>'name']);


$login_label_url = $lang==='fa' ? 'https://crm.stbbrokers.com/fa':'https://crm.stbbrokers.com/';
$register_label_url = $lang==='fa' ? 'https://crm.stbbrokers.com/fa/register':'https://crm.stbbrokers.com/register/';
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?> <?php echo $is_fa?'dir="rtl"':''; ?>>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo $is_fa ? 'دانشنامه معاملاتی | STB Provider' : 'Trading Encyclopedia | STB Provider'; ?></title>
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/assets/css/main.min.css?v=<?php echo filemtime(get_template_directory().'/assets/css/main.min.css'); ?>">
<?php if($is_fa): ?>
<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/assets/css/rtl.min.css?v=<?php echo filemtime(get_template_directory().'/assets/css/rtl.min.css'); ?>">
<?php endif; ?>
<style>
/* ── Encyclopedia Archive ──────────────────────────────────────────────────── */
.ency-hero{padding:80px 0 56px;background:var(--bg);position:relative;overflow:hidden;text-align:<?php echo $is_fa?'right':'left'; ?>}
.ency-hero::before{content:'';position:absolute;top:-200px;<?php echo $is_fa?'left':'right'; ?>:-100px;width:600px;height:600px;background:radial-gradient(circle,rgba(200,16,46,.1),transparent 65%);pointer-events:none}
.ency-hero-inner{max-width:1200px;margin:0 auto;padding:0 40px;position:relative;z-index:1}
.ency-kicker{display:inline-flex;align-items:center;gap:8px;padding:5px 14px;border-radius:20px;background:rgba(200,16,46,.08);border:1px solid rgba(200,16,46,.2);font-size:10.5px;font-weight:700;letter-spacing:.16em;color:rgba(200,16,46,.8);text-transform:uppercase;margin-bottom:20px}
.ency-kicker-dot{width:6px;height:6px;border-radius:50%;background:#C8102E;animation:enc-pulse 2s infinite}
@keyframes enc-pulse{0%,100%{opacity:1;box-shadow:0 0 0 0 rgba(200,16,46,.4)}50%{opacity:.8;box-shadow:0 0 0 6px rgba(200,16,46,0)}}
.ency-hero h1{font-size:clamp(36px,5vw,64px);font-weight:700;color:#fff;margin:0 0 16px;line-height:1.1}
.ency-hero h1 em{font-style:normal;color:#C8102E}
.lang-fa .ency-hero h1{font-family:'Vazirmatn',sans-serif;font-size:clamp(30px,4.5vw,56px)}
.ency-hero-desc{font-size:16px;color:rgba(255,255,255,.45);max-width:560px;line-height:1.7;margin-bottom:24px}
.ency-total-badge{display:inline-flex;align-items:center;gap:8px;padding:6px 16px;border-radius:8px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);font-size:13px;color:rgba(255,255,255,.5)}
.ency-total-badge strong{color:#fff}

/* ── Filter bar ── */
.ency-filters{background:rgba(255,255,255,.02);border-bottom:1px solid rgba(255,255,255,.07);position:sticky;top:70px;z-index:100;backdrop-filter:blur(20px)}
.ency-filters-inner{max-width:1200px;margin:0 auto;padding:16px 40px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;direction:<?php echo $is_fa?'rtl':'ltr'; ?>}
.ency-search{flex:1;min-width:200px;max-width:320px;position:relative}
.ency-search-icon{position:absolute;<?php echo $is_fa?'right':'left'; ?>:12px;top:50%;transform:translateY(-50%);color:rgba(255,255,255,.3)}
.ency-search-icon svg{width:14px;height:14px;stroke:currentColor;fill:none}
.ency-search input{width:100%;box-sizing:border-box;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:9px 12px 9px <?php echo $is_fa?'12px':'36px'; ?>;padding-<?php echo $is_fa?'right':'left'; ?>:36px;font-size:13.5px;color:#fff;outline:none;font-family:inherit;transition:border-color .15s}
.ency-search input:focus{border-color:rgba(200,16,46,.35)}
.ency-search input::placeholder{color:rgba(255,255,255,.25)}
.ency-filter-pills{display:flex;gap:6px;flex-wrap:wrap;align-items:center}
.ency-pill{padding:6px 14px;border-radius:20px;font-size:12.5px;font-weight:600;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);color:rgba(255,255,255,.5);cursor:pointer;transition:all .15s;white-space:nowrap}
.ency-pill.active,.ency-pill:hover{background:rgba(200,16,46,.12);border-color:rgba(200,16,46,.35);color:#fff}
.ency-filter-sep{width:1px;height:24px;background:rgba(255,255,255,.1);margin:0 4px}
.ency-results-count{font-size:12px;color:rgba(255,255,255,.3);margin-<?php echo $is_fa?'right':'left'; ?>:auto;white-space:nowrap}

/* ── Grid ── */
.ency-main{max-width:1200px;margin:0 auto;padding:40px 40px 80px;direction:<?php echo $is_fa?'rtl':'ltr'; ?>}
.ency-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px}
@media(max-width:600px){.ency-grid{grid-template-columns:1fr}}

/* ── Term card ── */
.ency-card{background:#0a0c10;border:1px solid rgba(255,255,255,.07);border-radius:14px;padding:22px;text-decoration:none;display:flex;flex-direction:column;gap:12px;transition:border-color .2s,transform .2s,box-shadow .2s;position:relative;overflow:hidden}
.ency-card:hover{border-color:rgba(200,16,46,.3);transform:translateY(-3px);box-shadow:0 8px 32px rgba(200,16,46,.08)}
.ency-card::after{content:'';position:absolute;top:0;<?php echo $is_fa?'right':'left'; ?>:0;right:auto;bottom:0;width:2px;background:#C8102E;transform:scaleY(0);transform-origin:bottom;transition:transform .25s}
.ency-card:hover::after{transform:scaleY(1)}
.ency-card-top{display:flex;align-items:center;justify-content:space-between;gap:8px}
.ency-letter{width:40px;height:40px;border-radius:10px;background:rgba(200,16,46,.08);border:1px solid rgba(200,16,46,.15);display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;color:#C8102E;flex-shrink:0;font-family:'Bebas Neue',sans-serif}
.lang-fa .ency-letter{font-family:'Vazirmatn',sans-serif;font-size:16px}
.ency-card-badges{display:flex;gap:6px;align-items:center;flex-wrap:wrap;justify-content:flex-end}
.ency-cat-badge{font-size:10px;font-weight:700;padding:2px 8px;border-radius:4px;background:rgba(200,16,46,.08);color:rgba(200,16,46,.7);text-transform:uppercase;letter-spacing:.05em}
.ency-diff-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
.ency-diff-dot.beginner{background:#14e0a3}
.ency-diff-dot.intermediate{background:#ff9800}
.ency-diff-dot.advanced{background:#C8102E}
.ency-card-title{font-size:17px;font-weight:700;color:#fff;line-height:1.2;text-align:<?php echo $is_fa?'right':'left'; ?>}
.lang-fa .ency-card-title{font-family:'Vazirmatn',sans-serif}
.ency-card-def{font-size:13px;color:rgba(255,255,255,.45);line-height:1.6;flex:1;text-align:<?php echo $is_fa?'right':'left'; ?>}
.ency-card-link{font-size:12.5px;font-weight:700;color:#C8102E;display:flex;align-items:center;gap:6px;margin-top:auto;<?php echo $is_fa?'flex-direction:row-reverse;justify-content:flex-end':''; ?>}
.ency-card-link svg{width:14px;height:14px;stroke:currentColor;fill:none;<?php echo $is_fa?'transform:scaleX(-1)':''; ?>}
.ency-card[data-hidden="1"]{display:none}

/* ── Empty state ── */
.ency-empty{display:none;text-align:center;padding:80px 20px;grid-column:1/-1}
.ency-empty svg{stroke:rgba(200,16,46,.3);fill:none;width:48px;height:48px;margin-bottom:16px}
.ency-empty-text{font-size:15px;color:rgba(255,255,255,.3)}
.ency-empty.visible{display:block}

/* ── Alphabet bar ── */
.ency-alpha{display:flex;gap:4px;flex-wrap:wrap;margin-bottom:24px;direction:ltr}
.ency-alpha-btn{min-width:32px;height:32px;border-radius:6px;font-size:12px;font-weight:700;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);color:rgba(255,255,255,.4);cursor:pointer;transition:all .15s;display:flex;align-items:center;justify-content:center;padding:0 6px}
.ency-alpha-btn.active,.ency-alpha-btn:hover{background:rgba(200,16,46,.12);border-color:rgba(200,16,46,.3);color:#fff}
.ency-alpha-btn:disabled{opacity:.25;cursor:default;pointer-events:none}

/* ── CTA strip ── */
.ency-cta{background:linear-gradient(135deg,rgba(200,16,46,.08),transparent);border-top:1px solid rgba(200,16,46,.15);padding:48px 40px;text-align:center}
.ency-cta-inner{max-width:600px;margin:0 auto}
.ency-cta h3{font-size:28px;font-weight:700;color:#fff;margin-bottom:10px}
.lang-fa .ency-cta h3{font-family:'Vazirmatn',sans-serif}
.ency-cta p{font-size:15px;color:rgba(255,255,255,.45);margin-bottom:24px}
.ency-cta-btns{display:flex;gap:12px;justify-content:center;flex-wrap:wrap}

@media(max-width:768px){
  .ency-hero-inner,.ency-filters-inner,.ency-main{padding-left:20px;padding-right:20px}
  .ency-filters-inner{gap:8px}
  .ency-hero{padding:60px 0 40px}
  .ency-hero-desc{font-size:14.5px}
}
</style>
</head>
<body class="<?php echo $is_fa?'lang-fa rtl':'lang-en'; ?>">
<?php // header already included via get_header() which handles body open ?>

<!-- Hero -->
<section class="ency-hero">
  <div class="ency-hero-inner">
    <div class="ency-kicker"><span class="ency-kicker-dot"></span><?php echo $T['hero_kicker']; ?></div>
    <h1><?php echo $T['hero_title']; ?></h1>
    <p class="ency-hero-desc"><?php echo $T['hero_desc']; ?></p>
    <div class="ency-total-badge">
      <strong><?php echo $total; ?></strong> <?php echo $T['terms_count']; ?>
    </div>
  </div>
</section>

<!-- Filters -->
<div class="ency-filters">
  <div class="ency-filters-inner">
    <!-- Search -->
    <div class="ency-search">
      <div class="ency-search-icon"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35" stroke-width="2" stroke-linecap="round"/></svg></div>
      <input type="text" id="ency-search" placeholder="<?php echo esc_attr($T['search_ph']); ?>" autocomplete="off">
    </div>

    <div class="ency-filter-sep"></div>

    <!-- Categories -->
    <div class="ency-filter-pills" id="ency-cats">
      <button class="ency-pill active" data-cat="all"><?php echo $T['cat_all']; ?></button>
      <?php foreach($categories as $cat):
        $fa_label = get_term_meta($cat->term_id,'_ency_cat_fa',true);
        $label = $is_fa && $fa_label ? $fa_label : $cat->name;
      ?>
      <button class="ency-pill" data-cat="<?php echo esc_attr($cat->slug); ?>"><?php echo esc_html($label); ?></button>
      <?php endforeach; ?>
    </div>

    <div class="ency-filter-sep"></div>

    <!-- Difficulty -->
    <div class="ency-filter-pills" id="ency-diffs">
      <button class="ency-pill active" data-diff="all"><?php echo $T['diff_all']; ?></button>
      <button class="ency-pill" data-diff="beginner"><?php echo $T['diff_beg']; ?></button>
      <button class="ency-pill" data-diff="intermediate"><?php echo $T['diff_int']; ?></button>
      <button class="ency-pill" data-diff="advanced"><?php echo $T['diff_adv']; ?></button>
    </div>

    <span class="ency-results-count" id="ency-count"><?php echo $total; ?> <?php echo $T['results']; ?></span>
  </div>
</div>

<!-- Main content -->
<div class="ency-main">

  <!-- Alphabet filter -->
  <div class="ency-alpha" id="ency-alpha">
    <?php
    $letters = [];
    foreach($all_terms as $t) {
        $first = strtoupper(mb_substr($t->post_title,0,1));
        $letters[$first] = true;
    }
    $all_alpha = range('A','Z');
    foreach($all_alpha as $l):
        $has = isset($letters[$l]);
    ?>
    <button class="ency-alpha-btn<?php echo !$has?' disabled':''; ?>"
            data-letter="<?php echo $l; ?>"
            <?php echo !$has?'disabled':''; ?>><?php echo $l; ?></button>
    <?php endforeach; ?>
    <button class="ency-alpha-btn active" data-letter="all" style="min-width:48px;margin-<?php echo $is_fa?'right':'left'; ?>:8px"><?php echo $is_fa?'همه':'All'; ?></button>
  </div>

  <!-- Grid -->
  <div class="ency-grid" id="ency-grid">
    <?php foreach($all_terms as $post):
      $term_cats = wp_get_post_terms($post->ID,'ency_category');
      $cat_slug  = !empty($term_cats) ? $term_cats[0]->slug : '';
      $cat_name  = !empty($term_cats) ? $term_cats[0]->name : '';
      $cat_fa    = !empty($term_cats) ? get_term_meta($term_cats[0]->term_id,'_ency_cat_fa',true) : '';
      $diff      = get_post_meta($post->ID,'_ency_difficulty',true) ?: 'beginner';
      $short_def = $is_fa ? get_post_meta($post->ID,'_ency_fa_short_def',true) : get_post_meta($post->ID,'_ency_short_def',true);
      $fa_title  = get_post_meta($post->ID,'_ency_fa_title',true);
      $display_title = $post->post_title;
      if(!$short_def) $short_def = $post->post_excerpt;
      $first_letter = strtoupper(mb_substr($post->post_title,0,1));
      $display_cat = $is_fa && $cat_fa ? $cat_fa : $cat_name;
      $url = get_permalink($post->ID) . ($is_fa ? '?lang=fa' : '');
    ?>
    <a href="<?php echo esc_url($url); ?>"
       class="ency-card"
       data-cat="<?php echo esc_attr($cat_slug); ?>"
       data-diff="<?php echo esc_attr($diff); ?>"
       data-letter="<?php echo esc_attr($first_letter); ?>"
       data-search="<?php echo esc_attr(strtolower($post->post_title.' '.$fa_title.' '.$short_def)); ?>">
      <div class="ency-card-top">
        <div class="ency-letter"><?php echo esc_html($first_letter); ?></div>
        <div class="ency-card-badges">
          <?php if($display_cat): ?><span class="ency-cat-badge"><?php echo esc_html($display_cat); ?></span><?php endif; ?>
          <span class="ency-diff-dot <?php echo esc_attr($diff); ?>" title="<?php echo esc_attr($diff); ?>"></span>
        </div>
      </div>
      <div class="ency-card-title"><?php echo esc_html($display_title); ?></div>
      <div class="ency-card-def"><?php echo esc_html($short_def); ?></div>
      <div class="ency-card-link">
        <?php echo $T['read_more']; ?>
        <svg viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7" stroke-width="1.5" stroke-linecap="round"/></svg>
      </div>
    </a>
    <?php endforeach; ?>

    <!-- Empty state -->
    <div class="ency-empty" id="ency-empty">
      <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35" stroke-width="2" stroke-linecap="round"/></svg>
      <div class="ency-empty-text"><?php echo $T['no_results']; ?></div>
    </div>
  </div>
</div>

<!-- CTA -->
<div class="ency-cta">
  <div class="ency-cta-inner">
    <h3><?php echo $T['cta_title']; ?></h3>
    <p><?php echo $T['cta_desc']; ?></p>
    <div class="ency-cta-btns">
      <a href="<?php echo esc_html($register_label_url);?>" class="ip-btn-red"><?php echo $T['cta_btn1']; ?></a>
      <a href="<?php echo esc_html($register_label_url);?>" class="ip-btn-ghost"><?php echo $T['cta_btn2']; ?></a>
    </div>
  </div>
</div>

<script>
(function(){
  var cards = Array.from(document.querySelectorAll('.ency-card'));
  var countEl = document.getElementById('ency-count');
  var emptyEl = document.getElementById('ency-empty');
  var activeCat = 'all', activeDiff = 'all', activeLetter = 'all', searchVal = '';

  function update(){
    var q = searchVal.toLowerCase().trim();
    var vis = 0;
    cards.forEach(function(c){
      var matchCat    = activeCat === 'all' || c.dataset.cat === activeCat;
      var matchDiff   = activeDiff === 'all' || c.dataset.diff === activeDiff;
      var matchLetter = activeLetter === 'all' || c.dataset.letter === activeLetter;
      var matchSearch = !q || (c.dataset.search || '').indexOf(q) !== -1;
      var show = matchCat && matchDiff && matchLetter && matchSearch;
      c.style.display = show ? '' : 'none';
      if(show) vis++;
    });
    countEl.textContent = vis + ' <?php echo $T['results']; ?>';
    emptyEl.classList.toggle('visible', vis === 0);
  }

  // Search
  document.getElementById('ency-search').addEventListener('input', function(){
    searchVal = this.value; update();
  });

  // Category pills
  document.querySelectorAll('#ency-cats .ency-pill').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.querySelectorAll('#ency-cats .ency-pill').forEach(function(b){ b.classList.remove('active'); });
      this.classList.add('active');
      activeCat = this.dataset.cat;
      update();
    });
  });

  // Difficulty pills
  document.querySelectorAll('#ency-diffs .ency-pill').forEach(function(btn){
    btn.addEventListener('click', function(){
      document.querySelectorAll('#ency-diffs .ency-pill').forEach(function(b){ b.classList.remove('active'); });
      this.classList.add('active');
      activeDiff = this.dataset.diff;
      update();
    });
  });

  // Alphabet
  document.querySelectorAll('.ency-alpha-btn').forEach(function(btn){
    btn.addEventListener('click', function(){
      if(this.disabled) return;
      document.querySelectorAll('.ency-alpha-btn').forEach(function(b){ b.classList.remove('active'); });
      this.classList.add('active');
      activeLetter = this.dataset.letter;
      update();
    });
  });
})();
</script>

<?php get_footer(); ?>
