/** @odoo-module **/

import { browser } from "@web/core/browser/browser";
import { cookie } from "@web/core/browser/cookie";
import { registry } from "@web/core/registry";
import { _t } from "@web/core/l10n/translation";

export function darkModeSwitchItem(env) {
    return {
        type: "switch",
        id: "color_scheme.switch",
        description: _t("Dark Mode"), // Use _t directly for translations
        callback: () => {
            env.services.color_scheme.switchColorScheme();
        },
        isChecked: cookie.get("color_scheme") === "dark",
        sequence: 40,
    };
}

export const colorSchemeService = {
    dependencies: ["orm", "ui", "user"],

    async start(env, { orm, ui, user }) {
        registry.category("user_menuitems").add("darkmode", darkModeSwitchItem);

        if (!cookie.get("color_scheme")) {
            const matchMedia = window.matchMedia("(prefers-color-scheme: dark)");
            const darkMode = matchMedia.matches;
            cookie.set("color_scheme", darkMode ? "dark" : "light");
            if (darkMode) browser.location.reload();
        }

        return {
            async switchColorScheme() {
                const currentScheme = cookie.get("color_scheme");
                const newScheme = currentScheme === "dark" ? "light" : "dark";
                cookie.set("color_scheme", newScheme);

                await orm.write("res.users", [user.userId], {
                    dark_mode: newScheme === "dark",
                });

                ui.block();
                browser.location.reload();
            },
        };
    },
};

registry.category("services").add("color_scheme", colorSchemeService);
