/* Theme controller — auto / light / dark, persisted in localStorage.
   The initial data-theme is set by an inline <head> script to avoid a flash;
   this module adds the reactive API, the system-change listener, and keeps the
   browser theme-color meta in sync. */
window.Theme = (function () {
    var KEY = 'inspector-theme';           // 'auto' | 'light' | 'dark'
    var mq = window.matchMedia('(prefers-color-scheme: dark)');
    var listeners = [];

    function pref() { return localStorage.getItem(KEY) || 'auto'; }
    function resolved() { var p = pref(); return p === 'auto' ? (mq.matches ? 'dark' : 'light') : p; }

    function apply() {
        var r = resolved();
        document.documentElement.setAttribute('data-theme', r);
        var meta = document.querySelector('meta[name="theme-color"]');
        if (meta) meta.setAttribute('content', r === 'dark' ? '#0c8f76' : '#0a7d67');
        listeners.forEach(function (fn) { try { fn(pref(), r); } catch (e) {} });
    }

    function setPref(p) { localStorage.setItem(KEY, p); apply(); }
    function cycle() { var order = ['auto', 'light', 'dark']; setPref(order[(order.indexOf(pref()) + 1) % 3]); }
    function onChange(fn) { listeners.push(fn); }

    // react to OS theme changes while in "auto"
    var handler = function () { if (pref() === 'auto') apply(); };
    mq.addEventListener ? mq.addEventListener('change', handler) : mq.addListener(handler);

    apply();
    return { pref: pref, resolved: resolved, setPref: setPref, cycle: cycle, onChange: onChange };
})();
