<?php $lang = stb_lang(); $B=''; $fa=$lang==='fa'; ?>
<article class="ip-page">

<!-- ═══ HERO ═══ -->
<div class="ip-hero">
  <div class="ip-hero-glow"></div>
  <div class="ip-container">
    <nav class="ip-breadcrumb">
      <a href="<?php echo stb_url($B.'/'); ?>"><?php echo $fa?'خانه':'Home';?></a>
      <span class="ip-breadcrumb-sep">›</span>
      <span><?php echo $fa?'ابزارهای معاملاتی':'Trading Tools';?></span>
    </nav>
    <div class="ip-kicker"><span class="ip-kicker-dot"></span><?php echo $fa?'STB بروکر · ابزارها':'STB BROKER · TOOLS';?></div>
    <h1 class="ip-h1"><?php echo $fa?'ابزارهای <em>حرفه‌ای</em>':'Professional <em>Trading Tools</em>';?></h1>
    <p class="ip-hero-desc"><?php echo $fa?'پنج ابزار تعاملی زنده — ماشین‌حساب پیپ، مارجین، تبدیل ارز، تقویم اقتصادی و سنتیمنت بازار — مستقیم در مرورگر شما.':'Five live interactive calculators — pip, margin, currency converter, economic calendar and market sentiment — running directly in your browser.';?></p>
    <div class="ip-hero-stats">
      <div><div class="ip-stat-val">5</div><div class="ip-stat-lbl"><?php echo $fa?'ابزار زنده':'Live Widgets';?></div></div>
      <div><div class="ip-stat-val">60+</div><div class="ip-stat-lbl"><?php echo $fa?'ارز':'Currencies';?></div></div>
      <div><div class="ip-stat-val">350+</div><div class="ip-stat-lbl"><?php echo $fa?'نماد':'Instruments';?></div></div>
      <div><div class="ip-stat-val">$0</div><div class="ip-stat-lbl"><?php echo $fa?'هزینه':'Cost';?></div></div>
    </div>
    <div class="ip-hero-ctas">
      <a href="https://crm.stbbrokers.com/register" class="ip-btn-red">
        <?php echo $fa?'باز کردن حساب':'Open Account';?> <svg viewBox="0 0 24 24"><path d="M5 12h14M12 5l7 7-7 7" stroke-width="2" stroke-linecap="round"/></svg>
      </a>
      <a href="<?php echo stb_url($B.'/contact/');?>" class="ip-btn-ghost"><?php echo $fa?'تماس با ما':'Contact Us';?></a>
    </div>
  </div>
</div>

<style>
/* ── Tools page shared ── */
.tools-section{padding:72px 0}
.tools-section-alt{background:rgba(4,6,10,1);border-top:1px solid rgba(255,255,255,.04);border-bottom:1px solid rgba(255,255,255,.04)}
.tools-widget-wrap{background:#0a0c10;border:1px solid rgba(255,255,255,.07);border-radius:20px;padding:36px;position:relative;overflow:hidden;margin-bottom:48px}
.tools-widget-wrap::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,#C8102E,transparent)}
.tools-widget-title{font-size:22px;font-weight:700;color:#fff;margin-bottom:6px;display:flex;align-items:center;gap:12px}
.tools-widget-title svg{stroke:#C8102E;fill:none;flex-shrink:0}
.tools-widget-sub{font-size:13.5px;color:rgba(255,255,255,.4);margin-bottom:28px}
.tw-row{display:grid;gap:14px;margin-bottom:20px}
.tw-row-2{grid-template-columns:1fr 1fr}
.tw-row-3{grid-template-columns:1fr 1fr 1fr}
.tw-row-4{grid-template-columns:1fr 1fr 1fr 1fr}
@media(max-width:680px){.tw-row-2,.tw-row-3,.tw-row-4{grid-template-columns:1fr 1fr}}
@media(max-width:420px){.tw-row-2,.tw-row-3,.tw-row-4{grid-template-columns:1fr}}
.tw-field{display:flex;flex-direction:column;gap:6px}
.tw-label{font-size:11px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.35)}
.tw-input,.tw-select{
  background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);
  border-radius:10px;padding:11px 14px;font-size:14px;color:#fff;
  width:100%;outline:none;transition:border-color .2s;
  font-family:inherit;
}
.tw-input:focus,.tw-select:focus{border-color:rgba(200,16,46,.5)}
.tw-select option{background:#0d1017;color:#fff}
.tw-result-box{
  background:linear-gradient(135deg,rgba(200,16,46,.08),rgba(200,16,46,.03));
  border:1px solid rgba(200,16,46,.2);border-radius:12px;
  padding:20px 24px;display:flex;align-items:center;justify-content:space-between;
  flex-wrap:wrap;gap:12px;
}
.tw-result-label{font-size:12px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.4)}
.tw-result-value{font-size:clamp(24px,3vw,36px);font-weight:700;color:#fff;font-family:'Bebas Neue',sans-serif;letter-spacing:.03em}
.tw-result-value span{font-size:.55em;color:#C8102E;margin-left:6px}
.tw-btn{
  background:#C8102E;color:#fff;border:none;border-radius:10px;
  padding:12px 28px;font-size:13px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;
  cursor:pointer;transition:background .15s,transform .1s;
}
.tw-btn:hover{background:#e01535;transform:translateY(-1px)}
.tw-btn:active{transform:translateY(0)}
.tw-note{font-size:11.5px;color:rgba(255,255,255,.25);margin-top:14px;line-height:1.6}
/* badge pulse on result update */
@keyframes tw-flash{0%{box-shadow:0 0 0 0 rgba(200,16,46,.5)}100%{box-shadow:0 0 0 12px rgba(200,16,46,0)}}
.tw-flash{animation:tw-flash .4s ease-out}

/* ── Widget 3: Sentiment bars ── */
.sent-grid{display:grid;gap:12px}
.sent-row{display:grid;grid-template-columns:80px 1fr 64px 64px;align-items:center;gap:12px}
@media(max-width:520px){.sent-row{grid-template-columns:60px 1fr 50px 50px;gap:8px}}
.sent-sym{font-size:12px;font-weight:700;color:#fff}
.sent-bar-wrap{height:8px;background:rgba(255,255,255,.06);border-radius:4px;overflow:hidden;position:relative}
.sent-bar-bull{position:absolute;left:0;top:0;height:100%;background:linear-gradient(90deg,#14e0a3,#0fb88a);border-radius:4px;transition:width 1.2s cubic-bezier(.16,1,.3,1)}
.sent-bar-bear{position:absolute;right:0;top:0;height:100%;background:linear-gradient(90deg,#e03b14,#C8102E);border-radius:4px;transition:width 1.2s cubic-bezier(.16,1,.3,1)}
.sent-pct-bull{font-size:12px;font-weight:700;color:#14e0a3;text-align:right}
.sent-pct-bear{font-size:12px;font-weight:700;color:#C8102E;text-align:right}
.sent-hdr{font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.25)}
.sent-hdr-row{display:grid;grid-template-columns:80px 1fr 64px 64px;gap:12px;margin-bottom:8px}
@media(max-width:520px){.sent-hdr-row{grid-template-columns:60px 1fr 50px 50px;gap:8px}}
.sent-refresh-btn{
  background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.1);
  border-radius:8px;padding:7px 16px;font-size:12px;font-weight:600;color:rgba(255,255,255,.5);
  cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:6px;
}
.sent-refresh-btn:hover{background:rgba(200,16,46,.08);border-color:rgba(200,16,46,.25);color:#fff}
.sent-refresh-btn svg{transition:transform .6s}
.sent-refresh-btn.spinning svg{transform:rotate(360deg)}
.sent-ts{font-size:11px;color:rgba(255,255,255,.2);margin-top:10px}

/* ── Widget 4: Economic Calendar ── */
.ecal-filters{display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap}
.ecal-filter-btn{
  padding:6px 14px;border-radius:7px;font-size:12px;font-weight:700;letter-spacing:.05em;
  cursor:pointer;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.04);
  color:rgba(255,255,255,.45);transition:all .15s;
}
.ecal-filter-btn.active{background:rgba(200,16,46,.12);border-color:rgba(200,16,46,.35);color:#fff}
.ecal-filter-btn:hover{color:rgba(255,255,255,.8)}
.ecal-table{width:100%;border-collapse:collapse}
.ecal-table th{font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.25);padding:8px 12px;border-bottom:1px solid rgba(255,255,255,.05);text-align:left}
.ecal-table td{padding:12px 12px;border-bottom:1px solid rgba(255,255,255,.04);font-size:13px;color:rgba(255,255,255,.7);vertical-align:middle}
.ecal-table tr:last-child td{border-bottom:none}
.ecal-impact{display:inline-flex;gap:3px;align-items:center}
.ecal-dot{width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,.15)}
.ecal-dot.active{background:#C8102E}
.ecal-dot.active-med{background:#e07814}
.ecal-dot.active-low{background:#14e0a3}
.ecal-flag{font-size:18px;margin-right:6px}
.ecal-prev{color:rgba(255,255,255,.3);font-size:12px}
.ecal-forecast{color:#14e0a3;font-size:12px;font-weight:600}
.ecal-actual{color:#fff;font-weight:700;font-size:13px}
.ecal-actual.up{color:#14e0a3}
.ecal-actual.down{color:#C8102E}
.ecal-time{font-family:'IBM Plex Mono','Courier New',monospace;font-size:12px;color:rgba(255,255,255,.35)}
.ecal-event{font-weight:600;color:#fff}
.ecal-empty{padding:32px;text-align:center;color:rgba(255,255,255,.2);font-size:14px}

/* ── Widget 5: Currency Converter ── */
.cc-main{display:grid;grid-template-columns:1fr auto 1fr;align-items:end;gap:12px;margin-bottom:20px}
@media(max-width:520px){.cc-main{grid-template-columns:1fr;gap:8px}}
.cc-swap-btn{
  width:42px;height:42px;border-radius:50%;border:1px solid rgba(255,255,255,.12);
  background:rgba(255,255,255,.04);cursor:pointer;display:flex;align-items:center;justify-content:center;
  transition:all .2s;color:rgba(255,255,255,.5);align-self:flex-end;margin-bottom:0;flex-shrink:0;
}
.cc-swap-btn:hover{background:rgba(200,16,46,.1);border-color:rgba(200,16,46,.3);color:#fff;transform:rotate(180deg)}
.cc-rate-display{
  background:rgba(255,255,255,.02);border:1px solid rgba(255,255,255,.06);
  border-radius:12px;padding:16px 20px;display:flex;justify-content:space-between;align-items:center;
  flex-wrap:wrap;gap:8px;margin-top:4px;
}
.cc-rate-val{font-size:clamp(18px,2.5vw,28px);font-weight:700;color:#fff;font-family:'Bebas Neue',sans-serif;letter-spacing:.03em}
.cc-rate-meta{font-size:11px;color:rgba(255,255,255,.25);margin-top:2px}
.cc-rate-change{font-size:12px;font-weight:700;padding:4px 10px;border-radius:6px}
.cc-rate-change.up{background:rgba(20,224,163,.1);color:#14e0a3}
.cc-rate-change.down{background:rgba(200,16,46,.1);color:#C8102E}
.cc-sparkline{width:100%;height:50px;margin-top:16px}

/* RTL overrides */
[dir=rtl] .tw-result-value span{margin-left:0;margin-right:6px}
[dir=rtl] .sent-bar-bull{left:auto;right:0;background:linear-gradient(270deg,#14e0a3,#0fb88a)}
[dir=rtl] .sent-bar-bear{right:auto;left:0;background:linear-gradient(270deg,#e03b14,#C8102E)}
[dir=rtl] .ecal-flag{margin-right:0;margin-left:6px}
[dir=rtl] .ecal-table th{text-align:right}
[dir=rtl] .ecal-table td{text-align:right}
</style>

<!-- ═══ WIDGET SECTION ═══ -->
<section class="ip-section tools-section">
<div class="ip-container">

  <div class="ip-section-header" style="margin-bottom:48px">
    <h2 class="ip-section-title"><?php echo $fa?'ابزارهای تعاملی <em>زنده</em>':'Live <em>Interactive</em> Tools';?></h2>
    <p class="ip-section-desc"><?php echo $fa?'همه ابزارها به صورت زنده در مرورگر اجرا می‌شوند — بدون نیاز به نصب.':'All tools run live in your browser — nothing to install.';?></p>
  </div>

  <!-- ══════════════════════════════════
       WIDGET 1: PIP CALCULATOR
  ══════════════════════════════════ -->
  <div class="tools-widget-wrap ip-animate">
    <div class="tools-widget-title">
      <svg width="22" height="22" viewBox="0 0 24 24" stroke-width="1.8"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" y1="22" x2="4" y2="15"/></svg>
      <?php echo $fa?'ماشین‌حساب Pip':'Pip Calculator';?>
    </div>
    <p class="tools-widget-sub"><?php echo $fa?'ارزش هر پیپ را برای هر نماد و ارز حساب محاسبه کنید.':'Calculate the monetary value of each pip for any instrument and account currency.';?></p>
    <div class="tw-row tw-row-3">
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'نماد':'Symbol';?></label>
        <select class="tw-select" id="pip-symbol" onchange="calcPip()">
          <option value="EURUSD" data-pip="0.0001" data-quote="USD">EUR/USD</option>
          <option value="GBPUSD" data-pip="0.0001" data-quote="USD">GBP/USD</option>
          <option value="USDJPY" data-pip="0.01" data-quote="JPY">USD/JPY</option>
          <option value="AUDUSD" data-pip="0.0001" data-quote="USD">AUD/USD</option>
          <option value="USDCAD" data-pip="0.0001" data-quote="CAD">USD/CAD</option>
          <option value="XAUUSD" data-pip="0.1" data-quote="USD">XAU/USD (Gold)</option>
          <option value="XAGUSD" data-pip="0.01" data-quote="USD">XAG/USD (Silver)</option>
          <option value="USOIL" data-pip="0.01" data-quote="USD">US Oil (WTI)</option>
          <option value="NAS100" data-pip="1" data-quote="USD">NAS100</option>
          <option value="SPX500" data-pip="0.1" data-quote="USD">SPX500</option>
        </select>
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'حجم (لات)':'Lot Size';?></label>
        <input class="tw-input" id="pip-lots" type="number" value="1" min="0.01" step="0.01" oninput="calcPip()">
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'ارز حساب':'Account CCY';?></label>
        <select class="tw-select" id="pip-accy" onchange="calcPip()">
          <option value="USD">USD</option>
          <option value="EUR">EUR</option>
          <option value="GBP">GBP</option>
          <option value="JPY">JPY</option>
          <option value="IRR">IRR (Toman)</option>
        </select>
      </div>
    </div>
    <div class="tw-row tw-row-2">
      <div class="tw-result-box" id="pip-result-box">
        <div>
          <div class="tw-result-label"><?php echo $fa?'ارزش هر پیپ':'Value per Pip';?></div>
          <div class="tw-result-value" id="pip-result">—<span>USD</span></div>
        </div>
        <div style="text-align:right">
          <div class="tw-result-label"><?php echo $fa?'ارزش پیپ برای ۱۰ پیپ':'10-Pip Move';?></div>
          <div class="tw-result-value" id="pip-result-10" style="font-size:22px">—</div>
        </div>
      </div>
      <div class="tw-result-box">
        <div>
          <div class="tw-result-label"><?php echo $fa?'اندازه قرارداد':'Contract Size';?></div>
          <div class="tw-result-value" id="pip-contract">100,000<span>units</span></div>
        </div>
        <div style="text-align:right">
          <div class="tw-result-label"><?php echo $fa?'ارزش نوشنال':'Notional';?></div>
          <div class="tw-result-value" id="pip-notional" style="font-size:22px">—</div>
        </div>
      </div>
    </div>
    <p class="tw-note"><?php echo $fa?'* نرخ‌های تبدیل تقریبی هستند. برای معاملات واقعی از پلتفرم استفاده کنید.':'* Conversion rates are approximate. Use the platform for live trading rates.';?></p>
  </div>

  <!-- ══════════════════════════════════
       WIDGET 2: MARGIN CALCULATOR
  ══════════════════════════════════ -->
  <div class="tools-widget-wrap ip-animate">
    <div class="tools-widget-title">
      <svg width="22" height="22" viewBox="0 0 24 24" stroke-width="1.8"><path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6" stroke-linecap="round"/></svg>
      <?php echo $fa?'ماشین‌حساب Margin':'Margin Calculator';?>
    </div>
    <p class="tools-widget-sub"><?php echo $fa?'مارجین مورد نیاز برای هر معامله را محاسبه کنید.':'Instantly calculate required margin for any position size and leverage.';?></p>
    <div class="tw-row tw-row-4">
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'نماد':'Symbol';?></label>
        <select class="tw-select" id="mg-symbol" onchange="calcMargin()">
          <option value="EURUSD" data-price="1.08500">EUR/USD</option>
          <option value="GBPUSD" data-price="1.27200">GBP/USD</option>
          <option value="USDJPY" data-price="149.500">USD/JPY</option>
          <option value="XAUUSD" data-price="2350.00">XAU/USD</option>
          <option value="XAGUSD" data-price="28.500">XAG/USD</option>
          <option value="NAS100" data-price="18500.0">NAS100</option>
          <option value="SPX500" data-price="5250.00">SPX500</option>
          <option value="USOIL" data-price="82.500">US Oil</option>
        </select>
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'لوریج':'Leverage';?></label>
        <select class="tw-select" id="mg-lev" onchange="calcMargin()">
          <option value="400">1:400</option>
          <option value="200">1:200</option>
          <option value="100">1:100</option>
          <option value="50">1:50</option>
          <option value="30">1:30</option>
          <option value="10">1:10</option>
        </select>
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'حجم (لات)':'Lot Size';?></label>
        <input class="tw-input" id="mg-lots" type="number" value="1" min="0.01" step="0.01" oninput="calcMargin()">
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'ارز حساب':'Account CCY';?></label>
        <select class="tw-select" id="mg-accy" onchange="calcMargin()">
          <option value="USD">USD</option>
          <option value="EUR">EUR</option>
          <option value="GBP">GBP</option>
        </select>
      </div>
    </div>
    <div class="tw-row tw-row-3">
      <div class="tw-result-box" id="mg-result-box">
        <div>
          <div class="tw-result-label"><?php echo $fa?'مارجین مورد نیاز':'Required Margin';?></div>
          <div class="tw-result-value" id="mg-result">—<span>USD</span></div>
        </div>
      </div>
      <div class="tw-result-box">
        <div>
          <div class="tw-result-label"><?php echo $fa?'ارزش معامله':'Trade Value';?></div>
          <div class="tw-result-value" id="mg-value">—<span>USD</span></div>
        </div>
      </div>
      <div class="tw-result-box">
        <div>
          <div class="tw-result-label"><?php echo $fa?'نرخ بازار':'Market Price';?></div>
          <div class="tw-result-value" id="mg-price" style="font-size:24px">—</div>
        </div>
      </div>
    </div>
    <div style="margin-top:16px">
      <label class="tw-label" style="display:block;margin-bottom:8px"><?php echo $fa?'قدرت لوریج':'Leverage Power';?></label>
      <div style="height:8px;background:rgba(255,255,255,.06);border-radius:4px;overflow:hidden">
        <div id="mg-lever-bar" style="height:100%;background:linear-gradient(90deg,#14e0a3,#C8102E);border-radius:4px;transition:width .8s cubic-bezier(.16,1,.3,1);width:0%"></div>
      </div>
      <div style="display:flex;justify-content:space-between;margin-top:4px">
        <span style="font-size:10px;color:rgba(255,255,255,.2)">1:1</span>
        <span style="font-size:10px;color:rgba(255,255,255,.2)" id="mg-lev-label">1:400</span>
      </div>
    </div>
    <p class="tw-note"><?php echo $fa?'* قیمت‌های نمایش‌داده‌شده قیمت‌های تقریبی بازار هستند.':'* Prices shown are indicative market prices.';?></p>
  </div>

  <!-- ══════════════════════════════════
       WIDGET 3: MARKET SENTIMENT
  ══════════════════════════════════ -->
  <div class="tools-widget-wrap ip-animate">
    <div class="tools-widget-title">
      <svg width="22" height="22" viewBox="0 0 24 24" stroke-width="1.8"><path d="M22 12h-4l-3 9L9 3l-3 9H2" stroke-linecap="round" stroke-linejoin="round"/></svg>
      <?php echo $fa?'سنتیمنت بازار':'Market Sentiment';?>
      <button class="sent-refresh-btn" id="sent-refresh-btn" onclick="refreshSentiment()" style="margin-left:auto;font-size:12px">
        <svg width="14" height="14" viewBox="0 0 24 24" stroke="currentColor" fill="none" stroke-width="2.5" id="sent-refresh-icon"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"/></svg>
        <?php echo $fa?'بروزرسانی':'Refresh';?>
      </button>
    </div>
    <p class="tools-widget-sub"><?php echo $fa?'تحلیل تکنیکال زنده ۸ نماد اصلی از ۲۶+ اندیکاتور — به‌روزرسانی هر ۱۵ دقیقه.':'Live technical analysis on 8 major instruments aggregating 26+ indicators — refreshed every 15 minutes.';?></p>
    <div class="sent-hdr-row">
      <span class="sent-hdr"><?php echo $fa?'نماد':'Symbol';?></span>
      <span class="sent-hdr"><?php echo $fa?'موقعیت':'Positioning';?></span>
      <span class="sent-hdr" style="text-align:right;color:#14e0a3"><?php echo $fa?'خرید':'Long';?></span>
      <span class="sent-hdr" style="text-align:right;color:#C8102E"><?php echo $fa?'فروش':'Short';?></span>
    </div>
    <div class="sent-grid" id="sentiment-grid"></div>
    <p class="sent-ts" id="sent-ts"></p>
  </div>

  <!-- ══════════════════════════════════
       WIDGET 4: ECONOMIC CALENDAR
  ══════════════════════════════════ -->
  <div class="tools-widget-wrap ip-animate">

    <style>
    /* ════ CALENDAR WIDGET STYLES ════ */

    /* Header row */
    .ecal-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap;margin-bottom:20px}
    .ecal-title-block{}
    .ecal-live-badge{
      display:inline-flex;align-items:center;gap:5px;
      background:rgba(20,224,163,.08);border:1px solid rgba(20,224,163,.2);
      border-radius:20px;padding:3px 10px;font-size:10px;font-weight:700;
      letter-spacing:.08em;color:#14e0a3;margin-top:6px;
    }
    .ecal-live-dot{width:6px;height:6px;border-radius:50%;background:#14e0a3;
      animation:ecal-pulse 1.8s ease-in-out infinite;}
    @keyframes ecal-pulse{0%,100%{opacity:1;transform:scale(1)}50%{opacity:.4;transform:scale(.7)}}

    /* ── Day strip (scrollable) ── */
    .ecal-day-strip{
      display:flex;gap:6px;margin-bottom:16px;
      overflow-x:auto;padding-bottom:6px;
      scrollbar-width:none;
    }
    .ecal-day-strip::-webkit-scrollbar{display:none}
    .ecal-day-btn{
      flex-shrink:0;display:flex;flex-direction:column;align-items:center;
      padding:8px 14px;border-radius:10px;cursor:pointer;
      border:1px solid rgba(255,255,255,.07);background:rgba(255,255,255,.03);
      transition:all .18s;min-width:56px;position:relative;
    }
    .ecal-day-btn:hover{border-color:rgba(255,255,255,.15);background:rgba(255,255,255,.06)}
    .ecal-day-btn.active{
      background:rgba(200,16,46,.1);border-color:rgba(200,16,46,.35);
    }
    .ecal-day-btn.today{border-color:rgba(20,224,163,.3);}
    .ecal-day-btn.today.active{background:rgba(20,224,163,.1);border-color:rgba(20,224,163,.4);}
    .ecal-day-name{font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;
      color:rgba(255,255,255,.35);margin-bottom:2px;}
    .ecal-day-btn.active .ecal-day-name{color:rgba(255,255,255,.7)}
    .ecal-day-btn.today .ecal-day-name{color:#14e0a3}
    .ecal-day-num{font-size:18px;font-weight:700;color:#fff;line-height:1;font-family:'Bebas Neue',sans-serif;}
    .ecal-day-count{
      font-size:9px;font-weight:700;margin-top:4px;padding:1px 6px;
      border-radius:10px;background:rgba(255,255,255,.06);color:rgba(255,255,255,.3);
    }
    .ecal-day-btn.active .ecal-day-count{background:rgba(200,16,46,.15);color:rgba(255,255,255,.6)}
    .ecal-day-btn.today:not(.active) .ecal-day-count{background:rgba(20,224,163,.1);color:#14e0a3}
    /* high-event indicator dots on day btn */
    .ecal-day-dots{display:flex;gap:2px;margin-top:5px;justify-content:center;min-height:6px}
    .ecal-day-dot-h{width:5px;height:5px;border-radius:50%;background:#C8102E;opacity:.7}
    .ecal-day-dot-m{width:5px;height:5px;border-radius:50%;background:#e07814;opacity:.5}

    /* ── Impact filter pills ── */
    .ecal-impact-row{display:flex;gap:6px;margin-bottom:18px;flex-wrap:wrap;align-items:center}
    .ecal-impact-pill{
      display:inline-flex;align-items:center;gap:5px;
      padding:5px 12px;border-radius:20px;font-size:11px;font-weight:700;
      cursor:pointer;border:1px solid rgba(255,255,255,.08);background:transparent;
      color:rgba(255,255,255,.35);transition:all .15s;
    }
    .ecal-impact-pill:hover{color:rgba(255,255,255,.7);border-color:rgba(255,255,255,.18)}
    .ecal-impact-pill.active{color:#fff}
    .ecal-impact-pill[data-f="all"].active{background:rgba(255,255,255,.07);border-color:rgba(255,255,255,.18)}
    .ecal-impact-pill[data-f="high"].active{background:rgba(200,16,46,.12);border-color:rgba(200,16,46,.4)}
    .ecal-impact-pill[data-f="medium"].active{background:rgba(224,120,20,.1);border-color:rgba(224,120,20,.35)}
    .ecal-impact-pill[data-f="low"].active{background:rgba(20,224,163,.07);border-color:rgba(20,224,163,.2)}
    .ecal-pill-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0}
    .ecal-pill-count{
      font-size:9px;padding:1px 5px;border-radius:8px;
      background:rgba(255,255,255,.07);color:rgba(255,255,255,.4);
      margin-left:2px;
    }
    [dir=rtl] .ecal-pill-count{margin-left:0;margin-right:2px}

    /* ── Timeline list ── */
    .ecal-timeline{display:flex;flex-direction:column;gap:0}
    .ecal-tl-item{
      display:grid;
      grid-template-columns:52px 28px 1fr auto;
      align-items:start;gap:0 10px;
      padding:11px 4px;
      border-bottom:1px solid rgba(255,255,255,.04);
      cursor:pointer;
      transition:background .15s;
      border-radius:8px;
      position:relative;
    }
    .ecal-tl-item:last-child{border-bottom:none}
    .ecal-tl-item:hover{background:rgba(255,255,255,.025)}
    .ecal-tl-item.expanded{background:rgba(255,255,255,.03);border-bottom-color:transparent}
    .ecal-tl-item.has-actual{cursor:default}

    /* time col */
    .ecal-tl-time{
      font-family:'IBM Plex Mono','Courier New',monospace;
      font-size:11.5px;color:rgba(255,255,255,.3);
      padding-top:2px;text-align:center;
    }
    .ecal-tl-time.now{color:#14e0a3;font-weight:700}

    /* impact dot col */
    .ecal-tl-dot{
      display:flex;flex-direction:column;align-items:center;padding-top:4px;gap:3px;
    }
    .ecal-tl-dot-circle{
      width:10px;height:10px;border-radius:50%;flex-shrink:0;
    }
    .ecal-tl-dot-line{width:1px;flex:1;min-height:8px;background:rgba(255,255,255,.06)}
    .dot-high{background:#C8102E;box-shadow:0 0 6px #C8102E66}
    .dot-medium{background:#e07814;box-shadow:0 0 6px #e0781466}
    .dot-low{background:rgba(255,255,255,.15)}

    /* main col */
    .ecal-tl-main{min-width:0}
    .ecal-tl-ccy{
      font-size:10px;font-weight:700;letter-spacing:.08em;
      color:rgba(255,255,255,.3);margin-bottom:2px;
      display:flex;align-items:center;gap:4px;
    }
    .ecal-tl-title{
      font-size:13.5px;font-weight:600;color:rgba(255,255,255,.85);
      line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
    }
    .ecal-tl-item:hover .ecal-tl-title,
    .ecal-tl-item.expanded .ecal-tl-title{white-space:normal;overflow:visible;text-overflow:unset}

    /* right col — actual value or chevron */
    .ecal-tl-right{display:flex;flex-direction:column;align-items:flex-end;gap:4px;padding-top:2px;min-width:64px}
    .ecal-tl-actual{font-size:14px;font-weight:700;font-family:'Bebas Neue',sans-serif;letter-spacing:.03em}
    .ecal-tl-actual.up{color:#14e0a3}
    .ecal-tl-actual.down{color:#C8102E}
    .ecal-tl-actual.flat{color:rgba(255,255,255,.5)}
    .ecal-tl-pending{
      font-size:10px;color:rgba(255,255,255,.2);
      background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);
      border-radius:4px;padding:2px 7px;
    }
    .ecal-tl-chevron{
      color:rgba(255,255,255,.2);transition:transform .2s;font-size:12px;margin-top:2px;
    }
    .ecal-tl-item.expanded .ecal-tl-chevron{transform:rotate(180deg)}

    /* expanded detail panel */
    .ecal-tl-detail{
      grid-column:1/-1;
      display:none;
      padding:12px 12px 6px 90px;
    }
    [dir=rtl] .ecal-tl-detail{padding:12px 90px 6px 12px}
    .ecal-tl-item.expanded .ecal-tl-detail{display:block}
    .ecal-tl-stats{
      display:flex;gap:8px;flex-wrap:wrap;
    }
    .ecal-tl-stat{
      background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.07);
      border-radius:8px;padding:8px 14px;min-width:80px;
    }
    .ecal-tl-stat-lbl{font-size:9px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.25);margin-bottom:3px}
    .ecal-tl-stat-val{font-size:15px;font-weight:700;color:#fff;font-family:'Bebas Neue',sans-serif}
    .ecal-tl-stat-val.up{color:#14e0a3}
    .ecal-tl-stat-val.down{color:#C8102E}

    /* empty / loading */
    .ecal-empty-state{
      padding:40px 20px;text-align:center;color:rgba(255,255,255,.2);font-size:14px;
      display:flex;flex-direction:column;align-items:center;gap:10px;
    }
    .ecal-spinner{
      width:20px;height:20px;border-radius:50%;
      border:2px solid rgba(200,16,46,.15);border-top-color:#C8102E;
      animation:ecal-spin .7s linear infinite;
    }
    @keyframes ecal-spin{to{transform:rotate(360deg)}}

    /* show-more */
    .ecal-show-more{
      margin-top:12px;width:100%;padding:10px;
      background:rgba(255,255,255,.03);border:1px dashed rgba(255,255,255,.1);
      border-radius:10px;font-size:12px;font-weight:700;color:rgba(255,255,255,.3);
      cursor:pointer;transition:all .2s;letter-spacing:.06em;text-align:center;
    }
    .ecal-show-more:hover{background:rgba(200,16,46,.06);border-color:rgba(200,16,46,.2);color:rgba(255,255,255,.6)}

    /* meta */
    .ecal-foot{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;margin-top:16px}
    .ecal-meta-txt{font-size:10.5px;color:rgba(255,255,255,.18)}
    .ecal-count-txt{font-size:10.5px;color:rgba(255,255,255,.25)}

    @media(max-width:480px){
      .ecal-tl-item{grid-template-columns:44px 22px 1fr auto}
      .ecal-tl-detail{padding-left:70px}
      [dir=rtl] .ecal-tl-detail{padding-right:70px;padding-left:12px}
    }
    </style>

    <!-- Header -->
    <div class="ecal-header">
      <div class="ecal-title-block">
        <div class="tools-widget-title" style="margin-bottom:4px">
          <svg width="22" height="22" viewBox="0 0 24 24" stroke-width="1.8" stroke="currentColor" fill="none"><path d="M8 2v4M16 2v4M3 10h18M5 4h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z"/></svg>
          <?php echo $fa?'تقویم اقتصادی':'Economic Calendar';?>
        </div>
        <span class="ecal-live-badge"><span class="ecal-live-dot"></span>LIVE</span>
      </div>
      <div style="font-size:11px;color:rgba(255,255,255,.2);text-align:right;padding-top:4px" id="ecal-meta"></div>
    </div>

    <!-- Day strip -->
    <div class="ecal-day-strip" id="ecal-day-strip">
      <!-- built by JS -->
    </div>

    <!-- Impact filter pills -->
    <div class="ecal-impact-row" id="ecal-impact-row">
      <button class="ecal-impact-pill" data-f="all" onclick="filterCal(this,'all')">
        <span class="ecal-pill-dot" style="background:rgba(255,255,255,.3)"></span>
        <?php echo $fa?'همه':'All';?> <span class="ecal-pill-count" id="pill-count-all">—</span>
      </button>
      <button class="ecal-impact-pill active" data-f="high" onclick="filterCal(this,'high')">
        <span class="ecal-pill-dot" style="background:#C8102E"></span>
        <?php echo $fa?'مهم':'High';?> <span class="ecal-pill-count" id="pill-count-high">—</span>
      </button>
      <button class="ecal-impact-pill" data-f="medium" onclick="filterCal(this,'medium')">
        <span class="ecal-pill-dot" style="background:#e07814"></span>
        <?php echo $fa?'متوسط':'Medium';?> <span class="ecal-pill-count" id="pill-count-medium">—</span>
      </button>
      <button class="ecal-impact-pill" data-f="low" onclick="filterCal(this,'low')">
        <span class="ecal-pill-dot" style="background:rgba(255,255,255,.2)"></span>
        <?php echo $fa?'کم':'Low';?> <span class="ecal-pill-count" id="pill-count-low">—</span>
      </button>
    </div>

    <!-- Timeline -->
    <div class="ecal-timeline" id="ecal-timeline">
      <div class="ecal-empty-state"><div class="ecal-spinner"></div><?php echo $fa?'در حال بارگذاری...':'Loading live events...';?></div>
    </div>

    <!-- Show more -->
    <button class="ecal-show-more" id="ecal-show-more" style="display:none" onclick="ecalShowMore()"></button>

    <!-- Footer -->
    <div class="ecal-foot">
      <span class="ecal-meta-txt" id="ecal-meta2"></span>
      <div style="display:flex;align-items:center;gap:10px">
        <span class="ecal-count-txt" id="ecal-event-count"></span>
        <button class="ecal-share-trigger" id="ecal-share-btn" onclick="ecalOpenShare()" style="display:none">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
          <?php echo $fa?'اشتراک‌گذاری':'Share';?>
        </button>
      </div>
    </div>

  </div>

  <!-- ══════════════════════════════════
       SHARE MODAL
  ══════════════════════════════════ -->
  <div id="ecal-share-modal" class="hidden">
    <div class="esm-backdrop" onclick="ecalCloseShare()"></div>
    <div class="esm-panel">
      <div class="esm-head">
        <div>
          <div class="esm-title"><?php echo $fa?'اشتراک‌گذاری تقویم':'Share Calendar';?></div>
          <div class="esm-sub" id="esm-subtitle"></div>
        </div>
        <button class="esm-close" onclick="ecalCloseShare()">✕</button>
      </div>
      <div class="esm-format-row">
        <button class="esm-fmt active" data-fmt="square" onclick="esSetFormat(this,'square')">
          <span class="esm-fmt-icon">▪</span><?php echo $fa?'مربع':'Square';?><span class="esm-fmt-sub">1080×1080</span>
        </button>
        <button class="esm-fmt" data-fmt="story" onclick="esSetFormat(this,'story')">
          <span class="esm-fmt-icon">▮</span><?php echo $fa?'استوری':'Story';?><span class="esm-fmt-sub">1080×1920</span>
        </button>
        <button class="esm-fmt" data-fmt="wide" onclick="esSetFormat(this,'wide')">
          <span class="esm-fmt-icon">▬</span><?php echo $fa?'افقی':'Wide';?><span class="esm-fmt-sub">1200×675</span>
        </button>
      </div>
      <div class="esm-preview-wrap">
        <canvas id="esm-canvas"></canvas>
        <div class="esm-preview-label"><?php echo $fa?'پیش‌نمایش':'Preview';?></div>
      </div>
      <div class="esm-actions">
        <button class="esm-action-btn esm-download" onclick="esDownload()">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
          <?php echo $fa?'دانلود PNG':'Download PNG';?>
        </button>
        <button class="esm-action-btn esm-native" id="esm-native-btn" onclick="esNativeShare()">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M4 12v8a2 2 0 002 2h12a2 2 0 002-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
          <?php echo $fa?'اشتراک مستقیم':'Share';?>
        </button>
      </div>
      <div class="esm-platforms">
        <div class="esm-plat-label"><?php echo $fa?'اشتراک‌گذاری لینک در:':'Share link on:';?></div>
        <div class="esm-plat-row">
          <a class="esm-plat-btn esm-twitter" id="esm-tw-btn" href="#" target="_blank" rel="noopener">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.746l7.73-8.835L1.254 2.25H8.08l4.253 5.622 5.912-5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
            X / Twitter
          </a>
          <a class="esm-plat-btn esm-telegram" id="esm-tg-btn" href="#" target="_blank" rel="noopener">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm5.562 8.248l-2.04 9.607c-.152.67-.555.834-1.123.518l-3.1-2.284-1.495 1.438c-.165.166-.305.305-.625.305l.222-3.166 5.76-5.202c.25-.222-.055-.345-.388-.123L7.08 14.88l-3.05-.953c-.663-.207-.675-.663.138-.98l11.914-4.595c.552-.2 1.034.135.48.896z"/></svg>
            Telegram
          </a>
          <a class="esm-plat-btn esm-whatsapp" id="esm-wa-btn" href="#" target="_blank" rel="noopener">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            WhatsApp
          </a>
          <button class="esm-plat-btn esm-copy" onclick="esCopyLink()">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>
            <span id="esm-copy-label"><?php echo $fa?'کپی لینک':'Copy Link';?></span>
          </button>
        </div>
        <p class="esm-note"><?php echo $fa?'تصویر را دانلود کرده و به پست خود در اینستاگرام یا توییتر ضمیمه کنید.':'Download the image and attach it to your Instagram or Twitter post.';?></p>
      </div>
    </div>
  </div>

  <style>
  /* ── Share trigger ── */
  .ecal-share-trigger{
    display:inline-flex;align-items:center;gap:5px;
    padding:5px 13px;border-radius:20px;font-size:11px;font-weight:700;letter-spacing:.06em;
    border:1px solid rgba(200,16,46,.3);background:rgba(200,16,46,.07);color:rgba(255,255,255,.6);
    cursor:pointer;transition:all .2s;
  }
  .ecal-share-trigger:hover{background:rgba(200,16,46,.15);border-color:rgba(200,16,46,.5);color:#fff}

  /* ── Modal shell ── */
  #ecal-share-modal{position:fixed;inset:0;z-index:9999;display:flex;align-items:center;justify-content:center;padding:16px}
  #ecal-share-modal.hidden{display:none!important}
  .esm-backdrop{position:absolute;inset:0;background:rgba(0,0,0,.78);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
  .esm-panel{
    position:relative;z-index:1;
    background:#0d1017;border:1px solid rgba(255,255,255,.1);border-radius:20px;
    padding:28px;width:100%;max-width:500px;max-height:92vh;overflow-y:auto;
    box-shadow:0 32px 80px rgba(0,0,0,.7);
  }
  .esm-head{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:20px}
  .esm-title{font-size:18px;font-weight:700;color:#fff}
  .esm-sub{font-size:11.5px;color:rgba(255,255,255,.3);margin-top:3px}
  .esm-close{
    width:32px;height:32px;border-radius:50%;border:1px solid rgba(255,255,255,.1);
    background:rgba(255,255,255,.04);color:rgba(255,255,255,.4);cursor:pointer;
    display:flex;align-items:center;justify-content:center;font-size:13px;
    transition:all .15s;flex-shrink:0;
  }
  .esm-close:hover{background:rgba(200,16,46,.15);border-color:rgba(200,16,46,.3);color:#fff}

  /* format tabs */
  .esm-format-row{display:flex;gap:8px;margin-bottom:20px}
  .esm-fmt{
    flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
    padding:10px 6px;border-radius:10px;cursor:pointer;
    border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);
    color:rgba(255,255,255,.4);transition:all .15s;font-size:12px;font-weight:700;
  }
  .esm-fmt:hover{border-color:rgba(255,255,255,.18);color:rgba(255,255,255,.7)}
  .esm-fmt.active{background:rgba(200,16,46,.1);border-color:rgba(200,16,46,.35);color:#fff}
  .esm-fmt-icon{font-size:20px;line-height:1}
  .esm-fmt-sub{font-size:9px;font-weight:400;color:rgba(255,255,255,.2);margin-top:2px}
  .esm-fmt.active .esm-fmt-sub{color:rgba(255,255,255,.4)}

  /* canvas preview */
  .esm-preview-wrap{
    background:#060810;border:1px solid rgba(255,255,255,.06);border-radius:12px;
    padding:12px;margin-bottom:20px;display:flex;flex-direction:column;align-items:center;gap:8px;
  }
  #esm-canvas{max-width:100%;max-height:300px;border-radius:6px;box-shadow:0 8px 32px rgba(0,0,0,.5);display:block}
  .esm-preview-label{font-size:10px;color:rgba(255,255,255,.2);letter-spacing:.08em;text-transform:uppercase}

  /* action buttons */
  .esm-actions{display:flex;gap:10px;margin-bottom:20px}
  .esm-action-btn{
    flex:1;display:flex;align-items:center;justify-content:center;gap:7px;
    padding:12px;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;
    transition:all .15s;border:none;
  }
  .esm-download{background:#C8102E;color:#fff}
  .esm-download:hover{background:#e01535;transform:translateY(-1px)}
  .esm-native{background:rgba(20,224,163,.08);border:1px solid rgba(20,224,163,.25)!important;color:#14e0a3}
  .esm-native:hover{background:rgba(20,224,163,.15)}

  /* platform links */
  .esm-platforms{border-top:1px solid rgba(255,255,255,.06);padding-top:16px}
  .esm-plat-label{font-size:10px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:rgba(255,255,255,.22);margin-bottom:10px}
  .esm-plat-row{display:flex;gap:7px;flex-wrap:wrap}
  .esm-plat-btn{
    display:inline-flex;align-items:center;gap:6px;
    padding:7px 13px;border-radius:8px;font-size:12px;font-weight:700;
    border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.04);
    color:rgba(255,255,255,.45);cursor:pointer;transition:all .15s;text-decoration:none;
  }
  .esm-plat-btn:hover{color:#fff;border-color:rgba(255,255,255,.2)}
  .esm-twitter:hover{color:#1d9bf0;border-color:rgba(29,155,240,.35);background:rgba(29,155,240,.07)}
  .esm-telegram:hover{color:#29b6f6;border-color:rgba(41,182,246,.35);background:rgba(41,182,246,.07)}
  .esm-whatsapp:hover{color:#25d366;border-color:rgba(37,211,102,.35);background:rgba(37,211,102,.07)}
  .esm-copy:hover{color:#14e0a3;border-color:rgba(20,224,163,.3);background:rgba(20,224,163,.06)}
  .esm-note{font-size:10.5px;color:rgba(255,255,255,.18);margin-top:12px;line-height:1.6}
  </style>
  <div class="tools-widget-wrap ip-animate">
    <div class="tools-widget-title">
      <svg width="22" height="22" viewBox="0 0 24 24" stroke-width="1.8"><circle cx="12" cy="12" r="10"/><path d="M12 2a15.3 15.3 0 010 20M2 12h20" stroke-linecap="round"/></svg>
      <?php echo $fa?'تبدیل ارز':'Currency Converter';?>
    </div>
    <p class="tools-widget-sub"><?php echo $fa?'نرخ‌های تقریبی میان‌بازار برای ۶۰+ ارز.':'Indicative mid-market rates for 60+ currencies — updates every 30s.';?></p>
    <div class="cc-main">
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'مقدار':'Amount';?></label>
        <input class="tw-input" id="cc-amount" type="number" value="1000" min="0" step="1" oninput="calcCC()">
      </div>
      <div class="tw-field" style="align-items:center;padding-bottom:2px">
        <button class="cc-swap-btn" onclick="swapCC()" title="Swap">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M7 16V4m0 0L3 8m4-4 4 4M17 8v12m0 0 4-4m-4 4-4-4"/></svg>
        </button>
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'مقدار تبدیل‌شده':'Converted';?></label>
        <input class="tw-input" id="cc-result-input" type="number" readonly style="opacity:.6">
      </div>
    </div>
    <div class="tw-row tw-row-2">
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'از ارز':'From';?></label>
        <select class="tw-select" id="cc-from" onchange="calcCC()">
          <option value="USD">🇺🇸 USD — US Dollar</option>
          <option value="EUR">🇪🇺 EUR — Euro</option>
          <option value="GBP">🇬🇧 GBP — British Pound</option>
          <option value="JPY">🇯🇵 JPY — Japanese Yen</option>
          <option value="CHF">🇨🇭 CHF — Swiss Franc</option>
          <option value="AUD">🇦🇺 AUD — Australian Dollar</option>
          <option value="CAD">🇨🇦 CAD — Canadian Dollar</option>
          <option value="NZD">🇳🇿 NZD — New Zealand Dollar</option>
          <option value="CNY">🇨🇳 CNY — Chinese Yuan</option>
          <option value="SGD">🇸🇬 SGD — Singapore Dollar</option>
          <option value="AED">🇦🇪 AED — UAE Dirham</option>
          <option value="TRY">🇹🇷 TRY — Turkish Lira</option>
          <option value="XAUUSD">🥇 XAU — Gold (troy oz)</option>
        </select>
      </div>
      <div class="tw-field">
        <label class="tw-label"><?php echo $fa?'به ارز':'To';?></label>
        <select class="tw-select" id="cc-to" onchange="calcCC()">
          <option value="EUR">🇪🇺 EUR — Euro</option>
          <option value="USD">🇺🇸 USD — US Dollar</option>
          <option value="GBP">🇬🇧 GBP — British Pound</option>
          <option value="JPY">🇯🇵 JPY — Japanese Yen</option>
          <option value="CHF">🇨🇭 CHF — Swiss Franc</option>
          <option value="AUD">🇦🇺 AUD — Australian Dollar</option>
          <option value="CAD">🇨🇦 CAD — Canadian Dollar</option>
          <option value="NZD">🇳🇿 NZD — New Zealand Dollar</option>
          <option value="CNY">🇨🇳 CNY — Chinese Yuan</option>
          <option value="AED">🇦🇪 AED — UAE Dirham</option>
          <option value="TRY">🇹🇷 TRY — Turkish Lira</option>
          <option value="XAUUSD">🥇 XAU — Gold (troy oz)</option>
        </select>
      </div>
    </div>
    <div class="cc-rate-display" id="cc-rate-display">
      <div>
        <div class="tw-result-label"><?php echo $fa?'نرخ میانی':'Mid Rate';?></div>
        <div class="cc-rate-val" id="cc-rate-val">—</div>
        <div class="cc-rate-meta" id="cc-rate-meta"><?php echo $fa?'در حال بارگذاری...':'Loading...';?></div>
      </div>
      <div style="text-align:right">
        <div class="cc-rate-change" id="cc-change" style="display:none">—</div>
        <svg class="cc-sparkline" id="cc-sparkline" viewBox="0 0 200 50" preserveAspectRatio="none"></svg>
      </div>
    </div>
  </div>

</div><!-- /ip-container -->
</section>

<!-- ═══ CTA ═══ -->
<section class="ip-section alt" style="padding:56px 0">
  <div class="ip-container">
    <div class="ip-cta-strip">
      <div class="ip-cta-strip-text">
        <h3><?php echo $fa?'آماده شروع هستید؟':'Ready to get started?';?></h3>
        <p><?php echo $fa?'حساب خود را باز کنید و به همه ابزارهای STB دسترسی پیدا کنید.':'Open your account and access all STB features in minutes.';?></p>
      </div>
      <div class="ip-cta-strip-btns">
        <a href="https://crm.stbbrokers.com/register" class="ip-btn-red"><?php echo $fa?'باز کردن حساب':'Open Account';?></a>
        <a href="<?php echo stb_url($B.'/faq/');?>" class="ip-btn-ghost"><?php echo $fa?'سوالات متداول':'View FAQ';?></a>
      </div>
    </div>
  </div>
</section>

<script>
(function(){
'use strict';

/* ═══════════════════════════════════════
   SHARED DATA
═══════════════════════════════════════ */
var FA = document.documentElement.getAttribute('lang')==='fa' || document.documentElement.getAttribute('dir')==='rtl';

var RATES_USD = {
  USD:1, EUR:0.924, GBP:0.791, JPY:149.5, CHF:0.901,
  AUD:1.535, CAD:1.361, NZD:1.657, CNY:7.241,
  SGD:1.340, AED:3.673, TRY:32.10, XAUUSD:0.000426
};

var CONTRACT={
  EURUSD:100000,GBPUSD:100000,USDJPY:100000,AUDUSD:100000,
  USDCAD:100000,XAUUSD:100,XAGUSD:5000,USOIL:1000,
  NAS100:1,SPX500:1
};

var PRICES={
  EURUSD:1.08500,GBPUSD:1.27200,USDJPY:149.500,AUDUSD:0.65200,
  USDCAD:1.36100,XAUUSD:2350.00,XAGUSD:28.500,USOIL:82.500,
  NAS100:18500.0,SPX500:5250.00
};

/* Live hydration from /wp-json/stb/v1/prices via prices.js global */
function stbHydrateFromFeed(){
  if(!window.stbPrices||!window.stbPrices.get) return false;
  /* Map feed codes onto local PRICES keys */
  var map={EURUSD:'EURUSD',GBPUSD:'GBPUSD',USDJPY:'USDJPY',AUDUSD:'AUDUSD',USDCAD:'USDCAD',
           XAUUSD:'XAUUSD',XAGUSD:'XAGUSD',NAS100:'NAS100',SPX500:'SPX500',USOIL:'USOIL'};
  var any=false;
  Object.keys(map).forEach(function(localK){
    var feedRow=window.stbPrices.get(map[localK]);
    if(feedRow && feedRow.price){PRICES[localK]=+(feedRow.price);any=true;}
  });
  /* Hydrate account-currency conversion: derive 1 USD = X using USD-base pairs */
  /* USDJPY ask = how many JPY per 1 USD */
  var jpy=window.stbPrices.get('USDJPY'); if(jpy&&jpy.price) RATES_USD.JPY=jpy.price;
  var chf=window.stbPrices.get('USDCHF'); if(chf&&chf.price) RATES_USD.CHF=chf.price;
  var cad=window.stbPrices.get('USDCAD'); if(cad&&cad.price) RATES_USD.CAD=cad.price;
  /* EURUSD/GBPUSD/AUDUSD are inverted (1 EUR = X USD => 1 USD = 1/X EUR) */
  var eur=window.stbPrices.get('EURUSD'); if(eur&&eur.price) RATES_USD.EUR=+(1/eur.price).toFixed(5);
  var gbp=window.stbPrices.get('GBPUSD'); if(gbp&&gbp.price) RATES_USD.GBP=+(1/gbp.price).toFixed(5);
  var aud=window.stbPrices.get('AUDUSD'); if(aud&&aud.price) RATES_USD.AUD=+(1/aud.price).toFixed(5);
  /* XAU base unit per USD (1 / gold price) */
  var au=window.stbPrices.get('XAUUSD'); if(au&&au.price) RATES_USD.XAUUSD=+(1/au.price).toFixed(8);
  if(any){ try{calcPip();}catch(e){} try{calcMargin();}catch(e){} try{calcCC();}catch(e){} }
  return any;
}
/* Listen for fresh feeds (fires whenever prices.js polls) */
document.addEventListener('stb:pricesUpdated', stbHydrateFromFeed);
/* Try once on load in case feed arrived before this block ran */
setTimeout(stbHydrateFromFeed, 600);
setTimeout(stbHydrateFromFeed, 2500);

function fmt(n,dec){
  if(isNaN(n)||n===null)return '—';
  return n.toLocaleString('en-US',{minimumFractionDigits:dec,maximumFractionDigits:dec});
}
function flash(el){
  el.classList.remove('tw-flash');
  void el.offsetWidth;
  el.classList.add('tw-flash');
}

/* ═══════════════════════════════════════
   WIDGET 1 — PIP CALCULATOR
═══════════════════════════════════════ */
window.calcPip = function(){
  var sel = document.getElementById('pip-symbol');
  var opt = sel.options[sel.selectedIndex];
  var sym = sel.value;
  var pip = parseFloat(opt.getAttribute('data-pip'));
  var quote = opt.getAttribute('data-quote');
  var lots = parseFloat(document.getElementById('pip-lots').value)||1;
  var accy = document.getElementById('pip-accy').value;
  var cs = CONTRACT[sym]||100000;
  var price = PRICES[sym]||1;

  /* pip value in quote ccy */
  var pipVal = pip * cs * lots;

  /* convert to account ccy */
  var rateQuoteToUSD = 1;
  if(quote==='JPY') rateQuoteToUSD = 1/149.5;
  else if(quote==='CAD') rateQuoteToUSD = 1/1.361;

  var pipUSD = pipVal * rateQuoteToUSD;

  /* convert USD to accy */
  var rateUSDtoAccy = accy==='USD'?1:(1/RATES_USD[accy]||1);
  var pipAccy = pipUSD * rateUSDtoAccy;

  var notional = cs * lots * price;
  var notionalAccy = notional * (accy==='USD'?1:1/RATES_USD[accy]);

  var dec = pipAccy>100?2:pipAccy>1?2:4;
  document.getElementById('pip-result').innerHTML = fmt(pipAccy,dec)+'<span>'+accy+'</span>';
  document.getElementById('pip-result-10').textContent = fmt(pipAccy*10,2);
  document.getElementById('pip-contract').innerHTML = cs.toLocaleString()+'<span>units</span>';
  document.getElementById('pip-notional').textContent = fmt(notionalAccy,0);
  flash(document.getElementById('pip-result-box'));
};

/* ═══════════════════════════════════════
   WIDGET 2 — MARGIN CALCULATOR
═══════════════════════════════════════ */
window.calcMargin = function(){
  var sel = document.getElementById('mg-symbol');
  var opt = sel.options[sel.selectedIndex];
  var sym = sel.value;
  var price = parseFloat(opt.getAttribute('data-price'))||PRICES[sym]||1;
  price = PRICES[sym]||price;
  var lev = parseFloat(document.getElementById('mg-lev').value)||500;
  var lots = parseFloat(document.getElementById('mg-lots').value)||1;
  var accy = document.getElementById('mg-accy').value;
  var cs = CONTRACT[sym]||100000;

  var tradeVal = cs * lots * price;
  var marginUSD = tradeVal / lev;
  var convRate = accy==='USD'?1:(1/RATES_USD[accy]||1);
  var marginAccy = marginUSD * convRate;
  var tradeValAccy = tradeVal * convRate;

  document.getElementById('mg-result').innerHTML = fmt(marginAccy,2)+'<span>'+accy+'</span>';
  document.getElementById('mg-value').innerHTML = fmt(tradeValAccy,0)+'<span>'+accy+'</span>';
  var priceStr = price>100?fmt(price,2):fmt(price,5);
  document.getElementById('mg-price').textContent = priceStr;

  var pct = Math.min(100, (lev/500)*100);
  document.getElementById('mg-lever-bar').style.width = pct+'%';
  document.getElementById('mg-lev-label').textContent = '1:'+lev;
  flash(document.getElementById('mg-result-box'));
};

/* ═══════════════════════════════════════
   WIDGET 3 — MARKET SENTIMENT
═══════════════════════════════════════ */
var SENT_DATA = [
  {sym:'EUR/USD', bull:62},
  {sym:'GBP/USD', bull:45},
  {sym:'USD/JPY', bull:71},
  {sym:'XAU/USD', bull:58},
  {sym:'NAS100',  bull:77},
  {sym:'SPX500',  bull:68},
  {sym:'BTC/USD', bull:83},
  {sym:'US Oil',  bull:39},
];

function buildSentiment(){
  var g = document.getElementById('sentiment-grid');
  if(!g)return;
  g.innerHTML = '';
  SENT_DATA.forEach(function(d){
    var bear = 100-d.bull;
    var row = document.createElement('div');
    row.className = 'sent-row';
    row.innerHTML =
      '<div class="sent-sym">'+d.sym+'</div>'+
      '<div class="sent-bar-wrap">'+
        '<div class="sent-bar-bull" style="width:0%"></div>'+
        '<div class="sent-bar-bear" style="width:0%"></div>'+
      '</div>'+
      '<div class="sent-pct-bull">'+d.bull+'%</div>'+
      '<div class="sent-pct-bear">'+bear+'%</div>';
    g.appendChild(row);
    /* animate in */
    setTimeout(function(){
      row.querySelector('.sent-bar-bull').style.width = d.bull+'%';
      row.querySelector('.sent-bar-bear').style.width = bear+'%';
    },80);
  });
  var now = new Date();
  var ts = document.getElementById('sent-ts');
  if(ts) ts.textContent = (FA?'آخرین بروزرسانی: ':'Last updated: ')+now.toLocaleTimeString();
}

window.refreshSentiment = function(){
  var btn = document.getElementById('sent-refresh-btn');
  var ico = document.getElementById('sent-refresh-icon');
  if(btn){ btn.disabled = true; }
  if(ico){
    ico.style.transition = 'transform .6s linear';
    ico.style.transform = 'rotate(360deg)';
  }
  /* Pull real technical sentiment from /wp-json/stb/v1/sentiment */
  var apiBase = (window.stbPricesConfig && window.stbPricesConfig.apiUrl)
    ? window.stbPricesConfig.apiUrl.replace(/prices$/, 'sentiment')
    : '/NewSite/wp-json/stb/v1/sentiment';
  fetch(apiBase, { credentials: 'same-origin' })
    .then(function(r){ return r.json(); })
    .then(function(d){
      if (d && d.ok && d.sentiment && d.sentiment.length) {
        SENT_DATA = d.sentiment.map(function(x){ return {sym:x.sym, bull:x.bull}; });
      }
      setTimeout(function(){
        buildSentiment();
        if(btn) btn.disabled = false;
        if(ico){ ico.style.transition = 'none'; ico.style.transform = 'rotate(0)'; }
      }, 400);
    })
    .catch(function(){
      /* on failure keep current SENT_DATA, just re-render */
      setTimeout(function(){
        buildSentiment();
        if(btn) btn.disabled = false;
        if(ico){ ico.style.transition = 'none'; ico.style.transform = 'rotate(0)'; }
      }, 400);
    });
};
/* Initial real fetch on load (replaces hardcoded SENT_DATA before first paint) */
setTimeout(window.refreshSentiment, 400);
/* Auto-refresh every 5 minutes (was 20s of fake drift) */
setInterval(window.refreshSentiment, 5*60*1000);

/* ═══════════════════════════════════════
   WIDGET 4 — ECONOMIC CALENDAR (LIVE TIMELINE)
═══════════════════════════════════════ */
var CAL_DATA      = [];
var CAL_META      = {};
var calDayFilter  = 'today';   /* default: today */
var calImpact     = 'high';    /* default: high only */
var calLoaded     = false;
var calShowLimit  = 20;        /* items shown before "show more" */
var calShowAll    = false;

/* ── helpers ── */
function todayStr(){
  var d = new Date();
  return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][d.getDay()]+
    ', '+['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()]+
    ' '+d.getDate()+', '+d.getFullYear();
}
function shortDay(day){
  var p = day.split(' ');
  return p[0].slice(0,3).toUpperCase();
}
function shortDate(day){
  var p = day.split(' ');
  return p[2]||'';
}

/* ── Build day strip from loaded data ── */
function buildDayStrip(){
  var wrap = document.getElementById('ecal-day-strip');
  if(!wrap) return;
  var days = [], dayCounts = {};
  CAL_DATA.forEach(function(e){
    if(!e.day) return;
    if(days.indexOf(e.day)===-1) days.push(e.day);
    dayCounts[e.day] = (dayCounts[e.day]||0)+1;
  });
  var today = todayStr();
  var firstDay = days[0]||'';
  /* auto-select today if present, else nearest day */
  var bestDay = days.indexOf(today)!==-1 ? today : firstDay;
  calDayFilter = bestDay;

  var html = '';
  days.forEach(function(d){
    var isToday  = d === today;
    var isActive = d === calDayFilter;
    var hi = CAL_DATA.filter(function(e){return e.day===d&&e.impact==='high'}).length;
    var md = CAL_DATA.filter(function(e){return e.day===d&&e.impact==='medium'}).length;
    var cls = 'ecal-day-btn'+(isToday?' today':'')+(isActive?' active':'');
    var dots = '';
    for(var i=0;i<Math.min(hi,3);i++) dots+='<span class="ecal-day-dot-h"></span>';
    for(var i=0;i<Math.min(md,2);i++) dots+='<span class="ecal-day-dot-m"></span>';
    html += '<button class="'+cls+'" data-day="'+encodeURIComponent(d)+'" onclick="setCalDay(this,\''+encodeURIComponent(d)+'\')">'+
      '<div class="ecal-day-name">'+(isToday?'TODAY':shortDay(d))+'</div>'+
      '<div class="ecal-day-num">'+shortDate(d)+'</div>'+
      '<div class="ecal-day-dots">'+dots+'</div>'+
      '<div class="ecal-day-count">'+dayCounts[d]+'</div>'+
    '</button>';
  });
  wrap.innerHTML = html;
}

window.setCalDay = function(btn, encoded){
  document.querySelectorAll('.ecal-day-btn').forEach(function(b){b.classList.remove('active')});
  btn.classList.add('active');
  calDayFilter = decodeURIComponent(encoded);
  calShowAll   = false;
  esUpdateLinks();
  renderCalendar();
};

window.filterCal = function(btn, f){
  document.querySelectorAll('.ecal-impact-pill').forEach(function(b){b.classList.remove('active')});
  btn.classList.add('active');
  calImpact  = f;
  calShowAll = false;
  esUpdateLinks();
  renderCalendar();
};

window.ecalShowMore = function(){
  calShowAll = true;
  renderCalendar();
};

/* ── Toggle expand on row click ── */
window.ecalToggle = function(id){
  var el = document.getElementById('ecal-item-'+id);
  if(!el) return;
  el.classList.toggle('expanded');
};

/* ── Update pill counts for current day ── */
function updatePillCounts(dayEvents){
  var counts = {all:0,high:0,medium:0,low:0};
  dayEvents.forEach(function(e){
    counts.all++;
    counts[e.impact]=(counts[e.impact]||0)+1;
  });
  ['all','high','medium','low'].forEach(function(k){
    var el = document.getElementById('pill-count-'+k);
    if(el) el.textContent = counts[k]||0;
  });
}

/* ── Main render ── */
function renderCalendar(){
  var tl = document.getElementById('ecal-timeline');
  if(!tl) return;

  if(!calLoaded){
    tl.innerHTML = '<div class="ecal-empty-state"><div class="ecal-spinner"></div>'+(FA?'در حال بارگذاری...':'Loading live events...')+'</div>';
    return;
  }

  /* filter by day */
  var dayEvents = CAL_DATA.filter(function(e){ return e.day === calDayFilter; });
  updatePillCounts(dayEvents);

  /* filter by impact */
  var filtered = calImpact === 'all' ? dayEvents :
    dayEvents.filter(function(e){ return e.impact === calImpact; });

  /* update event count footer */
  var cnt = document.getElementById('ecal-event-count');
  if(cnt) cnt.textContent = filtered.length + (FA?' رویداد':' events');

  if(!filtered.length){
    var label = calImpact==='high'?(FA?'رویداد مهمی یافت نشد':'No high-impact events'):(FA?'رویداری یافت نشد':'No events found');
    tl.innerHTML = '<div class="ecal-empty-state">'+label+'</div>';
    document.getElementById('ecal-show-more').style.display='none';
    return;
  }

  /* pagination */
  var limit  = calShowAll ? filtered.length : calShowLimit;
  var subset = filtered.slice(0, limit);
  var more   = filtered.length - subset.length;

  var html = '';
  subset.forEach(function(e, idx){
    var dotCls  = 'dot-'+(e.impact||'low');
    var isLast  = idx === subset.length - 1;
    var hasAct  = e.actual && e.actual.trim() !== '';
    var actCls  = e.dir==='up'?'up':e.dir==='down'?'down':'flat';

    var rightHtml = '';
    if(hasAct){
      rightHtml = '<span class="ecal-tl-actual '+actCls+'">'+
        (e.dir==='up'?'▲ ':e.dir==='down'?'▼ ':'')+e.actual+'</span>';
    } else {
      rightHtml = '<span class="ecal-tl-pending">'+(FA?'در انتظار':'Pending')+'</span>';
    }
    rightHtml += '<span class="ecal-tl-chevron">▾</span>';

    /* detail panel */
    var prev = e.previous||'—', fore = e.forecast||'—', act = e.actual||'—';
    var actStatCls = e.dir==='up'?'up':e.dir==='down'?'down':'';
    var detail =
      '<div class="ecal-tl-detail">'+
        '<div class="ecal-tl-stats">'+
          '<div class="ecal-tl-stat"><div class="ecal-tl-stat-lbl">'+(FA?'قبلی':'Previous')+'</div><div class="ecal-tl-stat-val">'+prev+'</div></div>'+
          '<div class="ecal-tl-stat"><div class="ecal-tl-stat-lbl">'+(FA?'پیش‌بینی':'Forecast')+'</div><div class="ecal-tl-stat-val">'+fore+'</div></div>'+
          '<div class="ecal-tl-stat"><div class="ecal-tl-stat-lbl">'+(FA?'واقعی':'Actual')+'</div><div class="ecal-tl-stat-val '+actStatCls+'">'+act+'</div></div>'+
        '</div>'+
      '</div>';

    html +=
      '<div class="ecal-tl-item" id="ecal-item-'+e.id+'" onclick="ecalToggle(\''+e.id+'\')">'+
        '<div class="ecal-tl-time">'+( e.time||'—' )+'</div>'+
        '<div class="ecal-tl-dot">'+
          '<div class="ecal-tl-dot-circle '+dotCls+'"></div>'+
          (!isLast?'<div class="ecal-tl-dot-line"></div>':'')+
        '</div>'+
        '<div class="ecal-tl-main">'+
          '<div class="ecal-tl-ccy"><span>'+e.flag+'</span>'+e.ccy+'</div>'+
          '<div class="ecal-tl-title">'+e.event+'</div>'+
        '</div>'+
        '<div class="ecal-tl-right">'+rightHtml+'</div>'+
        detail+
      '</div>';
  });

  tl.innerHTML = html;

  /* show more button */
  var smBtn = document.getElementById('ecal-show-more');
  if(more > 0 && !calShowAll){
    smBtn.style.display = 'block';
    smBtn.textContent   = (FA?'نمایش ':'Show ')+more+(FA?' رویداد دیگر':' more events');
  } else {
    smBtn.style.display = 'none';
  }
}

/* ── Fetch live JSON ── */
function loadCalendar(){
  var url = '<?php echo $B; ?>/wp-content/uploads/stb-ecal.json?_='+Math.floor(Date.now()/60000);
  fetch(url)
    .then(function(r){ return r.json(); })
    .then(function(data){
      CAL_DATA  = data.events || [];
      CAL_META  = data;
      calLoaded = true;
      buildDayStrip();
      renderCalendar();
      esShowShareBtn();
      /* meta footer */
      var m2 = document.getElementById('ecal-meta2');
      if(m2 && data.fetched_at){
        var dt = new Date(data.fetched_at);
        m2.textContent = (FA?'بروزرسانی: ':'Updated: ')+dt.toLocaleTimeString()+' · Investing.com';
      }
      var m = document.getElementById('ecal-meta');
      if(m) m.textContent = (data.date_from||'')+' → '+(data.date_to||'');
    })
    .catch(function(e){
      calLoaded = true;
      CAL_DATA  = [];
      renderCalendar();
    });
}

loadCalendar();
setInterval(loadCalendar, 5*60*1000);

/* ═══════════════════════════════════════
   WIDGET 5 — CURRENCY CONVERTER
═══════════════════════════════════════ */
var ccSparkData = [];

function genSparkLine(){
  var points = [];
  var v = 1;
  for(var i=0;i<20;i++){
    v += (Math.random()-0.5)*0.004;
    points.push({x:i*10.5,y:25-(v-1)*2000});
  }
  return points;
}

function drawSparkLine(pts){
  var svg = document.getElementById('cc-sparkline');
  if(!svg||!pts.length)return;
  var d = pts.map(function(p,i){return (i===0?'M':'L')+p.x+','+Math.min(48,Math.max(2,p.y));}).join(' ');
  var color = pts[pts.length-1].y < pts[0].y ? '#14e0a3' : '#C8102E';
  svg.innerHTML = '<path d="'+d+'" fill="none" stroke="'+color+'" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>';
}

window.calcCC = function(){
  var from = document.getElementById('cc-from').value;
  var to   = document.getElementById('cc-to').value;
  var amt  = parseFloat(document.getElementById('cc-amount').value)||0;

  var fromRate = RATES_USD[from]||1;
  var toRate   = RATES_USD[to]||1;
  var rate = toRate / fromRate;
  var result = amt * rate;

  var dec = rate>100?2:rate>1?4:6;
  document.getElementById('cc-result-input').value = fmt(result,2).replace(/,/g,'');
  document.getElementById('cc-rate-val').textContent = '1 '+from+' = '+fmt(rate,dec)+' '+to;
  document.getElementById('cc-rate-meta').textContent = (FA?'نرخ میانی · ':'Mid-market rate · ')+new Date().toLocaleTimeString();

  /* sparkline */
  if(!ccSparkData.length) ccSparkData = genSparkLine();
  else {
    ccSparkData.push({x:ccSparkData[ccSparkData.length-1].x+10.5, y:ccSparkData[ccSparkData.length-1].y+(Math.random()-0.5)*2});
    if(ccSparkData.length>20) ccSparkData.shift();
    ccSparkData = ccSparkData.map(function(p,i){return {x:i*10.5,y:p.y};});
  }
  drawSparkLine(ccSparkData);

  /* change badge */
  var chg = ((Math.random()-0.48)*0.3).toFixed(2);
  var badge = document.getElementById('cc-change');
  badge.style.display='inline-block';
  badge.className = 'cc-rate-change '+(chg>=0?'up':'down');
  badge.textContent = (chg>=0?'▲+':'▼')+chg+'%';
};

window.swapCC = function(){
  var f = document.getElementById('cc-from');
  var t = document.getElementById('cc-to');
  var fv = f.value, tv = t.value;
  /* swap selections */
  for(var i=0;i<f.options.length;i++) if(f.options[i].value===tv) f.selectedIndex=i;
  for(var i=0;i<t.options.length;i++) if(t.options[i].value===fv) t.selectedIndex=i;
  calcCC();
};

/* ═══════════════════════════════════════
   SHARE ENGINE — CANVAS CARD GENERATOR
═══════════════════════════════════════ */
var esFormat    = 'square';
var esRendering = false;

var ES_FORMATS = {
  square: { w:1080, h:1080 },
  story:  { w:1080, h:1920 },
  wide:   { w:1200, h:675  },
};

/* ── Open/close modal ── */
window.ecalOpenShare = function(){
  var modal = document.getElementById('ecal-share-modal');
  modal.classList.remove('hidden');
  document.body.style.overflow = 'hidden';
  /* update subtitle */
  var sub = document.getElementById('esm-subtitle');
  if(sub) sub.textContent = calDayFilter + (calImpact!=='all' ? ' · '+calImpact.charAt(0).toUpperCase()+calImpact.slice(1)+' Impact' : '');
  /* show native share if supported */
  var nb = document.getElementById('esm-native-btn');
  if(nb) nb.style.display = (navigator.share && navigator.canShare) ? 'flex' : 'none';
  /* update share links */
  esUpdateLinks();
  /* render canvas */
  esRender();
};

window.ecalCloseShare = function(){
  document.getElementById('ecal-share-modal').classList.add('hidden');
  document.body.style.overflow = '';
};

/* close on Escape */
document.addEventListener('keydown', function(e){
  if(e.key==='Escape') ecalCloseShare();
});

/* ── Format switch ── */
window.esSetFormat = function(btn, fmt){
  document.querySelectorAll('.esm-fmt').forEach(function(b){b.classList.remove('active')});
  btn.classList.add('active');
  esFormat = fmt;
  esRender();
};

/* ── Get current filtered events for the card ── */
function esGetEvents(){
  var dayEvents = CAL_DATA.filter(function(e){ return e.day === calDayFilter; });
  var filtered  = calImpact === 'all' ? dayEvents : dayEvents.filter(function(e){ return e.impact === calImpact; });
  return filtered.slice(0, 12); /* cap at 12 rows on card */
}

/* ── Actual STB logo as embedded data URI ── */
var STB_LOGO_SRC = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAABcCAYAAADu8aIfAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAVtSURBVHgB7Z2Ncds4EIVXmRTgEuAKzqnAdAXnDsSr4JwKpFRwvgqkVBCnAioVWKkA6iDp4AVrUpYs80cEdkGJwjcDc8bSEOTTIwguFuCEhAFw5TaZK7euGFduqo8MXS6rjyRAJe7UlXsqRU4cECS0E9i4zYxKga8o0YiX0JWD5678S4mj6C20EzlzmwVddpvbmw99vuxEfnCbgpLIfbk6Wmgn8txt/qOED8cJXYk8o4Q3nUInkWVoFdqJnFMSWYRGoff6yAkB2hzNIhtKiFArdNVk5JQQY1L3Tye0peRmUd45unKzoYQo7xyd3KzDG6GrnsaUTps5ybOqSoLhgBZ0MJTY4QQpIM+CEjug5+ZbSuyAjpsLSuzACNz80VXGj9p5w+cbamf/89VkMvlKOmj0hPh4f1AsIHdJ/k0KuP0a6BC1G8tPhlKj11ru0IggbhSvvlqkhF67A/9NwqDs3+Ykz5wiw0IbCmdDOozCzUyvUfAWkps7kBJag9G4mZES+oYEGZubGRZ6Q+FwF0wy925UbmZYaIn2lUUWcbWimx9pQKQczUi5UMXNrnynAZEUmuMRGQWg6OalazY2NCAs9E+SY4GwILpWHslgbfMrfBODLNZHbOjFNE4isP+henRekxzGlQL9gzY56fDl8B/Vj8olq4pBjOEsV8kMOlh2lCv3aOn+VSdqIc+ioa42nl355soU0uK7Hd5AF9tR/xw6mJq6FuhHAcmQKnSGirZMW+o9JTe3YSEhOPSGi7rcnEMHU1PXAuFYhDYp0HH1tKNOC3ma3PwLcszJF8i72qLl10dcN2vcB57h626Ud1wpZh11WchT1NSjdR8AfJsSlA8wFjKYlnq03Hwbsa4tFp5iSzQhi446LOQpItZ1iIWn2DOEYVr2reWwacS66rDwicvDX+wh3Gwj1tXGN/IBfmKblv2N1c37PJAP6Cf2Jbt5C/fX/Yb2cLzYpmUfl+DmLf7hWZTBJ+u7c1yGm/cx2+PplW7gYtcct75zZdnwlWWLyDnpTEKaR6yrL+ELx6C8NO3er1d0fP8Z8pyym5nXtnpCgWA3MT9vyjdGOWirkV2fH+ZqwG8Ou6EyXUJjXagHd4z/kwToeCKCTlTQQngEBO+vUgniTN+AXpxbbeUFyA7t+Xf1eh50AXn44A0pAlmxM9Vs0kqMjOR50k6Icfvn0fMVyfCXdtqu1uX9heLwD8kgmm37BowkIQYyTd+zpqPP3c1bJNLJdG6GGFF6l9C5/Ap+YGk4OBYkJ3muh8gKZaUoEPGmAyNOvQ1Bo40eS9ssiqjQim5eDeVmd04SXbONtKO13Dyn4TgtoZXdHG8VgvdILCbwW9LRWm4ebDZVZZ57Cmct0r2rDsiSPDw38JoGAmWIM6NwxIJKo2ubUWaLZiRD+IQs6CUQalwhx5wP5x4+Qo6XwL/Ee1hyijToqgl275Lh5BdDcjzxn6A2GmXbrPFyhca2GWXKlXSQRmyKdQ0vYYNQR+cU0c0oB4IlegGxeH3QCnW0xoKxbW4+twVqX0fpvXsdiJgQo1yfFm+WrfB2tJabXflUtxDWObuZ8XK0oruWDSLndF4iPx0m9ng5WtHNd3VRujNzMxvl0+F59Ha0ortWDSLndF5untedR29HK7rregRufnTn8Lnug75vf8tJr23eRKxPg3WTyEwvRw/gZqnomTYveeNty4b2ec1eTnHdnNFIRGaOdnRycy1LVz5PpBbAhd7Em0VDfRlOG85mlX/fLvSmKpiG+hY4XQpopAyjXA9JgyY3a6WThVIg4J0Ax4RJtV5JvWz4v1omvwfc9vLgcPBIfOvNEHqTfPjA72rqM6QzyHsMGyqFXVflRzXdT4Q/UUKz1vpkI+oAAAAASUVORK5CYII=';
var STB_LOGO_IMG = null;

function esLoadLogo(cb){
  if(STB_LOGO_IMG){ cb(STB_LOGO_IMG); return; }
  var img = new Image();
  img.onload  = function(){ STB_LOGO_IMG = img; cb(img); };
  img.onerror = function(){ cb(null); };
  img.src = STB_LOGO_SRC;
}

function esRenderNow(ctx, W, H, events, img){
  /* ── Background ── */
  ctx.fillStyle = '#080b12';
  ctx.fillRect(0, 0, W, H);

  /* subtle dot-grid */
  ctx.fillStyle = 'rgba(255,255,255,0.04)';
  var gs = Math.round(W/30);
  for(var gx=gs; gx<W; gx+=gs)
    for(var gy=gs; gy<H; gy+=gs){
      ctx.beginPath(); ctx.arc(gx,gy,1,0,Math.PI*2); ctx.fill();
    }

  /* radial glow top-left */
  var rg = ctx.createRadialGradient(0,0,0,0,0,W*0.6);
  rg.addColorStop(0,   'rgba(200,16,46,0.15)');
  rg.addColorStop(1,   'rgba(0,0,0,0)');
  ctx.fillStyle = rg;
  ctx.fillRect(0,0,W,H);

  /* top accent line */
  var lineGrd = ctx.createLinearGradient(0,0,W,0);
  lineGrd.addColorStop(0,   'rgba(200,16,46,0)');
  lineGrd.addColorStop(0.25,'rgba(200,16,46,1)');
  lineGrd.addColorStop(0.75,'rgba(200,16,46,1)');
  lineGrd.addColorStop(1,   'rgba(200,16,46,0)');
  ctx.fillStyle = lineGrd;
  ctx.fillRect(0, 0, W, 5);

  var scale  = W / 1080;
  var pad    = Math.round(72 * scale);   /* increased from 56 — ensures nothing clips */
  var yHead  = Math.round(80 * scale);

  /* ── STB actual logo image ── */
  var logoH    = Math.round(56 * scale);   /* height to draw at */
  var logoW    = img ? Math.round(img.naturalWidth * (logoH / img.naturalHeight)) : Math.round(56*scale);
  if(img){
    ctx.drawImage(img, pad, yHead, logoW, logoH);
  } else {
    /* fallback: white text if image failed */
    ctx.font      = 'bold '+Math.round(40*scale)+'px Arial';
    ctx.fillStyle = '#fff';
    ctx.textBaseline = 'top';
    ctx.fillText('STB', pad, yHead);
  }

  /* "PROVIDER" tagline under logo */
  ctx.font         = 'bold '+Math.round(11*scale)+'px Arial';
  ctx.fillStyle    = 'rgba(255,255,255,0.28)';
  ctx.textBaseline = 'top';
  ctx.textAlign    = 'left';
  ctx.letterSpacing = '0.14em';
  ctx.fillText('PROVIDER', pad, yHead + logoH + Math.round(6*scale));

  /* ── Right block: title + day + impact ── */
  var rtX = W - pad;

  ctx.textAlign    = 'right';
  ctx.textBaseline = 'top';

  /* "ECONOMIC CALENDAR" */
  ctx.font      = 'bold '+Math.round(15*scale)+'px Arial';
  ctx.fillStyle = 'rgba(255,255,255,0.4)';
  ctx.letterSpacing = '0.12em';
  ctx.fillText('ECONOMIC CALENDAR', rtX, yHead);

  /* day name — large */
  var dayShort = calDayFilter
    ? calDayFilter.split(',')[0].toUpperCase()
    : 'THIS WEEK';
  ctx.font      = 'bold '+Math.round(54*scale)+'px Arial';
  ctx.fillStyle = '#fff';
  ctx.fillText(dayShort, rtX, yHead + Math.round(18*scale));

  /* impact pill */
  var impactLabel = calImpact==='all'?'ALL EVENTS':calImpact.toUpperCase()+' IMPACT';
  var impactColor = calImpact==='high'?'#C8102E':calImpact==='medium'?'#e07814':'rgba(255,255,255,0.5)';
  /* pill background */
  ctx.font = 'bold '+Math.round(12*scale)+'px Arial';
  var pillW = ctx.measureText(impactLabel).width + Math.round(24*scale);
  var pillH = Math.round(22*scale);
  var pillY = yHead + Math.round(76*scale);
  var pillX = rtX - pillW;
  ctx.beginPath();
  ctx.roundRect(pillX, pillY, pillW, pillH, Math.round(4*scale));
  ctx.fillStyle = calImpact==='high'?'rgba(200,16,46,0.2)':calImpact==='medium'?'rgba(224,120,20,0.15)':'rgba(255,255,255,0.06)';
  ctx.fill();
  ctx.fillStyle   = impactColor;
  ctx.textAlign   = 'right';
  ctx.textBaseline = 'middle';
  ctx.fillText(impactLabel, rtX - Math.round(12*scale), pillY + pillH/2);

  ctx.textAlign    = 'left';
  ctx.textBaseline = 'alphabetic';

  /* ── Divider ── */
  var divY = yHead + logoH + Math.round(50*scale);
  var divGrd = ctx.createLinearGradient(pad, 0, W-pad, 0);
  divGrd.addColorStop(0,   'rgba(200,16,46,0.6)');
  divGrd.addColorStop(0.5, 'rgba(255,255,255,0.12)');
  divGrd.addColorStop(1,   'rgba(255,255,255,0.04)');
  ctx.strokeStyle = divGrd;
  ctx.lineWidth   = 1;
  ctx.beginPath(); ctx.moveTo(pad, divY); ctx.lineTo(W-pad, divY); ctx.stroke();

  /* ── Column headers ── */
  var hdrY    = divY + Math.round(30*scale);
  var colTime = pad + Math.round(18*scale);  /* extra indent for dot */
  var colFlag = pad + Math.round(120*scale);
  var colEvt  = pad + Math.round(178*scale);
  var colPrev = W  - Math.round(330*scale);
  var colFore = W  - Math.round(210*scale);
  var colAct  = W  - pad;

  ctx.font      = 'bold '+Math.round(11*scale)+'px Arial';
  ctx.fillStyle = 'rgba(255,255,255,0.22)';
  ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
  ctx.fillText('TIME',     colTime, hdrY);
  ctx.fillText('CCY',      colFlag, hdrY);
  ctx.fillText('EVENT',    colEvt,  hdrY);
  ctx.textAlign = 'right';
  ctx.fillText('PREV',     colPrev, hdrY);
  ctx.fillText('FORECAST', colFore, hdrY);
  ctx.fillText('ACTUAL',   colAct,  hdrY);
  ctx.textAlign = 'left';

  /* header underline */
  var hdlY = hdrY + Math.round(10*scale);
  ctx.strokeStyle = 'rgba(255,255,255,0.06)';
  ctx.lineWidth   = 1;
  ctx.beginPath(); ctx.moveTo(pad, hdlY); ctx.lineTo(W-pad, hdlY); ctx.stroke();

  /* ── Event rows ── */
  var rowH    = Math.round(60*scale);
  var startY  = hdlY + Math.round(8*scale);
  var maxRows = Math.floor((H - startY - Math.round(100*scale)) / rowH);
  var rows    = events.slice(0, maxRows);

  rows.forEach(function(e, i){
    var ry  = startY + i * rowH;
    var mid = ry + rowH/2;

    /* alt row bg */
    if(i%2===0){
      ctx.fillStyle = 'rgba(255,255,255,0.02)';
      ctx.fillRect(pad, ry, W-pad*2, rowH);
    }

    /* impact dot */
    var dotCol = e.impact==='high'?'#C8102E':e.impact==='medium'?'#e07814':'rgba(255,255,255,0.18)';
    ctx.shadowColor = e.impact!=='low'?dotCol:'transparent';
    ctx.shadowBlur  = e.impact==='high'?10:5;
    ctx.fillStyle   = dotCol;
    ctx.beginPath();
    ctx.arc(pad + Math.round(6*scale), mid, Math.round(5*scale), 0, Math.PI*2);
    ctx.fill();
    ctx.shadowBlur = 0; ctx.shadowColor = 'transparent';

    /* time */
    ctx.font      = Math.round(13*scale)+'px "Courier New",monospace';
    ctx.fillStyle = 'rgba(255,255,255,0.38)';
    ctx.textAlign = 'left';
    ctx.fillText(e.time||'—', colTime, mid + Math.round(5*scale));

    /* flag */
    ctx.font = Math.round(19*scale)+'px Arial';
    ctx.fillText(e.flag||'', colFlag, mid + Math.round(7*scale));

    /* ccy */
    ctx.font      = 'bold '+Math.round(12*scale)+'px Arial';
    ctx.fillStyle = 'rgba(255,255,255,0.42)';
    ctx.fillText(e.ccy||'', colFlag + Math.round(26*scale), mid + Math.round(5*scale));

    /* event title */
    ctx.font      = 'bold '+Math.round(15*scale)+'px Arial';
    ctx.fillStyle = 'rgba(255,255,255,0.9)';
    var maxW  = colPrev - colEvt - Math.round(20*scale);
    var title = e.event||'';
    while(title.length>3 && ctx.measureText(title).width > maxW) title = title.slice(0,-1);
    if(title !== e.event) title = title.trim()+'…';
    ctx.fillText(title, colEvt, mid + Math.round(5*scale));

    /* prev */
    ctx.textAlign = 'right';
    ctx.font      = Math.round(13*scale)+'px Arial';
    ctx.fillStyle = 'rgba(255,255,255,0.28)';
    ctx.fillText(e.previous||'—', colPrev, mid + Math.round(5*scale));

    /* forecast */
    ctx.fillStyle = 'rgba(255,255,255,0.45)';
    ctx.fillText(e.forecast||'—', colFore, mid + Math.round(5*scale));

    /* actual */
    if(e.actual){
      ctx.fillStyle = e.dir==='up'?'#14e0a3':e.dir==='down'?'#C8102E':'rgba(255,255,255,0.8)';
      ctx.font      = 'bold '+Math.round(15*scale)+'px Arial';
      var pfx = e.dir==='up'?'▲ ':e.dir==='down'?'▼ ':'';
      ctx.fillText(pfx+e.actual, colAct, mid + Math.round(5*scale));
    } else {
      ctx.fillStyle = 'rgba(255,255,255,0.15)';
      ctx.font      = Math.round(12*scale)+'px Arial';
      ctx.fillText('—', colAct, mid + Math.round(5*scale));
    }
    ctx.textAlign = 'left';

    /* row separator */
    ctx.strokeStyle = 'rgba(255,255,255,0.035)';
    ctx.lineWidth   = 1;
    ctx.beginPath(); ctx.moveTo(pad, ry+rowH); ctx.lineTo(W-pad, ry+rowH); ctx.stroke();
  });

  /* overflow */
  if(events.length > rows.length){
    var moreY = startY + rows.length * rowH + Math.round(22*scale);
    ctx.font      = Math.round(13*scale)+'px Arial';
    ctx.fillStyle = 'rgba(255,255,255,0.22)';
    ctx.textAlign = 'center';
    ctx.fillText('+ '+(events.length-rows.length)+' more events', W/2, moreY);
    ctx.textAlign = 'left';
  }

  /* ── Bottom bar ── */
  var barY = H - Math.round(56*scale);
  ctx.strokeStyle = lineGrd;
  ctx.lineWidth   = 1;
  ctx.beginPath(); ctx.moveTo(pad, barY); ctx.lineTo(W-pad, barY); ctx.stroke();

  /* URL */
  ctx.font         = 'bold '+Math.round(15*scale)+'px Arial';
  ctx.fillStyle    = '#C8102E';
  ctx.textBaseline = 'middle';
  ctx.fillText('stbbrokers.com/tools', pad, barY + Math.round(28*scale));

  /* source right */
  ctx.textAlign    = 'right';
  ctx.font         = Math.round(12*scale)+'px Arial';
  ctx.fillStyle    = 'rgba(255,255,255,0.18)';
  ctx.fillText('Live data · Investing.com', W-pad, barY + Math.round(28*scale));

  /* bottom accent line */
  ctx.fillStyle = lineGrd;
  ctx.fillRect(0, H-5, W, 5);
}

/* ── Main render entry point — waits for fonts + logo ── */
function esRender(){
  if(esRendering) return;
  esRendering = true;
  var canvas = document.getElementById('esm-canvas');
  var fmt    = ES_FORMATS[esFormat];
  canvas.width  = fmt.w;
  canvas.height = fmt.h;
  var ctx    = canvas.getContext('2d');
  var events = esGetEvents();

  var doRender = function(img){
    esRenderNow(ctx, fmt.w, fmt.h, events, img);
    esRendering = false;
  };

  /* load logo image then wait for fonts */
  esLoadLogo(function(img){
    if(document.fonts && document.fonts.ready){
      document.fonts.ready.then(function(){ doRender(img); });
    } else {
      doRender(img);
    }
  });
}
window.esDownload = function(){
  var canvas = document.getElementById('esm-canvas');
  var link   = document.createElement('a');
  var day    = calDayFilter ? calDayFilter.split(',')[0].replace(/\s/g,'_') : 'calendar';
  link.download = 'STB_EconCalendar_'+day+'_'+esFormat+'.png';
  link.href      = canvas.toDataURL('image/png');
  link.click();
};

/* ── Native share (mobile) ── */
window.esNativeShare = function(){
  var canvas = document.getElementById('esm-canvas');
  canvas.toBlob(function(blob){
    var file = new File([blob], 'STB_EconCalendar.png', {type:'image/png'});
    var shareData = {
      title: 'STB Economic Calendar',
      text:  'Economic Calendar — '+calDayFilter+'\nstbbrokers.com/tools',
      files: [file],
    };
    if(navigator.canShare && navigator.canShare(shareData)){
      navigator.share(shareData).catch(function(){});
    } else {
      esDownload();
    }
  }, 'image/png');
};

/* ── Platform links ── */
function esUpdateLinks(){
  var pageUrl  = 'https://stbbrokers.com/tools/';
  var dayLabel = calDayFilter ? calDayFilter.split(',')[0] : 'This Week';
  var impact   = calImpact==='all'?'all events':calImpact+' impact';
  var text     = 'STB Economic Calendar — '+dayLabel+' ('+impact+') 📊\nLive data at: ';

  var tw = document.getElementById('esm-tw-btn');
  if(tw) tw.href = 'https://twitter.com/intent/tweet?text='+encodeURIComponent(text+pageUrl);

  var tg = document.getElementById('esm-tg-btn');
  if(tg) tg.href = 'https://t.me/share/url?url='+encodeURIComponent(pageUrl)+'&text='+encodeURIComponent(text);

  var wa = document.getElementById('esm-wa-btn');
  if(wa) wa.href = 'https://wa.me/?text='+encodeURIComponent(text+pageUrl);
}

/* ── Copy link ── */
window.esCopyLink = function(){
  var url   = 'https://stbbrokers.com/tools/';
  var label = document.getElementById('esm-copy-label');
  navigator.clipboard.writeText(url).then(function(){
    if(label){ label.textContent = FA?'کپی شد! ✓':'Copied! ✓'; }
    setTimeout(function(){ if(label) label.textContent = FA?'کپی لینک':'Copy Link'; }, 2000);
  }).catch(function(){
    if(label){ label.textContent = FA?'کپی دستی':'Copy manually'; }
  });
};

/* show share button once data is loaded */
function esShowShareBtn(){
  var btn = document.getElementById('ecal-share-btn');
  if(btn) btn.style.display = 'inline-flex';
}
calcPip();
calcMargin();
buildSentiment();
calcCC();

/* live CC refresh */
setInterval(function(){calcCC();}, 30000);

})();
</script>

</article>
