// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2026 ndaal Gesellschaft für Sicherheit in der Informationstechnik mbH & Co KG, Cologne
// SPDX-FileCopyrightText: Author: Pierre Gronau <Pierre.Gronau@ndaal.eu>
//
// Bootstrap 5.3 colour-mode switcher. Loaded synchronously in <head> so the
// saved theme is applied before first paint (no flash). The toggle button is
// wired on DOMContentLoaded. Kept in an external file so the page CSP needs no
// inline-script hash and no 'unsafe-inline'.
(function () {
  'use strict';
  var KEY = 'sarif-theme';
  var html = document.documentElement;

  function preferred() {
    try {
      var saved = localStorage.getItem(KEY);
      if (saved === 'dark' || saved === 'light') {
        return saved;
      }
    } catch (e) { /* localStorage unavailable */ }
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      return 'dark';
    }
    return 'light';
  }

  function apply(theme) {
    html.setAttribute('data-bs-theme', theme);
    var icon = document.getElementById('theme-icon');
    if (icon) {
      icon.className = theme === 'dark' ? 'bi bi-sun-fill' : 'bi bi-moon-stars-fill';
    }
  }

  // Apply immediately (before body paints).
  apply(preferred());

  document.addEventListener('DOMContentLoaded', function () {
    apply(preferred());
    var btn = document.getElementById('theme-toggle');
    if (btn) {
      btn.addEventListener('click', function () {
        var next = html.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
        try { localStorage.setItem(KEY, next); } catch (e) { /* ignore */ }
        apply(next);
      });
    }
  });
})();
