import { t } from "../i18n.js";

// Speichert den Zustand zentral, damit die man.js darauf zugreifen kann
export const formState = {
    isLoginMode: false,
    isForgetPasswordMode: false,
    isResetPasswordMode: false,
    isOtpMode: false,
    pendingVerificationEmail: '',
    resetEmail: '',
    cooldownTimer: null
};

// Hier wird die PixiJS-Referenz gespeichertm die wir beim Initialisieren übergeben bekommen.
let p = {};

/**
 * Initialisiert die Formular-Steuerunf und regeistiert alle Event-Listener.
 * 
 * @param {Object} pixiRefs - Ein Objekt mit allen zu steuernden PixiJS-Elementen und Farben.
 */
export function initForms(pixiRefs) {
    p = pixiRefs;
    
    const htmlTabLogin = document.getElementById('tab-login');
    const htmlTabRegistert = document.getElementById('tab-register');
    const htmlButton = document.getElementById('btn-register');
    const htmlDiscord = document.getElementById('discord-link');

    // --- Hover Effekte synchronisieren (HTML -> PixiJS) ---
    htmlTabLogin.addEventListener('mouseenter', () => {
        if (!formState.isLoginMode) {
            p.tabLogin.fill.tint = p.COLOR_TAB_HOVER;
            p.tabLogin.fill.alpha = 0.8;
        }
    });
    htmlTabLogin.addEventListener('mouseleave', () => {
        if (!formState.isLoginMode) {
            p.tabLogin.fill.tint = p.COLOR_TAB_INACTIVE;
            p.tabLogin.fill.alpha = 0.4;
        }
    });

    htmlTabRegistert.addEventListener('mouseenter', () => {
        if (formState.isLoginMode) {
            p.tabRegister.fill.tint = p.COLOR_TAB_HOVER;
            p.tabRegister.fill.alpha = 0.8;
        }
    });
    htmlTabRegistert.addEventListener('mouseleave', () => {
        if (formState.isLoginMode) {
            p.tabRegister.fill.tint = p.COLOR_TAB_INACTIVE;
            p.tabRegister.fill.alpha = 0.4;
        }
    });
    
    htmlButton.addEventListener('mouseenter', () => {
        p.btnRegister.fill.tint = p.COLOR_BTN_HOVER;
        p.btnRegister.fill.alpha = 1.0;
    });
    htmlButton.addEventListener('mouseleave', () => {
        p.btnRegister.fill.tint = p.COLOR_BTN_DEFAULT;
        p.btnRegister.fill.alpha = 0.6;
    });

    if (htmlDiscord) {
        htmlDiscord.addEventListener('mouseenter', () => {
            p.discordIcon.tint = p.COLOR_TAB_HOVER;
            p.discordText.style.fill = p.COLOR_TAB_HOVER;
        });
        htmlDiscord.addEventListener('mouseleave', () => {
            p.discordIcon.tint = p.COLOR_TAB_INACTIVE;
            p.discordText.style.fill = p.COLOR_TAB_INACTIVE;
        });
    }

    htmlTabLogin.addEventListener('click', setLoginMode);
    htmlTabRegistert.addEventListener('click', setRegisterMode);

    const forgotPasswordLink = document.getElementById('forgot-password-link');
    if (forgotPasswordLink) {
        forgotPasswordLink.addEventListener('click', (e) => {
            e.preventDefault();
            setForgotPasswordMode();
        });
    }

    const backLink = document.getElementById('back-link');
    if (backLink) {
        backLink.addEventListener('click', (e) => {
            e.preventDefault();
            formState.pendingVerificationEmail = '';
            formState.resetEmail = '';
            formState.isOtpMode = false;
            formState.isForgotPasswordMode = false;
            formState.isResetPasswordMode = false;
            formState.isLoginMode = false;
            setLoginMode();
        });
    }
}

/**
 * Leert die Formulardaten bei einem TabWechsel
 */
export function clearForm() {
    document.getElementById('username').value = '';
    document.getElementById('email').value = '';
    document.getElementById('password').value = '';
    document.getElementById('remember').checked = false;
    document.getElementById('agb').checked = false;

    document.getElementById('tab-container').style.display = 'block';
    p.tabLogin.container.visible = true;
    p.tabRegister.container.visible = true;

    document.getElementById('username').style.display = 'block';
    p.inputUser.container.visible = true;

    const pwField = document.getElementById('password');
    pwField.style.display = 'block';
    pwField.type = 'password';
    p.inputLock.container.visible = true;

    document.getElementById('otp-instruction').style.display = 'none';
    document.getElementById('resend-otp-link').style.display = 'none';
    document.getElementById('forgot-password-link').style.display = 'none';
    document.getElementById('back-link').style.display = 'none';

    if (formState.cooldownTimer) {
        clearInterval(formState.cooldownTimer);
        formState.cooldownTimer = null;
    }
    const resendLink = document.getElementById('resend-otp-link');
    if(resendLink) {
        resendLink.style.pointerEvents = 'auto';
        resendLink.style.opacity = '1.0';
        resendLink.textContent = t('link_resend_otp');
    }

    const msgBox = document.getElementById('msg-box');
    msgBox.textContent = '';
    msgBox.style.color = 'var(--color-text-main)';
}

export function setLoginMode() {
    if (formState.isLoginMode) return;
    formState.isLoginMode = true;
    clearForm();

    p.tabLogin.fill.tint = p.COLOR_TAB_ACTIVE;
    p.tabLogin.fill.alpha = 0.6;
    p.tabRegister.fill.tint = p.COLOR_TAB_INACTIVE;
    p.tabRegister.fill.alpha = 0.4;

    document.getElementById('tab-login').classList.add('active');
    document.getElementById('tab-register').classList.remove('active');

    p.inputEmail.container.visible = false;
    document.getElementById('group-email').style.display = 'none';

    p.inputLock.container.y = 200;
    document.getElementById('password').style.top = '200px';
    document.getElementById('forgot-password-link').style.display = 'block';

    document.getElementById('email').required = false;

    document.getElementById('group-remember').style.display = 'flex';
    document.getElementById('group-agb').style.display = 'none';
    document.getElementById('agb').required = false;

    document.getElementById('btn-register').textContent = t('btn_login');
    document.getElementById('username').placeholder = t('ph_username_login');
    document.getElementById('password').placeholder = t('ph_password');
    document.getElementById('msg-box').textContent = '';
}

export function setRegisterMode() {
    if (!formState.isLoginMode) return;
    formState.isLoginMode = false;
    clearForm();

    p.tabRegister.fill.tint = p.COLOR_TAB_ACTIVE;
    p.tabRegister.fill.alpha = 0.6;
    p.tabLogin.fill.tint = p.COLOR_TAB_INACTIVE;
    p.tabLogin.fill.alpha = 0.4;

    document.getElementById('tab-register').classList.add('active');
    document.getElementById('tab-login').classList.remove('active');

    p.inputEmail.container.visible = true;
    document.getElementById('group-email').style.display = 'block';

    p.inputLock.container.y = 265;
    document.getElementById('password').style.top = '265px';

    document.getElementById('email').required = true;

    document.getElementById('group-remember').style.display = 'none';
    document.getElementById('group-agb').style.display = 'flex';
    document.getElementById('agb').required = true;

    document.getElementById('btn-register').textContent = t('btn_register');
    document.getElementById('username').placeholder = t('ph_username_reg');
    document.getElementById('email').placeholder = t('ph_email');
    document.getElementById('password').placeholder = t('ph_password');
    document.getElementById('msg-box').textContent = '';
}

export function setOtpMode(email) {
    formState.isOtpMode = true;
    formState.pendingVerificationEmail = email;
    clearForm();

    document.getElementById('tab-container').style.display = 'none';
    p.tabLogin.container.visible = false;
    p.tabRegister.container.visible = false;

    document.getElementById('username').style.display = 'none';
    document.getElementById('username').required = false;
    p.inputUser.container.visible = false;

    document.getElementById('group-email').style.display = 'none';
    document.getElementById('email').required = false;
    p.inputEmail.container.visible = false;
    const instructionEl = document.getElementById('otp-instruction');
    instructionEl.style.display = 'block';
    instructionEl.textContent = t('txt_otp_instruction');

    document.getElementById('resend-otp-link').style.display = 'block';

    p.inputLock.container.y = 200;
    document.getElementById('password').style.top = '200px';
    document.getElementById('password').type = 'text';
    document.getElementById('password').placeholder = t('ph_otp');
    document.getElementById('password').value = '';

    document.getElementById('group-agb').style.display = 'none';
    document.getElementById('agb').required = false;
    document.getElementById('group-remember').style.display = 'none';

    document.getElementById('msg-box').textContent = '';
    document.getElementById('btn-register').textContent = t('btn_verify');
    document.getElementById('back-link').style.display = 'block';
}

export function setForgotPasswordMode() {
    formState.isLoginMode = false;
    formState.isOtpMode = false;
    formState.isForgotPasswordMode = true;
    formState.isResetPasswordMode = false;
    clearForm();

    document.getElementById('tab-container').style.display = 'none';
    p.tabLogin.container.visible = false;
    p.tabRegister.container.visible = false;

    document.getElementById('username').style.display = 'none';
    document.getElementById('username').required = false;
    p.inputUser.container.visible = false;

    document.getElementById('password').style.display = 'none';
    document.getElementById('password').required = false;
    p.inputLock.container.visible = false;

    document.getElementById('group-email').style.display = 'block';
    document.getElementById('email').type = 'email';
    document.getElementById('email').required = true;
    document.getElementById('email').style.top = '200px';
    p.inputEmail.container.visible = true;
    p.inputEmail.container.y = 200;

    document.getElementById('group-remember').style.display = 'none';
    document.getElementById('group-agb').style.display = 'none';
    document.getElementById('forgot-password-link').style.display = 'none';

    const instructionEl = document.getElementById('otp-instruction');
    instructionEl.style.display = 'block';
    instructionEl.textContent = t('txt_reset_instruction_1');

    document.getElementById('btn-register').textContent = t('btn_reset_request');
    document.getElementById('back-link').style.display = 'block';
    document.getElementById('msg-box').textContent = '';
}

export function setResetPasswordMode(email) {
    formState.isForgotPasswordMode = false;
    formState.isResetPasswordMode = true;
    formState.resetEmail = email;
    clearForm();

    document.getElementById('tab-container').style.display = 'none';
    p.tabLogin.container.visible = false;
    p.tabRegister.container.visible = false;

    document.getElementById('username').style.display = 'none';
    document.getElementById('username').required = false;
    p.inputUser.container.visible = false;
    
    document.getElementById('group-email').style.display = 'block';
    document.getElementById('email').type = 'text';
    document.getElementById('email').placeholder = t('ph_otp');
    document.getElementById('email').required = true;
    document.getElementById('email').style.top = '200px';
    p.inputEmail.container.y = 200;

    document.getElementById('password').style.display = 'block';
    document.getElementById('password').required = true;
    document.getElementById('password').placeholder = t('ph_password');
    document.getElementById('password').style.top = '265px';
    p.inputLock.container.visible = true;
    p.inputLock.container.y = 265;

    const instructionEl = document.getElementById('otp-instruction');
    instructionEl.style.display = 'block';
    instructionEl.style.top = '150px';
    instructionEl.textContent = t('txt_reset_instruction_2');

    document.getElementById('back-link').style.display = 'block';
    document.getElementById('btn-register').textContent = t('btn_reset_password');
    document.getElementById('msg-box').textContent = '';
}

/**
 * Startet einen visuellen Countdown auf einem übergebenen Link-Element.
 * Sperrt währenddessen die Klickbarkeit
 * 
 * @param {HTMLElement} linkElement - Das HTML A-Tag (zB resendOtpLink)
 * @param {string} orginalTextKey - Der i18n Key für den ursprünglichen Text
 * @param {number} durationSconds - Die Dauer in Sekunden (hier 120 für 2Minuten)
 */
export function startVisualCountdown(linkElement, orginalTextKey, durationSconds) {
    if (formState.cooldownTimer) clearInterval(formState.cooldownTimer);
    let remaining = durationSconds;

    linkElement.style.pointerEvents = 'none';
    linkElement.style.opacity = '0.5';

    const updateText = () => {
        const minutes = Math.floor(remaining / 60);
        const seconds = remaining % 60;
        const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
        linkElement.textContent = `${t(orginalTextKey)} (${timeString})`;
    };

    updateText();

    formState.cooldownTimer = setInterval(() => {
        remaining--;

        if (remaining <= 0) {
            clearInterval(formState.cooldownTimer);
            formState.cooldownTimer = null;
            linkElement.style.pointerEvents = 'auto';
            linkElement.style.opacity = '1.0';
            linkElement.textContent = t(orginalTextKey);
        } else {
            updateText();
        }
    }, 1000);
}
