/** This file is part of Reactor.
 *  Copyright (c) 2020-2026 Kedron Holdings LLC, All Rights Reserved.
 *  Reactor is not public domain or open source. Distribution or derivative works are expressly prohibited.
 */

export const version = 26171;

import api from '/client/ClientAPI.js';

import ReactorUICore from "./reactor-ui-core.js";

import { getAuthInfo, showGlobalLoading } from "./reactor-ui-common.js";

import { _T, getLocale } from './i18n.js';

function readyHandler() {
    console.log("reactor-ui.js:readyHandler()");

    const auth = getAuthInfo( 'reactor' );

    showGlobalLoading( _T( "Loading Reactor..." ) );
    $( 'main' ).empty();
    
    api.off( 'auth_fail.core' ).on( 'auth_fail.core', () => {
        window.location.href = "/reactor/login.html";
    });

    api.start( { authorization: auth?.token } ).then( () => {
        console.log("ui: loading core (API ready)");
        ReactorUICore.start();
    }).catch ( err => {
        if ( err.status === 401 ) {
            window.location.href = "/reactor/login.html";
        } else {
            console.error( err );
        }
    });

    let $el = jQuery( 'a#re-sysclock' );
    let update_browser_time = function() {
        /* Fixed format time display */
        let t = ( new Date() ).toLocaleTimeString( getLocale(), { hour12: false } );
        if ( t !== $el.text() ) {
            $el.text( t );
        }
        setTimeout( update_browser_time, 1000 - ( Date.now() % 1000 ) );
    };
    // Kick it off.
    setTimeout( update_browser_time, 500 );

    // Handle light/dark theme changes
    /* ??? TO-DO "Auto" mode:
       const e = window.matchMedia('(prefers-color-scheme: dark)')
           .addEventListener( 'change', e => toggleTheme( e.matches ) );
       toggleTheme( e.matches );
    */
    $( 'a#swap-theme' ).on( 'click', () => toggleTheme() );
    try {
        // Restore last theme.
        const d = localStorage.getItem( "reactor-theme" );
        console.log("ui: restoring last theme",d);
        toggleTheme( d === "dark" );
    } catch ( err ) {
        console.error( err );
    }
}

function toggleTheme( dark ) {
    const $L = $( 'html' );
    let theme = $L.attr( 'data-bs-theme' ) || "";
    if ( "boolean" === typeof dark ) {
        theme = dark ? "dark" : "";
    } else {
        theme = "dark" === theme ? "" : "dark";
    }
    console.log("ui: setting theme to", theme);
    $L.attr( 'data-bs-theme', theme );
    const $a = $( "a#swap-theme" );
    $( 'i.bi', $a )
        .toggleClass( 'bi-moon', "dark" !== theme )
        .toggleClass( 'bi-sun-fill', "dark" === theme );
    $a.attr( "title", "dark" !== theme ?
            _T(["#ui-theme-switch-to-dark", "Switch to dark theme"]) :
            _T(["#ui-theme-switch-to-light", "Switch to light theme"])
        );
    localStorage.setItem( "reactor-theme", theme );
}

jQuery( readyHandler );
