(function () {

  function formatNumber(n) {
    return Number(n).toFixed(2);
  }

  function currencySymbol(code) {
    var map = { USD: '$', EUR: '€', GBP: '£', JPY: '¥', INR: '₹', AUD: 'A$', CAD: 'C$', CHF: 'Fr', CNY: '¥', AED: 'د.إ' };
    return map[code] || '';
  }

  function metalCode(m) {
    var map = { gold: 'XAU', silver: 'XAG', platinum: 'XPT', palladium: 'XPD' };
    return map[m] || null;
  }

  function getUsdPerOzFromRates(rates, code) {
    if (!rates || !code) return null;
    var usdKey = 'USD' + code;
    if (rates[usdKey]) return Number(rates[usdKey]);
    if (rates[code]) {
      var direct = Number(rates[code]);
      if (direct > 0) return direct;
    }
    return null;
  }

  function convertUsdToCurrency(usd, currency, base, rates) {
    if (currency === 'USD') return usd;
    if (base === 'USD' && rates && rates[currency]) return usd * Number(rates[currency]);
    if (currency === base) return usd;
    if (base !== 'USD' && rates && rates[currency] && rates[base] && Number(rates[base]) > 0) {
      return (usd / Number(rates[base])) * Number(rates[currency]);
    }
    return usd;
  }

  // ✅ ratesByDate માંથી series બનાવો
  function parseSeriesFromRatesByDate(ratesByDate, metal, rangeDays) {
    var code = metalCode(metal);
    if (!code || !ratesByDate) return [];

    var now = Date.now();
    var cutoff = now - rangeDays * 24 * 60 * 60 * 1000;
    var points = [];

    Object.keys(ratesByDate).forEach(function (dateStr) {
      var t = new Date(dateStr).getTime();
      if (!t || t < cutoff) return;
      var dayRates = ratesByDate[dateStr];
      var usdPerOz = getUsdPerOzFromRates(dayRates, code);
      if (usdPerOz !== null) {
        points.push({ t: t, v: usdPerOz, dateStr: dateStr });
      }
    });

    points.sort(function (a, b) { return a.t - b.t; });
    return points;
  }

  // ✅ Chart.js instance store
  var chartInstances = {};

  function drawChartJS(canvas, series, currency, base, rates, metal) {
    if (!canvas || !window.Chart) return;

    var canvasId = canvas.id || (canvas.id = 'pmrcgold-canvas-' + Math.random().toString(36).substr(2, 8));

    // Destroy existing chart
    if (chartInstances[canvasId]) {
      chartInstances[canvasId].destroy();
      delete chartInstances[canvasId];
    }

    if (!series || series.length === 0) return;

    var labels = series.map(function (p) { return p.dateStr; });
    var values = series.map(function (p) {
      return parseFloat(convertUsdToCurrency(p.v, currency, base, rates).toFixed(2));
    });

    var sym = currencySymbol(currency);

    chartInstances[canvasId] = new Chart(canvas, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: metal.charAt(0).toUpperCase() + metal.slice(1) + ' (' + currency + ')',
          data: values,
          borderColor: '#2f5d7c',
          backgroundColor: 'rgba(47, 93, 124, 0.1)',
          borderWidth: 2,
          pointRadius: series.length <= 5 ? 4 : 2,
          pointHoverRadius: 6,
          fill: true,
          tension: 0.3,
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: { display: false },
          tooltip: {
            callbacks: {
              label: function (ctx) {
                return sym + formatNumber(ctx.parsed.y);
              }
            }
          }
        },
        scales: {
          x: {
            ticks: {
              maxTicksLimit: 5,
              font: { size: 11 }
            },
            grid: { display: false }
          },
          y: {
            ticks: {
              callback: function (val) { return sym + formatNumber(val); },
              font: { size: 11 }
            },
            grid: { color: 'rgba(0,0,0,0.05)' }
          }
        }
      }
    });
  }

  function updateRow(root, row, state) {
    var metal = row.getAttribute('data-metal');
    var code = metalCode(metal);
    if (!code) return;

    var usdPerOz = getUsdPerOzFromRates(state.latestRates, code);
    if (usdPerOz === null) return;

    var price = convertUsdToCurrency(usdPerOz, state.currency, state.base, state.latestRates);
    var sym = currencySymbol(state.currency);

    var priceEl = row.querySelector('.pmrcgold-widget3__price');
    if (priceEl) priceEl.textContent = sym + formatNumber(price);

    var changeEl = row.querySelector('.pmrcgold-widget3__change');
    if (changeEl) {
      var series = parseSeriesFromRatesByDate(state.ratesByDate, metal, state.rangeDays);
      var changePct = 0;
      if (series.length >= 2) {
        var first = convertUsdToCurrency(series[0].v, state.currency, state.base, state.latestRates);
        var last = convertUsdToCurrency(series[series.length - 1].v, state.currency, state.base, state.latestRates);
        if (first > 0) changePct = ((last - first) / first) * 100;
      }
      changeEl.classList.remove('up', 'down');
      changeEl.classList.add(changePct >= 0 ? 'up' : 'down');
      var valEl = changeEl.querySelector('.pmrcgold-widget3__change-val');
      if (valEl) valEl.textContent = (changePct >= 0 ? '+' : '') + formatNumber(changePct) + '%';
    }

    if (row.classList.contains('is-open')) {
      var canvas = row.querySelector('canvas');
      if (canvas) {
        var chartSeries = parseSeriesFromRatesByDate(state.ratesByDate, metal, state.rangeDays);
        drawChartJS(canvas, chartSeries, state.currency, state.base, state.latestRates, metal);
      }
    }
  }

  function initWidget(root) {
    var data = window.pmrcgold_widget3_data && window.pmrcgold_widget3_data[root.id];
    if (!data) return;

    var state = {
      base: data.base || 'USD',
      latestRates: data.latest_rates || {},
      ratesByDate: data.rates_by_date || {},  // ✅
      currency: data.currencies && data.currencies[0] ? data.currencies[0] : (data.base || 'USD'),
      rangeDays: 1
    };

    var currencySelect = root.querySelector('.pmrcgold-widget3__currency select');
    if (currencySelect) {
      currencySelect.value = state.currency;
      currencySelect.addEventListener('change', function () {
        state.currency = currencySelect.value;
        refresh();
      });
    }

    root.querySelectorAll('.pmrcgold-widget3__range-btn').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var d = Number(btn.getAttribute('data-days'));
        state.rangeDays = d;
        root.querySelectorAll('.pmrcgold-widget3__range-btn').forEach(function (b) {
          b.classList.toggle('active', b === btn);
        });
        refresh();
      });
    });

    root.querySelectorAll('.pmrcgold-widget3__row-btn').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var row = btn.closest('.pmrcgold-widget3__row');
        if (!row) return;

        var isOpen = row.classList.contains('is-open');

        // બધા બંધ
        root.querySelectorAll('.pmrcgold-widget3__row').forEach(function (r) {
          r.classList.remove('is-open');
        });

        // Toggle
        if (!isOpen) {
          row.classList.add('is-open');
          refresh();
        }
      });
    });

    function refresh() {
      root.querySelectorAll('.pmrcgold-widget3__row').forEach(function (row) {
        updateRow(root, row, state);
      });
    }

    // Default: 1 day active
    var defaultBtn = root.querySelector('.pmrcgold-widget3__range-btn[data-days="1"]');
    if (defaultBtn) defaultBtn.classList.add('active');

    // First row open
    var firstRow = root.querySelector('.pmrcgold-widget3__row');
    if (firstRow) firstRow.classList.add('is-open');

    refresh();
  }

  window.pmrcgold_init_widget3 = function () {
    document.querySelectorAll('.pmrcgold-widget3').forEach(function (root) {
      if (!root.hasAttribute('data-initialized')) {
        initWidget(root);
        root.setAttribute('data-initialized', 'true');
      }
    });
  };

  function initWidget3AfterLoad() {
    document.querySelectorAll('.pmrcgold-widget3').forEach(function (root) {
      if (!root.hasAttribute('data-initialized')) {
        initWidget(root);
        root.setAttribute('data-initialized', 'true');
      }
    });
  }

  var checkCount = 0;
  var checkInterval = setInterval(function () {
    initWidget3AfterLoad();
    checkCount++;
    if (checkCount >= 10) clearInterval(checkInterval);
  }, 500);

})();