<?php $lang = stb_lang(); ?>
<section class="mkt-wrap" id="markets" aria-labelledby="mkt-heading">
<style>
/* ═══════════════════════════════════════════
   MARKETS — Live spread table + asset class bar
   Futuristic, animated, no static cards
═══════════════════════════════════════════ */
.mkt-wrap{background:#060809;padding:96px 0;position:relative;overflow:hidden}
.mkt-wrap::before{
  content:'';position:absolute;inset:0;
  background-image:radial-gradient(rgba(200,16,46,.04) 1px,transparent 1px);
  background-size:32px 32px;
  mask-image:radial-gradient(ellipse 80% 80% at 50% 0%,black 40%,transparent 100%);
  pointer-events:none;
}
.mkt-inner{max-width:1280px;margin:0 auto;padding:0 40px;position:relative;z-index:1}
@media(max-width:768px){.mkt-inner{padding:0 20px}}

/* ── Header ── */
.mkt-header{
  display:grid;grid-template-columns:1fr auto;
  gap:32px;align-items:end;margin-bottom:48px;
}
@media(max-width:640px){.mkt-header{grid-template-columns:1fr;gap:16px}}
.mkt-kicker{font-size:10.5px;font-weight:700;letter-spacing:.16em;text-transform:uppercase;color:rgba(200,16,46,.8);margin-bottom:12px}
.mkt-title{font-size:clamp(28px,3.5vw,42px);font-weight:700;color:#fff;line-height:1.15}
.mkt-desc{font-size:14px;color:rgba(255,255,255,.45);margin-top:10px;line-height:1.6}
.mkt-live-badge{
  display:flex;align-items:center;gap:7px;
  padding:8px 16px;border-radius:8px;
  background:rgba(20,224,163,.06);border:1px solid rgba(20,224,163,.18);
  font-size:12px;font-weight:700;color:#14e0a3;white-space:nowrap;
}
.mkt-live-dot{width:7px;height:7px;border-radius:50%;background:#14e0a3;animation:mkt-pulse 2s infinite}
@keyframes mkt-pulse{0%,100%{box-shadow:0 0 0 0 rgba(20,224,163,.4)}50%{box-shadow:0 0 0 6px rgba(20,224,163,0)}}

/* ── Asset class filter tabs ── */
.mkt-filters{
  display:flex;gap:6px;flex-wrap:wrap;margin-bottom:20px;
}
.mkt-filter{
  padding:7px 16px;border-radius:20px;
  font-size:12px;font-weight:600;letter-spacing:.04em;
  color:rgba(255,255,255,.4);
  background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);
  cursor:pointer;transition:all .18s;
}
.mkt-filter:hover{color:rgba(255,255,255,.75);border-color:rgba(255,255,255,.18)}
.mkt-filter.active{
  background:rgba(200,16,46,.12);border-color:rgba(200,16,46,.35);
  color:#fff;
}

/* ── Main grid: table left, asset bar right ── */
.mkt-body{
  display:grid;grid-template-columns:1fr 300px;
  gap:16px;align-items:start;
}
@media(max-width:1024px){.mkt-body{grid-template-columns:1fr}}

/* ── Live spread table ── */
.mkt-table{
  background:#0a0c10;border:1px solid rgba(255,255,255,.07);
  border-radius:16px;overflow:hidden;
}
.mkt-table-head {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 80px;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.03);
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Ccircle cx='1' cy='1' r='0.5' fill='rgba(255, 255, 255, 0.04)'/%3E%3C/svg%3E");
  background-size: 8px 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  gap: 8px;
}
@media(max-width:600px){
  .mkt-table-head{grid-template-columns:2fr 1fr 1fr;padding:10px 14px}
  .mkt-th-spread,.mkt-th-vol{display:none}
}
.mkt-th{font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:rgba(255,255,255,.25)}
.mkt-th:not(:first-child){text-align:right}

/* Table rows */
.mkt-row{
  display:grid;
  grid-template-columns:2fr 1fr 1fr 1fr 80px;
  padding:14px 20px;gap:8px;
  border-bottom:1px solid rgba(255,255,255,.04);
  align-items:center;
  transition:background .12s;
  cursor:default;
}
.mkt-row:last-child{border-bottom:none}
.mkt-row:hover{background:rgba(255,255,255,.025)}
@media(max-width:600px){
  .mkt-row{grid-template-columns:2fr 1fr 1fr;padding:12px 14px}
  .mkt-cell-spread,.mkt-cell-vol{display:none}
}

/* Row instrument info */
.mkt-row-pair{display:flex;align-items:center;gap:10px}
.mkt-row-dot{
  width:6px;height:6px;border-radius:50%;flex-shrink:0;
  box-shadow:0 0 6px currentColor;
}
.mkt-row-name{font-size:13.5px;font-weight:600;color:#fff}
.mkt-row-type{font-size:10.5px;color:rgba(255,255,255,.3);text-transform:uppercase;letter-spacing:.05em;margin-top:1px}

/* Price cell */
.mkt-cell-price{
  font-size:14px;font-weight:700;color:#fff;
  text-align:right;font-variant-numeric:tabular-nums;
  transition:color .3s;
}
.mkt-cell-price.flash-up{color:#14e0a3}
.mkt-cell-price.flash-dn{color:#ff5a72}

/* Change cell */
.mkt-cell-change{
  font-size:12.5px;font-weight:600;text-align:right;
  font-variant-numeric:tabular-nums;
}
.mkt-cell-change.up{color:#14e0a3}
.mkt-cell-change.dn{color:#ff5a72}

/* Spread pill */
.mkt-cell-spread{text-align:right}
.mkt-spread-pill{
  display:inline-block;
  font-size:11px;font-weight:700;
  padding:3px 9px;border-radius:4px;
  background:rgba(255,255,255,.05);
  color:rgba(255,255,255,.45);
  font-variant-numeric:tabular-nums;
}

/* Mini sparkline */
.mkt-cell-vol{display:flex;justify-content:flex-end;align-items:center}
.mkt-spark{width:60px;height:24px}

/* ── Right panel: asset class breakdown ── */
.mkt-classes{
  display:flex;flex-direction:column;gap:10px;
}
.mkt-class-card {
  background: #0a0c10;
  border: 1px solid rgba(255, 255, 255, 0.07);
  border-radius: 12px; padding: 16px 18px;
  display: flex; align-items: center; gap: 14px;
  cursor: pointer; transition: border-color .2s, background .2s, transform .2s;
  position: relative; overflow: hidden;
}
.mkt-class-card::before {
  content: ''; position: absolute; left: 0; top: 0; bottom: 0;
  width: 3px; background: var(--cc);
  opacity: 0; transition: opacity .2s;
  border-radius: 3px 0 0 3px;
  z-index: 2;
}
.mkt-class-card::after {
  content: ''; position: absolute; inset: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24'%3E%3Ccircle cx='2' cy='2' r='0.75' fill='rgba(255, 255, 255, 0.03)'/%3E%3C/svg%3E");
  background-size: 24px 24px;
  opacity: 0; transition: opacity .3s;
  pointer-events: none;
  z-index: 1;
}
.mkt-class-card:hover, .mkt-class-card.active {
  border-color: rgba(255, 255, 255, 0.12); background: #0f1116;
  transform: translateX(4px);
}
.mkt-class-card:hover::before, .mkt-class-card.active::before,
.mkt-class-card:hover::after, .mkt-class-card.active::after {
  opacity: 1;
}
body.rtl .mkt-class-card:hover, body.rtl .mkt-class-card.active {
  transform: translateX(-4px);
}
body.rtl .mkt-class-card::before { left: auto; right: 0; border-radius: 0 3px 3px 0; }
.mkt-class-icon { z-index: 2; position: relative; }
.mkt-class-info { flex: 1; min-width: 0; z-index: 2; position: relative; }
.mkt-class-icon{
  width:36px;height:36px;border-radius:9px;flex-shrink:0;
  display:flex;align-items:center;justify-content:center;
  background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);
}
.mkt-class-icon svg{stroke:var(--cc);fill:none;width:17px;height:17px}
.mkt-class-info{flex:1;min-width:0}
.mkt-class-name{font-size:13px;font-weight:600;color:#fff;margin-bottom:2px}
.mkt-class-count{font-size:11px;color:rgba(255,255,255,.35)}
/* Animated fill bar */
.mkt-class-bar-wrap{
  width:100%;height:2px;background:rgba(255,255,255,.06);
  border-radius:1px;margin-top:8px;overflow:hidden;
}
.mkt-class-bar-fill{
  height:100%;border-radius:1px;background:var(--cc);
  width:0;transition:width 1.2s cubic-bezier(.16,1,.3,1);
  box-shadow:0 0 6px var(--cc);
}

/* ── Bottom: global coverage strip ── */
.mkt-coverage{
  margin-top:20px;
  background:#0a0c10;border:1px solid rgba(255,255,255,.07);
  border-radius:12px;padding:20px 24px;
  display:flex;align-items:center;justify-content:space-between;
  gap:16px;flex-wrap:wrap;
}
.mkt-coverage-text{font-size:13.5px;color:rgba(255,255,255,.45)}
.mkt-coverage-text strong{color:#fff}
.mkt-coverage-flags{display:flex;gap:6px;flex-wrap:wrap}
.mkt-flag{
  width:28px;height:20px;border-radius:3px;
  background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.1);
  display:flex;align-items:center;justify-content:center;
  font-size:13px;line-height:1;
}
</style>

<div class="mkt-inner">

  <!-- Header -->
  <div class="mkt-header">
    <div>
      <div class="mkt-kicker"><?php echo $lang==='fa' ? 'بازارها' : 'MARKETS'; ?></div>
      <h2 class="mkt-title" id="mkt-heading">
        <?php echo $lang==='fa' ? 'بازارهای جهانی، یک پلتفرم' : 'Global Markets, One Platform'; ?>
      </h2>
      <p class="mkt-desc">
        <?php echo $lang==='fa' ? '۱۸۰+ ابزار CFD و اسپات در شش کلاس دارایی — نقدینگی نهادی روی MetaTrader 5.' : '180+ CFD instruments and spot assets across six asset classes — institutional liquidity on MetaTrader 5.'; ?>
      </p>
    </div>
    <div class="mkt-live-badge">
      <span class="mkt-live-dot"></span>
      <?php echo $lang==='fa' ? 'قیمت زنده' : 'Live Pricing'; ?>
    </div>
  </div>

  <!-- Asset class filter tabs -->
  <div class="mkt-filters" role="group" aria-label="Filter by asset class">
    <?php $filters = $lang==='fa'
      ? ['all'=>'همه','FOREX'=>'فارکس','INDEX'=>'شاخص','COMMODITY'=>'کالا','CRYPTO'=>'رمزارز']
      : ['all'=>'All','FOREX'=>'Forex','INDEX'=>'Indices','COMMODITY'=>'Commodities','CRYPTO'=>'Crypto'];
    foreach($filters as $key=>$label): ?>
    <button class="mkt-filter<?php echo $key==='all'?' active':''; ?>"
            data-filter="<?php echo $key; ?>"
            onclick="mktFilter('<?php echo $key; ?>',this)">
      <?php echo esc_html($label); ?>
    </button>
    <?php endforeach; ?>
  </div>

  <div class="mkt-body">

    <!-- Live spread table -->
    <div class="mkt-table" role="table" aria-label="Live market prices">
      <div class="mkt-table-head" role="row">
        <span class="mkt-th"><?php echo $lang==='fa' ? 'ابزار' : 'Instrument'; ?></span>
        <span class="mkt-th"><?php echo $lang==='fa' ? 'قیمت' : 'Price'; ?></span>
        <span class="mkt-th"><?php echo $lang==='fa' ? 'تغییر' : 'Change'; ?></span>
        <span class="mkt-th mkt-th-spread"><?php echo $lang==='fa' ? 'اسپرد' : 'Spread'; ?></span>
        <span class="mkt-th mkt-th-vol"><?php echo $lang==='fa' ? 'نمودار' : 'Chart'; ?></span>
      </div>
      <div id="mkt-rows">
        <?php
        // Static rows — JS will update prices from live feed
        $rows = [
          ['FX:EURUSD',         'EUR / USD',  'FOREX',     '#14e0a3', '0.1'],
          ['FX:GBPUSD',         'GBP / USD',  'FOREX',     '#14e0a3', '0.2'],
          ['FX:USDJPY',         'USD / JPY',  'FOREX',     '#14e0a3', '0.3'],
          ['FX:AUDUSD',         'AUD / USD',  'FOREX',     '#14e0a3', '0.4'],
          ['CAPITALCOM:US100',  'NAS 100',    'INDEX',     '#C8102E', '0.5'],
          ['CAPITALCOM:US30',   'US 30',      'INDEX',     '#C8102E', '1.0'],
          ['CAPITALCOM:DE40',   'DAX 40',     'INDEX',     '#C8102E', '1.2'],
          ['CAPITALCOM:XAUUSD', 'XAU / USD',  'COMMODITY', '#14e0a3', '0.3'],
          ['CAPITALCOM:XAGUSD', 'XAG / USD',  'COMMODITY', '#14e0a3', '0.5'],
          ['CAPITALCOM:USOIL',  'WTI Oil',    'COMMODITY', '#C8102E', '0.4'],
          ['BINANCE:BTCUSDT',   'BTC / USD',  'CRYPTO',   '#C8102E', '1.5'],
          ['BINANCE:ETHUSDT',   'ETH / USD',  'CRYPTO',   '#627eea', '1.2'],
        ];
        foreach($rows as $r): ?>
        <div class="mkt-row" role="row" data-symbol="<?php echo $r[0]; ?>" data-type="<?php echo $r[2]; ?>">
          <div class="mkt-row-pair">
            <span class="mkt-row-dot" style="color:<?php echo $r[3]; ?>;background:<?php echo $r[3]; ?>"></span>
            <div>
              <div class="mkt-row-name"><?php echo $r[1]; ?></div>
              <div class="mkt-row-type"><?php echo $r[2]; ?></div>
            </div>
          </div>
          <div class="mkt-cell-price" data-price>—</div>
          <div class="mkt-cell-change" data-change>—</div>
          <div class="mkt-cell-spread">
            <span class="mkt-spread-pill"><?php echo $r[4]; ?> pip</span>
          </div>
          <div class="mkt-cell-vol">
            <canvas class="mkt-spark" data-spark></canvas>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Right: asset class breakdown with animated bars -->
    <div class="mkt-classes" id="mkt-classes">
      <?php
      $classes = $lang==='fa' ? [
        ['#14e0a3', '<circle cx="12" cy="12" r="10" stroke-width="1.5"/><path d="M2 12h20M12 2a15.3 15.3 0 010 20M12 2a15.3 15.3 0 000 20" stroke-width="1.5"/>',
         'فارکس',    '60+ جفت‌ارز',   72],
        ['#C8102E', '<polyline points="22 12 18 12 15 21 9 3 6 12 2 12" stroke-width="1.8" stroke-linecap="round"/>',
         'شاخص‌ها',  '10+ شاخص',      55],
        ['#14e0a3', '<circle cx="12" cy="12" r="5" stroke-width="1.5"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4" stroke-width="1.5"/>',
         'کالاها',   '10+ ابزار',      40],
        ['#C8102E', '<path d="M9 8h6c1.1 0 2 .9 2 2s-.9 2-2 2H9V8zm0 8h7c1.1 0 2-.9 2-2s-.9-2-2-2H9v4z" stroke-width="1.5"/><path d="M6 4v16M15 4v2M15 18v2" stroke-width="1.5" stroke-linecap="round"/>',
         'رمزارز',   '50+ CFD',        60],
        ['#C8102E', '<rect x="2" y="3" width="20" height="14" rx="2" stroke-width="1.5"/><path d="M8 21h8M12 17v4" stroke-width="1.5" stroke-linecap="round"/>',
         'سهام',     '۲۰۰+ سهام',     100],
        ['#C8102E', '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke-width="1.5"/>',
         'اسپات',    '5+ دارایی',     25],
      ] : [
        ['#14e0a3', '<circle cx="12" cy="12" r="10" stroke-width="1.5"/><path d="M2 12h20M12 2a15.3 15.3 0 010 20M12 2a15.3 15.3 0 000 20" stroke-width="1.5"/>',
         'Forex',       '60+ Pairs',     72],
        ['#C8102E', '<polyline points="22 12 18 12 15 21 9 3 6 12 2 12" stroke-width="1.8" stroke-linecap="round"/>',
         'Indices',     '10+ Indices',   55],
        ['#14e0a3', '<circle cx="12" cy="12" r="5" stroke-width="1.5"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4" stroke-width="1.5"/>',
         'Commodities', '10+ Instruments',40],
        ['#C8102E', '<path d="M9 8h6c1.1 0 2 .9 2 2s-.9 2-2 2H9V8zm0 8h7c1.1 0 2-.9 2-2s-.9-2-2-2H9v4z" stroke-width="1.5"/><path d="M6 4v16M15 4v2M15 18v2" stroke-width="1.5" stroke-linecap="round"/>',
         'Crypto',      '50+ CFDs',      60],
        ['#C8102E', '<rect x="2" y="3" width="20" height="14" rx="2" stroke-width="1.5"/><path d="M8 21h8M12 17v4" stroke-width="1.5" stroke-linecap="round"/>',
         'Equities',    '200+ Stocks',  100],
        ['#C8102E', '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke-width="1.5"/>',
         'Spot',        '5+ Assets',    25],
      ];
      foreach($classes as $i=>$c): ?>
      <div class="mkt-class-card<?php echo $i===0?' active':''; ?>"
           style="--cc:<?php echo $c[0]; ?>"
           data-class="<?php echo strtolower(explode(' ',$c[2])[0]); ?>"
           onclick="mktClassClick(this)">
        <div class="mkt-class-icon">
          <svg viewBox="0 0 24 24" stroke="currentColor" fill="none"><?php echo $c[1]; ?></svg>
        </div>
        <div class="mkt-class-info">
          <div class="mkt-class-name"><?php echo esc_html($c[2]); ?></div>
          <div class="mkt-class-count"><?php echo esc_html($c[3]); ?></div>
          <div class="mkt-class-bar-wrap">
            <div class="mkt-class-bar-fill" data-pct="<?php echo $c[4]; ?>"></div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

  </div>

  <!-- Coverage strip -->
  <div class="mkt-coverage">
    <div class="mkt-coverage-text">
      <strong><?php echo $lang==='fa' ? 'پوشش بازارهای جهانی' : 'Global Market Coverage'; ?></strong>
      <?php echo $lang==='fa' ? 'دسترسی به بازارهای آمریکا، اروپا، آسیا و خاورمیانه — از یک حساب' : 'Access US, European, Asian and Middle Eastern markets — from one account'; ?>
    </div>
    <div class="mkt-coverage-flags">
      <?php foreach(['🇺🇸','🇬🇧','🇩🇪','🇯🇵','🇦🇺','🇨🇭','🇪🇺','🇨🇦'] as $f): ?>
      <div class="mkt-flag"><?php echo $f; ?></div>
      <?php endforeach; ?>
    </div>
  </div>

</div>

<script>
(function(){

  /* ── Sparkline drawer ── */
  function drawSpark(canvas, up) {
    var W = canvas.width  = canvas.offsetWidth || 60;
    var H = canvas.height = canvas.offsetHeight || 24;
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0,0,W,H);
    var pts = 8;
    var points = [];
    var v = H/2;
    for(var i=0;i<pts;i++){
      v += (Math.random()-.5)*(H*.4);
      v = Math.max(4,Math.min(H-4,v));
      points.push({x:i*(W/(pts-1)), y:v});
    }
    // Trend bias
    if(up)  points[pts-1].y = Math.min(points[pts-1].y, H*.35);
    else    points[pts-1].y = Math.max(points[pts-1].y, H*.65);

    var grad = ctx.createLinearGradient(0,0,W,0);
    grad.addColorStop(0, up?'rgba(20,224,163,0)':'rgba(255,90,114,0)');
    grad.addColorStop(1, up?'rgba(20,224,163,.8)':'rgba(255,90,114,.8)');
    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);
    for(var j=1;j<pts;j++) ctx.lineTo(points[j].x, points[j].y);
    ctx.strokeStyle = grad;
    ctx.lineWidth = 1.5;
    ctx.stroke();
  }

  /* ── Populate prices from live feed ── */
  var apiUrl = (window.stbPricesConfig && window.stbPricesConfig.apiUrl) || '/NewSite/wp-json/stb/v1/prices';
  var prevPrices = {};

  function updateTable(prices) {
    var rows = document.querySelectorAll('#mkt-rows .mkt-row[data-symbol]');
    rows.forEach(function(row){
      var sym   = row.getAttribute('data-symbol');
      var p     = prices.find(function(px){ return px.symbol === sym; });
      if(!p) return;

      var priceEl  = row.querySelector('[data-price]');
      var changeEl = row.querySelector('[data-change]');
      var sparkEl  = row.querySelector('[data-spark]');

      if(priceEl){
        var prev = prevPrices[sym];
        if(prev && prev !== p.price_fmt){
          priceEl.classList.remove('flash-up','flash-dn');
          void priceEl.offsetWidth;
          priceEl.classList.add(p.direction==='up'?'flash-up':'flash-dn');
          setTimeout(function(){ priceEl.classList.remove('flash-up','flash-dn'); }, 800);
        }
        priceEl.textContent = p.price_fmt;
        prevPrices[sym] = p.price_fmt;
      }

      if(changeEl){
        var arrow = p.direction==='up' ? '▲ ' : '▼ ';
        changeEl.textContent = arrow + p.change_str;
        changeEl.className = 'mkt-cell-change ' + (p.direction==='up'?'up':'dn');
      }

      if(sparkEl) drawSpark(sparkEl, p.direction==='up');
    });
  }

  function loadPrices(){
    fetch(apiUrl)
      .then(function(r){return r.json();})
      .then(function(d){ if(d.ok && d.prices) updateTable(d.prices); })
      .catch(function(){});
  }

  /* ── Filter rows by asset class ── */
  window.mktFilter = function(type, btn) {
    document.querySelectorAll('.mkt-filter').forEach(function(b){
      b.classList.remove('active');
    });
    btn.classList.add('active');
    document.querySelectorAll('#mkt-rows .mkt-row').forEach(function(row){
      var show = type==='all' || row.getAttribute('data-type')===type;
      row.style.display = show ? '' : 'none';
    });
  };

  /* ── Asset class card click — filter table ── */
  window.mktClassClick = function(card) {
    document.querySelectorAll('.mkt-class-card').forEach(function(c){c.classList.remove('active');});
    card.classList.add('active');
  };

  /* ── Animate bar fills on load ── */
  function animateBars(){
    var max = 0;
    document.querySelectorAll('.mkt-class-bar-fill').forEach(function(b){
      max = Math.max(max, parseInt(b.getAttribute('data-pct')||0));
    });
    document.querySelectorAll('.mkt-class-bar-fill').forEach(function(b){
      var pct = parseInt(b.getAttribute('data-pct')||0);
      setTimeout(function(){
        b.style.width = (pct/max*100) + '%';
      }, 300);
    });
  }

  /* ── Init ── */
  document.addEventListener('DOMContentLoaded', function(){
    loadPrices();
    setInterval(loadPrices, 30000);
    animateBars();
  });

})();
</script>
</section>
