'use strict';

import { Controller } from "@hotwired/stimulus";
import * as altcha from "altcha";

export default class extends Controller {
    getStrings() {
        const locale = document.documentElement.lang?.toLowerCase() ?? "fr";

        if (locale.startsWith("en")) {
            return {
                error: "Verification failed. Please try again later.",
                expired: "Verification expired. Please try again.",
                footer: 'Protected by <a href="https://altcha.org/" target="_blank" aria-label="Visit Altcha.org">ALTCHA</a>',
                label: "I am not a robot",
                verified: "Verified",
                verifying: "Verifying...",
                waitAlert: "Verifying... please wait.",
            };
        }

        return {
            error: "Échec de la vérification. Réessayez plus tard.",
            expired: "Vérification expirée. Réessayez.",
            footer: 'Protégé par <a href="https://altcha.org/" target="_blank" aria-label="Visitez Altcha.org">ALTCHA</a>',
            label: "Je ne suis pas un robot",
            verified: "Vérifié",
            verifying: "Vérification en cours...",
            waitAlert: "Vérification en cours... veuillez patienter.",
        };
    }

    async initialize() {
        await altcha;
    }

    connect() {
        this.initialize().then(() => {
            const challengeUrl = process.env.ALTCHA_CHALLENGE;
            const isTestMode = process.env.ALTCHA_TEST === "1";
            let options = {
                refetchonexpire: true,
                spamfilter: false,
                strings: this.getStrings(),
            };

            if (challengeUrl) {
                options = { ...options, challengeurl: challengeUrl };
            }

            if (isTestMode) {
                options = { ...options, test: true, debug: true };
            }

            this.element.configure(options);
        });
    }

    disconnect() {
        this.element.remove();
    }
}
