/**
 * auth-login.js
 * Vollständige Fassung mit Passwort-Sichtbarkeit und allen Handlern.
 */
import { BackendService } from "./backend-db.js";
import { frontendConfig } from "./utilities.js";

export class AuthLogin {
    constructor() {
        this._modal = null;
        this._onSuccessCallback = null;
        this._isRegistrationMode = false;
        this._minPwdLength = frontendConfig.minPwdLength || 6;

        this._injectCSS();
        this._injectHTML();
        this._cacheElements();
        this._addListeners();
    }

    _injectCSS() {
        if (document.getElementById('sc-ux-gateway-styles')) return;
        const style = document.createElement('style');
        style.id = 'sc-ux-gateway-styles';
        style.textContent = `
            .ux-gateway-overlay {
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.4); display: none; justify-content: center; align-items: center; 
                z-index: 100000; backdrop-filter: blur(12px) saturate(180%); -webkit-backdrop-filter: blur(12px) saturate(180%);
            }
            .ux-gateway-content {
                background: rgba(255, 255, 255, 0.95); padding: 30px 25px; border-radius: 20px;
                width: 85%; max-width: 320px; box-shadow: 0 20px 60px rgba(0,0,0,0.2); text-align: center;
            }
            .ux-gateway-header h3 { margin: 0 0 10px 0; font-size: 20px; font-weight: 700; color: #1c1c1e; }
            .ux-gateway-body input {
                width: 100%; padding: 14px; margin: 8px 0; border: 1px solid #ddd; border-radius: 10px; font-size: 16px; 
                box-sizing: border-box; background: white; -webkit-appearance: none;
            }
            /* Auge-Positionierung */
            .ux-pwd-wrapper { position: relative; width: 100%; }
            .ux-pwd-wrapper input { padding-right: 45px !important; }
            #ux-pwd-eye {
                position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
                cursor: pointer; color: #8e8e93; font-size: 18px; z-index: 5;
            }
            .ux-feedback-area { color: #ff3b30; font-size: 13px; margin: 10px 0; display: none; font-weight: 500; }
            .ux-btn-primary { width: 100%; background: #007AFF; color: white; border: none; padding: 14px; border-radius: 10px; font-weight: 600; margin-top: 15px; cursor: pointer; font-size: 16px; }
            .ux-btn-alt { background: none; border: none; color: #007AFF; margin-top: 20px; cursor: pointer; font-size: 15px; }
            .ux-footer-switch { margin-top: 25px; padding-top: 20px; border-top: 1px solid rgba(0,0,0,0.1); font-size: 13px; color: #8e8e93; }
            #ux-link-toggle { color: #007AFF; font-weight: 600; text-decoration: none; }
        `;
        document.head.appendChild(style);
    }

    _injectHTML() {
        if (document.getElementById('ux-gateway-root')) return;
        const html = `
        <div id="ux-gateway-root" class="ux-gateway-overlay">
            <div class="ux-gateway-content">
                <div class="ux-gateway-header"><h3 id="ux-header-title">stolperClean</h3></div>
                <div class="ux-gateway-body">
                    <p id="ux-notice-text" style="font-size: 14px; color: #3a3a3c; margin-bottom: 20px; line-height: 1.4;">Identifiziere dich...</p>
                    <input type="text" id="ux-id-entry" placeholder="Name" autocomplete="off" spellcheck="false">
                    <div class="ux-pwd-wrapper">
                        <input type="password" id="ux-code-entry" placeholder="Passwort" autocomplete="current-password">
                        <i id="ux-pwd-eye" class="fas fa-eye"></i>
                    </div>
                    <div id="ux-error-info" class="ux-feedback-area"></div>
                    <button id="ux-submit-trigger" class="ux-btn-primary">Bestätigen</button>
                    <button id="ux-alt-trigger" type="button" class="ux-btn-alt">Weiter als Gast</button>
                    <div class="ux-footer-switch">
                        <span id="ux-switch-label">Neu hier?</span> <a href="#" id="ux-link-toggle">Konto erstellen</a>
                    </div>
                </div>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
    }

    _cacheElements() {
        this._modal = document.getElementById('ux-gateway-root');
        this._title = document.getElementById('ux-header-title');
        this._note = document.getElementById('ux-notice-text');
        this._userInput = document.getElementById('ux-id-entry');
        this._passInput = document.getElementById('ux-code-entry');
        this._eyeIcon = document.getElementById('ux-pwd-eye');
        this._errorMsg = document.getElementById('ux-error-info');
        this._submitBtn = document.getElementById('ux-submit-trigger');
        this._switchLink = document.getElementById('ux-link-toggle');
        this._guestBtn = document.getElementById('ux-alt-trigger');
        this._switchLabel = document.getElementById('ux-switch-label');
    }

    _addListeners() {
        this._eyeIcon.onclick = () => {
            const isPwd = this._passInput.type === 'password';
            this._passInput.type = isPwd ? 'text' : 'password';
            this._eyeIcon.classList.toggle('fa-eye', !isPwd);
            this._eyeIcon.classList.toggle('fa-eye-slash', isPwd);
        };
        this._guestBtn.onclick = (e) => { e.preventDefault(); this._handleGuestLogin(); };
        this._switchLink.onclick = (e) => { e.preventDefault(); this._toggleMode(); };
        this._submitBtn.onclick = (e) => { e.preventDefault(); this._handleAction(); };
        this._passInput.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); this._handleAction(); }};
        this._modal.onclick = (e) => { if (e.target === this._modal) this.close(); };
    }

    async _handleGuestLogin() {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('last_known_user');
        localStorage.removeItem('auth_session_expired');
        try { await BackendService.getInstance().logoutUser(); } catch (e) { console.warn("Logout fehlgeschlagen."); }
        localStorage.setItem('currentUser', 'Gast');
        this.close();
        if (this._onSuccessCallback) this._onSuccessCallback({ success: true, uid: 1, username: 'Gast' });
    }

    open(lastUser = null, isExpired = false) {
        this._passInput.value = '';
        this._passInput.type = 'password';
        this._eyeIcon.className = 'fas fa-eye';
        this._isRegistrationMode = false;
        this._updateUIForMode();
        if (isExpired) this._note.textContent = "Deine Sitzung ist abgelaufen. Bitte melde dich erneut an.";
        else this._note.textContent = "Melde dich an, um deine Beiträge zu sehen.";
        this._userInput.value = (lastUser && lastUser !== 'Gast') ? lastUser : '';
        this._errorMsg.style.display = 'none';
        this._modal.style.display = 'flex';
        setTimeout(() => (this._userInput.value ? this._passInput : this._userInput).focus(), 250);
    }

    close() { this._modal.style.display = 'none'; this._passInput.value = ''; localStorage.removeItem('auth_session_expired'); }

    _toggleMode() { this._isRegistrationMode = !this._isRegistrationMode; this._passInput.value = ''; this._updateUIForMode(); }

    _updateUIForMode() {
        const isReg = this._isRegistrationMode;
        this._title.textContent = isReg ? "Registrieren" : "Anmelden";
        this._submitBtn.textContent = isReg ? "Registrieren" : "Anmelden";
        this._note.textContent = isReg ? "Wähle Zugangsdaten, um deine Beiträge zu speichern." : "Melde dich an, um deine Beiträge zu sehen.";
        if (this._switchLabel) this._switchLabel.textContent = isReg ? "Schon registriert?" : "Neu hier?";
        this._switchLink.textContent = isReg ? "Anmelden" : "Registrieren";
    }

    async _handleAction() {
        const isRegistration = this._isRegistrationMode;
        const username = this._userInput.value.trim();
        const password = this._passInput.value;
        if (!username || !password) { this.showError("Bitte alle Felder ausfüllen."); return; }
        if (isRegistration && password.length < this._minPwdLength) { this.showError(`Passwort muss mindestens ${this._minPwdLength} Zeichen lang sein.`); return; }
        try {
            const backend = BackendService.getInstance();
            const res = isRegistration ? await backend.insertUser(username, password) : await backend.loginUser(username, password);
            if (res.success) {
                localStorage.setItem('currentUser', res.username);
                localStorage.setItem('last_known_user', res.username);
                if (this._onSuccessCallback) this._onSuccessCallback(res);
                this.close();
            } else { this.showError(res.error || "Zugriff verweigert."); this._passInput.value = ''; }
        } catch (e) { this.showError(e.message || "Verbindung fehlgeschlagen."); }
    }

    showError(msg) { this._errorMsg.textContent = msg; this._errorMsg.style.display = 'block'; }
    onSuccess(callback) { this._onSuccessCallback = callback; }
}