(function () {
  function addButtons(gd) {
    const modebar = gd.querySelector('.modebar');
    if (!modebar || modebar.dataset.extrasAdded === '1') return;
    modebar.dataset.extrasAdded = '1';

    function mkBtn(title, svgPath, onClick) {
      const a = document.createElement('a');
      a.className = 'modebar-btn';
      a.setAttribute('data-title', title);
      a.setAttribute('aria-label', title);
      a.innerHTML =
        '<svg viewBox="0 0 24 24" width="16" height="16">' +
        `<path d="${svgPath}"></path>` +
        '</svg>';
      a.addEventListener('click', function (e) {
        e.preventDefault();
        onClick(gd);
      });
      return a;
    }

    const refreshBtn = mkBtn(
      'Hard refresh',
      'M12 2v12m0 0l-4-4m4 4l4-4M5 20h14',
      function () {
        const u = new URL(window.location.href);
        u.searchParams.set('_r', Date.now().toString()); // bust cache
        window.location.href = u.toString();
      }
    );

    const downloadBtn = mkBtn(
      'Download visible CSV',
      'M12 3v10m0 0l-4-4m4 4l4-4M5 19h14',
      function (gdEl) {
        const graphId = gdEl.id; // Dash Graph id
        const hiddenId = 'download-hidden-' + graphId;
        const el = document.getElementById(hiddenId);
        if (el) el.click();
      }
    );

    const group = document.createElement('div');
    group.className = 'modebar-group';
    group.appendChild(refreshBtn);
    group.appendChild(downloadBtn);

    modebar.insertBefore(group, modebar.firstChild);
  }

  document.addEventListener('plotly_afterplot', function (e) {
    const gd = e.target;
    if (gd && gd.classList && gd.classList.contains('js-plotly-plot')) {
      addButtons(gd);
    }
  });
})();
