import RollDialog from "./dialogs/rollDialog.mjs";
import { initUserDice } from "./dice3d.mjs";
import { VermineUtils } from "./roll.mjs";
import { postWelcomeMessage } from "./tour.mjs";

export const registerHooks = function () {
    /**
     * Ready hook loads tables, and override's foundry's entity link functions to provide extension to pseudo entities
     */
    CONFIG.debug.hooks = false;
    Hooks.once('diceSoNiceReady', async (dice3d) => {
        const dsnModule = game.modules.get('dice-so-nice');
        if (!dsnModule?.active) return;
        const { DiceSystem } = await import(`/modules/${dsnModule.id}/api.js`);
        const vermineSystem = new DiceSystem('Vermine2047', 'Vermine 2047', "preferred", 'totem')
        dice3d.addSystem(vermineSystem);

        game.users.forEach(user => {
            initUserDice(dice3d, user)
        });

        dice3d.addDicePreset({
            type: "d10",
            labels: [
                "systems/vermine2047/assets/images/die/d10-1.webp",
                "systems/vermine2047/assets/images/die/d10-2.webp",
                "systems/vermine2047/assets/images/die/d10-3.webp",
                "systems/vermine2047/assets/images/die/d10-4.webp",
                "systems/vermine2047/assets/images/die/d10-5.webp",
                "systems/vermine2047/assets/images/die/d10-6.webp",
                "systems/vermine2047/assets/images/die/d10-7.webp",
                "systems/vermine2047/assets/images/die/d10-8.webp",
                "systems/vermine2047/assets/images/die/d10-9.webp",
                "systems/vermine2047/assets/images/die/d10-0.webp",
            ],

            system: "Vermine2047",

        });

    });

    Hooks.on('renderChatMessageHTML', async (message, html, data) => {
        // Échanges de coups : liaisons ouvertes à tous (propriétaires de cibles inclus)
        const { VermineExchange } = await import('./exchange.mjs');
        VermineExchange.bindChat(html, message);

        let rerollTitle = html.querySelector(".reroll-fromroll h4");
        if (rerollTitle) {
            rerollTitle.addEventListener("click", () => { html.querySelector(".reroll").classList.toggle('visible') })
        }
        if (message.author?._id !== game.user._id && !game.user.isGM) {
            // désactiver les inputs pour les joueurs non-auteurs du message
            html.querySelectorAll("input").forEach(inp => inp.disabled = true);
            //cacher le boutton reroll
            html.querySelectorAll("div.reroll-from-effort").forEach(el => el.style.display = "none")
            return
        }
        await VermineUtils.chatListenners(html)
    })


    Hooks.on('updateUser', async (user, updateData, options, id) => {
        if (game.dice3d) {
            initUserDice(game.dice3d, user)

        }
    })
    Hooks.once("ready", async () => {
        // Relays player rerolls to the GM client (Foundry v14 ChatMessage
        // updates are GM-only).
        VermineUtils.registerRerollSocket();
        // Message de bienvenue (crédits), affiché à chaque chargement.
        await postWelcomeMessage();
    });

    // changement de la pause
    Hooks.on("renderGamePause", async function (app, element) {
        const pauseEl = element ?? document.getElementById("pause");
        if (!pauseEl || pauseEl.className !== "paused") return;
        pauseEl.querySelectorAll("img").forEach(img => {
            img.src = 'systems/vermine2047/assets/images/ui/vermine_pause.webp';
            img.style.opacity = 1;
        });
        const caption = pauseEl.querySelector("figcaption");
        if (caption) caption.textContent = "Communauté endormie...";
    });

    /**
     * Create a macro when dropping an entity on the hotbar
     * Item      - open roll dialog for item
     * Actor     - open actor sheet
     * Journal   - open journal sheet
     */
    Hooks.on("hotbarDrop", async (bar, data, slot) => {
        // console.log(data.type);
        // Create item macro if rollable item - weapon, spell, prayer, trait, or skill

        return false;
    });

    Hooks.on('getSceneControlButtons', async (controls) => {
        const tokenControls = controls.tokens;
        if (tokenControls && tokenControls.tools) {
            tokenControls.tools['dice-roller'] = {
                name: 'Dice Roller',
                title: game.i18n.localize("VERMINE.RollTool"),
                icon: 'fas fa-dice-d10',
                button: true,
                onChange() {
                    RollDialog.create().then(d => d.render(true));
                }
            };
        }
    });

    /* -------------------------------------------- */
    /*  PreCreate Hooks                                */
    /* -------------------------------------------- */

    Hooks.on("preCreateActor", function (actor) {
        // pre create actor
        if (actor.img == "icons/svg/mystery-man.svg") {
            actor.updateSource({ "img": `systems/vermine2047/assets/icons/actors/${actor.type}.webp` });
        }

    });

    Hooks.on("preCreateItem", function (item) {
        if (item.img == "icons/svg/item-bag.svg") {
            item.updateSource({ "img": `systems/vermine2047/assets/icons/items/${item.type}.webp` });
            // item.updateSource({"img": `systems/vermine2047/icons/competence.webp`});
        }
    });

    // Un Groupe démarre avec une Réserve à son maximum (3D + 1D par membre).
    Hooks.on("createActor", async function (actor) {
        if (actor.type !== "group") return;
        const reserve = actor.system?.reserve;
        if (reserve && reserve.value === 0 && reserve.max > 0) {
            await actor.update({ "system.reserve.value": reserve.max });
        }
    });

    /* -------------------------------------------- */
    /*  Combat Hooks                                */
    /* -------------------------------------------- */

    /*
    Hooks.on("createCombatant", function (combatant) {
    if (game.user.isGM) {
        let actor = combatant.actor;

        console.log('create combatant', actor);
    }
    });*/

    Hooks.on("updateCombat", function () {
        if (game.user.isGM) {
            let combatant = (game.combat.combatant) ? game.combat.combatant.actor : "";

            // update combat

            /*if (combatant.type == "marker" && combatant.system.settings.general.isCounter == true) {
                let step = (!combatant.system.settings.general.counting) ? -1 : combatant.system.settings.general.counting;
                let newQuantity = combatant.system.pools.quantity.value + step;
                combatant.update({"system.pools.quantity.value": newQuantity});
            }*/
        }
    });
    // Note: editMode flag is no longer auto-set on actor creation to avoid
    // "ActiveEffect application phase already completed" errors.
    // Users can enable edit mode manually via the checkbox in the character sheet.
    // Hooks.on("createActor", async function (actor, options, id) {
    //   actor.setFlag("world", "editMode", true);
    // })
}