/**
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  JavaScript
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025 Wassilios Meletiadis <https://www.bplan-solutions.de/>
 * /Δ\
 */


/**
 *
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
export function setTheme(theme)
{
    // theme: 'dark' | 'light' | 'system'
    try {
        if (theme === 'dark') {
            document.documentElement.classList.add('dark');
            localStorage.setItem('theme', 'dark');

        } else if (theme === 'light') {
            document.documentElement.classList.remove('dark');
            localStorage.setItem('theme', 'light');
        } else {
            // system: remove stored preference (fallback to script in head)
            localStorage.removeItem('theme');
            // apply immediate system preference
            const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

            if (prefersDark) {
                document.documentElement.classList.add('dark');

            } else {
                document.documentElement.classList.remove('dark');
            }
        }
    } catch (e) {
        console.error(e);
    }
}; // setTheme()


/**
 *
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
export function toggleTheme()
{
    try {
        const isDark = document.documentElement.classList.toggle('dark');
        localStorage.setItem('theme', isDark ? 'dark' : 'light');

        return isDark;

    } catch (e) {
        console.error(e);

        return null;
    }
}; // toggleTheme()
