const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
const savedTheme = localStorage.getItem('ossctx-theme');
document.documentElement.dataset.theme = savedTheme || (prefersDark ? 'dark' : 'light');

function renderPlots() {
  document.querySelectorAll('[data-plot]').forEach((element) => {
    try {
      const figure = JSON.parse(element.dataset.plot);
      const theme = document.documentElement.dataset.theme;
      const baseLayout = {
        paper_bgcolor: 'rgba(0,0,0,0)',
        plot_bgcolor: 'rgba(0,0,0,0)',
        font: { color: theme === 'dark' ? '#e2e8f0' : '#102033', family: 'Inter, system-ui, sans-serif' },
        margin: { l: 20, r: 20, t: 20, b: 20 },
      };
      Plotly.newPlot(element, figure.data || [], { ...(figure.layout || {}), ...baseLayout }, { responsive: true, displayModeBar: false });
    } catch (error) {
      element.innerHTML = '<div class="empty-state">Chart unavailable.</div>';
    }
  });
}

function bindThemeToggle() {
  document.querySelectorAll('[data-theme-toggle]').forEach((button) => {
    button.addEventListener('click', () => {
      const nextTheme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
      document.documentElement.dataset.theme = nextTheme;
      localStorage.setItem('ossctx-theme', nextTheme);
      renderPlots();
    });
  });
}

document.addEventListener('DOMContentLoaded', () => {
  bindThemeToggle();
  renderPlots();
});
