(function() {
  const track = document.getElementById('popupTickerTrack');
  let initialised = false;

  function fmtPrice(p) {
    if (p == null) return '$—';
    return p >= 1000 ? '$' + p.toLocaleString('en-US', {maximumFractionDigits: 2})
         : p >= 1    ? '$' + p.toFixed(2)
         :              '$' + p.toFixed(6);
  }

  function fmtChange(chg) {
    if (chg == null) return '0.00%';
    return (chg >= 0 ? '+' : '') + chg.toFixed(2) + '%';
  }

  function buildItems(coins) {
    const frag = document.createDocumentFragment();
    for (let pass = 0; pass < 2; pass++) {
      coins.forEach(coin => {
        const item = document.createElement('span');
        item.className = 'pt-item';
        item.dataset.id = coin.id;

        const img = document.createElement('img');
        img.src = coin.image || '';
        img.alt = '';
        img.width = 12; img.height = 12;
        img.onerror = () => { img.style.display = 'none'; };

        const sym = document.createElement('span');
        sym.className = 'pt-sym';
        sym.textContent = coin.symbol.toUpperCase();

        const price = document.createElement('span');
        price.className = 'pt-price';
        price.textContent = fmtPrice(coin.current_price);

        const chg = coin.price_change_percentage_24h;
        const change = document.createElement('span');
        change.className = 'pt-chg ' + (chg > 0.05 ? 'up' : chg < -0.05 ? 'down' : 'flat');
        change.textContent = fmtChange(chg);

        item.appendChild(img);
        item.appendChild(sym);
        item.appendChild(price);
        item.appendChild(change);
        frag.appendChild(item);
      });
    }
    return frag;
  }

  function updateItems(coins) {
    coins.forEach(coin => {
      track.querySelectorAll('[data-id="' + coin.id + '"]').forEach(item => {
        const priceEl = item.querySelector('.pt-price');
        const changeEl = item.querySelector('.pt-chg');
        if (priceEl) priceEl.textContent = fmtPrice(coin.current_price);
        if (changeEl) {
          const chg = coin.price_change_percentage_24h;
          changeEl.textContent = fmtChange(chg);
          changeEl.className = 'pt-chg ' + (chg > 0.05 ? 'up' : chg < -0.05 ? 'down' : 'flat');
        }
      });
    });
  }

  function fetchTicker(attempt) {
    attempt = attempt || 0;
    chrome.runtime.sendMessage({ type: 'GET_TICKER' }, (resp) => {
      if (chrome.runtime.lastError) {
        if (attempt < 4) setTimeout(() => fetchTicker(attempt + 1), 700);
        return;
      }
      if (!resp || resp.error || !Array.isArray(resp.coins)) return;
      const coins = resp.coins;
      if (!initialised) {
        track.innerHTML = '';
        track.appendChild(buildItems(coins));
        const duration = Math.round(coins.length * 2 * 1.5);
        track.style.animationDuration = duration + 's';
        initialised = true;
      } else {
        updateItems(coins);
      }
    });
  }

  fetchTicker();
  setInterval(fetchTicker, 60000);
})();
