/**
 * STB Live Prices Client v2
 * Source: /wp-json/stb/v1/prices (mu-plugin stb-live-prices.php v2)
 *
 * Updates:
 *   1. Header ticker (.stb-ticker-track / #stb-ticker)
 *   2. Hero featured panel + 4 rows
 *   3. MT-style platform preview rows
 *   4. Tools page calculators (Pip / Margin / Currency Converter)
 *      — exposes window.stbPrices.get(code) and 'stb:pricesUpdated' event
 */
(function () {
  'use strict';

  var API = (window.stbPricesConfig && window.stbPricesConfig.apiUrl)
    ? window.stbPricesConfig.apiUrl
    : '/NewSite/wp-json/stb/v1/prices';
  var REFRESH = 30000; // poll every 30s
  var cache   = {};    // code → row

  // ── Fetch ──────────────────────────────────────────────────────────────
  function fetchPrices() {
    fetch(API, { credentials: 'same-origin' })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (!data || !data.ok || !data.prices) return;
        data.prices.forEach(function (p) { cache[p.code] = p; });
        window.stbPrices = {
          get: function (code) { return cache[code]; },
          all: function () { return Object.values(cache); },
          updatedAt: data.updated_at || 0,
          stale: !!data.stale
        };
        updateAll();
        document.dispatchEvent(new CustomEvent('stb:pricesUpdated', { detail: cache }));
      })
      .catch(function (e) { console.warn('STB prices:', e); });
  }

  // ── Helpers ────────────────────────────────────────────────────────────
  function dirArrow(d) { return d === 'up' ? '\u25B2' : '\u25BC'; }
  function dirClass(d) { return d === 'up' ? 'up' : 'dn'; }

  var ICON_OVERRIDE = {
    EURUSD: '\u20AC$', GBPUSD: '\u00A3$', USDJPY: '$\u00A5', USDCHF: '$\u20A3',
    AUDUSD: 'A$',      USDCAD: '$C',
    XAUUSD: 'Au',      XAGUSD: 'Ag',
    BTCUSD: '\u20BF',  ETHUSD: '\u039E',
    NAS100: 'NQ',      SPX500: 'SP', US30: 'DJ', DAX40: 'DE', USOIL: 'WT'
  };

  function iconFor(p) {
    return ICON_OVERRIDE[p.code] || (p.display || p.code).substring(0, 2).toUpperCase();
  }

  function colorFor(p) {
    var palette = {
      FOREX:     '#14e0a3',
      COMMODITY: '#14e0a3',
      INDEX:     '#C8102E',
      CRYPTO:    '#C8102E'
    };
    return palette[p.type] || '#ffffff';
  }

  // ── Ticker ────────────────────────────────────────────────────────────
  function buildTicker() {
    var track = document.getElementById('stb-ticker');
    if (!track) return;
    var items = Object.values(cache);
    if (!items.length) return;

    var order = ['EURUSD','XAUUSD','BTCUSD','NAS100','SPX500','US30','GBPUSD','ETHUSD','USDJPY','XAGUSD','DAX40','AUDUSD','USOIL','USDCHF','USDCAD'];
    var sorted = order.map(function (c) { return cache[c]; }).filter(Boolean);
    var rest   = items.filter(function (p) { return order.indexOf(p.code) === -1; });
    var list   = sorted.concat(rest);

    var html = '';
    [list, list].forEach(function (batch) {
      batch.forEach(function (p) {
        var col = colorFor(p);
        var icon = iconFor(p);
        html +=
          '<div class="stb-ticker-item" data-code="' + p.code + '">' +
            '<div class="stb-ticker-icon" style="background:' + col + '22;color:' + col + '">' + icon + '</div>' +
            '<span class="stb-ticker-name">' + p.name + '</span>' +
            '<span class="stb-ticker-price">' + p.price_fmt + '</span>' +
            '<span class="stb-ticker-change ' + dirClass(p.direction) + '">' + dirArrow(p.direction) + ' ' + p.change_str + '</span>' +
          '</div>';
      });
    });
    track.innerHTML = html;
  }

  // ── Hero featured panel + rows ─────────────────────────────────────────
  // The Broker slide on homepage hero (template-parts/sections/hero.php) uses
  // .broker-price-row with elements:
  //   .broker-pair  (e.g. "EUR/USD")
  //   .broker-price id="hp-<code-lowercased>" (e.g. id="hp-eurusd")
  //   .broker-chg.up / .broker-chg.dn
  // We also still support older .stb-panel-row markup if it appears anywhere.
  function updateHeroPanel() {
    var eur = cache.EURUSD;
    if (eur) {
      var fP = document.querySelector('.stb-panel-featured-price');
      var fC = document.querySelector('.stb-panel-featured-change');
      if (fP) fP.textContent = eur.price_fmt;
      if (fC) {
        fC.textContent = dirArrow(eur.direction) + ' ' + eur.change_str + ' today';
        fC.className   = 'stb-panel-featured-change ' + dirClass(eur.direction);
      }
    }

    // Broker slide hero rows — find each .broker-price-row by its id="hp-<code>"
    // Map UI pair → feed code
    var pairToCode = {
      'EUR/USD':'EURUSD', 'GBP/USD':'GBPUSD', 'USD/JPY':'USDJPY',
      'USD/CHF':'USDCHF', 'AUD/USD':'AUDUSD', 'USD/CAD':'USDCAD',
      'XAU/USD':'XAUUSD', 'XAG/USD':'XAGUSD',
      'BTC/USD':'BTCUSD', 'ETH/USD':'ETHUSD',
      'NAS100':'NAS100',  'SPX500':'SPX500',  'US30':'US30',
      'DAX40':'DAX40',    'US Oil':'USOIL'
    };
    document.querySelectorAll('.broker-price-row').forEach(function (row) {
      var pairEl  = row.querySelector('.broker-pair');
      if (!pairEl) return;
      var code = pairToCode[pairEl.textContent.trim()];
      var p    = code ? cache[code] : null;
      if (!p) return;
      var priceEl  = row.querySelector('.broker-price');
      var changeEl = row.querySelector('.broker-chg');
      if (priceEl)  priceEl.textContent  = p.price_fmt;
      if (changeEl) {
        changeEl.textContent = dirArrow(p.direction) + ' ' + p.change_str;
        changeEl.className   = 'broker-chg ' + dirClass(p.direction);
      }
    });

    // Legacy .stb-panel-row support (kept for any older partial that still uses it)
    var rowCodes = ['GBPUSD','XAUUSD','BTCUSD','NAS100'];
    var rows = document.querySelectorAll('.stb-panel-row');
    rows.forEach(function (row, i) {
      var p = cache[rowCodes[i]];
      if (!p) return;
      var priceEl  = row.querySelector('.stb-panel-row-price');
      var changeEl = row.querySelector('.stb-panel-row-change');
      if (priceEl)  priceEl.textContent  = p.price_fmt;
      if (changeEl) {
        changeEl.textContent = dirArrow(p.direction) + ' ' + p.change_str;
        changeEl.className   = 'stb-panel-row-change ' + dirClass(p.direction);
      }
    });
  }

  // ── MT-style platform rows ─────────────────────────────────────────────
  function updatePlatformRows() {
    var platCodes = ['EURUSD','XAUUSD','NAS100','GBPUSD'];
    var rows = document.querySelectorAll('.stb-mt-row');
    rows.forEach(function (row, i) {
      var p = cache[platCodes[i]];
      if (!p) return;
      var priceEl = row.querySelector('.stb-mt-price');
      if (priceEl) {
        priceEl.textContent = p.price_fmt;
        priceEl.className   = 'stb-mt-price ' + (p.direction === 'up' ? 'stb-green' : 'stb-red');
      }
    });
  }

  // ── Update all ─────────────────────────────────────────────────────────
  function updateAll() {
    buildTicker();
    updateHeroPanel();
    updatePlatformRows();
  }

  // ── Boot ───────────────────────────────────────────────────────────────
  function start() {
    fetchPrices();
    setInterval(fetchPrices, REFRESH);
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', start);
  } else {
    start();
  }
})();
