/**
 * auth-mgmt.js
 * Vollständige Fassung inklusive Passwort-Auge und funktionsfähigen Handlern.
 */
import { ScCloseButton } from "./close-button";
import { BackendService } from './backend-db.js';
import { frontendConfig } from "./utilities.js";

export class AuthMgmt {
    constructor() {
        this._modal = null;
        this._pwdInput = null;
        this._verifyBtn = null;
        this._statusMsg = null;
        this._errorMsg = null;
        this._actionContainer = null;
        this._titleName = null;
        this._userDisplay = null;
        this._eyeIcon = null;
        this._btns = [];
        this._isVerified = false;

        this.backend = BackendService.getInstance();
        this._minPwdLength = frontendConfig.minPwdLength || 6;

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

    _injectCSS() {
        if (document.getElementById('auth-mgmt-styles')) return;
        const style = document.createElement('style');
        style.id = 'auth-mgmt-styles';
        style.textContent = `
            .auth-modal-overlay {
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(0, 0, 0, 0.5); display: none; justify-content: center; align-items: center; 
                z-index: 100000; backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
            }
            .auth-modal-content {
                background: white; padding: 25px; border-radius: 20px; width: 90%; max-width: 340px; box-shadow: 0 20px 50px rgba(0,0,0,0.3);
            }
            .mgmt-verify-box { display: flex; gap: 8px; margin-bottom: 15px; }
            .mgmt-pwd-wrapper { position: relative; flex: 1; }
            .mgmt-pwd-wrapper input { 
                padding-right: 40px !important; width: 100%; padding: 12px; 
                border: 1px solid #ddd; border-radius: 10px; font-size: 16px; box-sizing: border-box; 
            }
            #auth-mgmt-eye {
                position: absolute; right: 12px; top: 50%; transform: translateY(-50%);
                cursor: pointer; color: #8e8e93; font-size: 16px;
            }
            .auth-primary-button {
                width: 100%; padding: 14px; border-radius: 12px; border: none; background: #007AFF; color: white;
                font-size: 16px; font-weight: 600; cursor: pointer; display: flex; align-items: center; justify-content: center;
            }
            .auth-success-button { background: #34c759 !important; color: #000 !important; }
            .auth-primary-button:disabled { background: #d1d1d6 !important; color: #8e8e93 !important; cursor: not-allowed; }
            .auth-error { color: #ff3b30; font-size: 13px; text-align: center; display: none; margin-bottom: 10px; }
        `;
        document.head.appendChild(style);
    }

    _injectHTML() {
        if (document.getElementById('auth-mgmt-modal')) return;
        const html = `
        <div id="auth-mgmt-modal" class="auth-modal-overlay">
            <div class="auth-modal-content">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 id="mgmt-title-name" style="margin:0; font-size: 18px;">Mein Bereich</h3>
                    <div id="auth-mgmt-close-placeholder"></div>
                </div>
                <div class="auth-modal-body">
                    <div id="mgmt-user-display" style="font-size: 13px; color: #8e8e93; margin-bottom: 15px; margin-top: -15px;"></div>
                    <p style="margin-bottom: 15px; font-size: 14px; line-height: 1.4;">Passwort erforderlich für Änderungen.</p>
                    <div class="mgmt-verify-box">
                        <div class="mgmt-pwd-wrapper">
                            <input type="password" id="auth-mgmt-old-password" placeholder="Aktuelles Passwort">
                            <i id="auth-mgmt-eye" class="fas fa-eye"></i>
                        </div>
                        <button id="auth-mgmt-verify-btn" class="auth-primary-button" style="width: auto; padding: 0 15px; font-size: 14px;">Prüfen</button>
                    </div>
                    <div id="auth-mgmt-status" style="font-size: 12px; margin-bottom: 10px; min-height: 15px; text-align: center; font-weight: 600;"></div>
                    <div id="auth-mgmt-error-msg" class="auth-error"></div>
                    <div id="mgmt-action-container" style="display: flex; flex-direction: column; gap: 10px; margin-top: 15px; opacity: 0.3; pointer-events: none;">
                        <button id="auth-btn-chg-pwd" class="auth-primary-button" disabled>Passwort ändern</button>
                        <button id="auth-btn-export" class="auth-primary-button auth-success-button" disabled>Mein Engagement (Bericht)</button>
                        <button id="auth-btn-anonymize" class="auth-primary-button" style="background:#ff3b30;" disabled>Konto löschen</button>
                    </div>
                </div>
            </div>
        </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
    }

    _cacheElements() {
        this._modal = document.getElementById('auth-mgmt-modal');
        this._pwdInput = document.getElementById('auth-mgmt-old-password');
        this._eyeIcon = document.getElementById('auth-mgmt-eye');
        this._verifyBtn = document.getElementById('auth-mgmt-verify-btn');
        this._statusMsg = document.getElementById('auth-mgmt-status');
        this._errorMsg = document.getElementById('auth-mgmt-error-msg');
        this._actionContainer = document.getElementById('mgmt-action-container');
        this._userDisplay = document.getElementById('mgmt-user-display');
        this._titleName = document.getElementById('mgmt-title-name');
        
        this._btns = [
            document.getElementById('auth-btn-chg-pwd'),
            document.getElementById('auth-btn-anonymize'),
            document.getElementById('auth-btn-export')
        ];
    }

    _addListeners() {
        const cp = document.getElementById('auth-mgmt-close-placeholder');
        if (cp) { 
            const cb = new ScCloseButton('mgmt-close-btn'); 
            cp.appendChild(cb.getElement()); 
            cb.onClick(() => this.close()); 
        }
        
        this._eyeIcon.onclick = () => {
            const isPwd = this._pwdInput.type === 'password';
            this._pwdInput.type = isPwd ? 'text' : 'password';
            this._eyeIcon.classList.toggle('fa-eye', !isPwd);
            this._eyeIcon.classList.toggle('fa-eye-slash', isPwd);
        };

        this._verifyBtn.onclick = () => this._verifyPasswordOnServer();
        this._pwdInput.onkeydown = (e) => { if (e.key === 'Enter') this._verifyPasswordOnServer(); };

        // Die Button-Handler
        this._btns[0].onclick = () => this._handlePasswordChange();
        this._btns[1].onclick = () => this._handleAnonymize();
        this._btns[2].onclick = () => this._handleExport();
    }

    async _verifyPasswordOnServer() {
        const user = localStorage.getItem('currentUser');
        const password = this._pwdInput.value;
        if (!user || user === 'Gast') return this._showError("Kein aktiver Benutzer.");

        this._verifyBtn.disabled = true;
        this._statusMsg.textContent = "Prüfe...";
        this._statusMsg.style.color = "#8e8e93";
        this._errorMsg.style.display = 'none';

        try {
            const res = await this.backend.loginUser(user, password);
            if (res.success) {
                this._setVerified(true);
            } else {
                this._setVerified(false);
                this._showError(res.error || "Passwort inkorrekt.");
                this._pwdInput.value = '';
            }
        } catch (e) {
            this._showError("Verbindung fehlgeschlagen.");
        } finally {
            this._verifyBtn.disabled = false;
        }
    }

    _setVerified(v) {
        this._isVerified = v;
        this._actionContainer.style.opacity = v ? '1' : '0.3';
        this._actionContainer.style.pointerEvents = v ? 'auto' : 'none';
        this._btns.forEach(b => { if(b) b.disabled = !v; });
        if (v) {
            this._statusMsg.textContent = "✓ Bestätigt";
            this._statusMsg.style.color = "#34c759";
            this._pwdInput.blur();
        }
    }

    _resetUI() {
        this._isVerified = false;
        this._pwdInput.value = '';
        this._pwdInput.type = 'password';
        this._eyeIcon.className = 'fas fa-eye';
        this._statusMsg.textContent = '';
        this._errorMsg.style.display = 'none';
        const u = localStorage.getItem('currentUser');
        if (this._userDisplay) this._userDisplay.textContent = (u && u !== 'Gast') ? `Angemeldet als: ${u}` : "";
        this._setVerified(false);
    }

    open() {
        this._resetUI();
        this._modal.style.display = 'flex';
        setTimeout(() => this._pwdInput.focus(), 200);
    }

    close() {
        this._modal.style.display = 'none';
        this._resetUI();
    }

    _showError(m) {
        this._statusMsg.textContent = "";
        this._errorMsg.textContent = m;
        this._errorMsg.style.display = 'block';
    }

    async _handlePasswordChange() {
        if (!this._isVerified) return;
        const newPass = prompt(`Neues Passwort (mind. ${this._minPwdLength} Zeichen):`);
        if (!newPass) return;
        if (newPass.length < this._minPwdLength) return alert("Zu kurz.");
        
        const confirmPass = prompt("Wiederholen:");
        if (newPass !== confirmPass) return alert("Passwörter nicht identisch.");

        try {
            await this.backend.changePassword(this._pwdInput.value, newPass);
            alert("Erfolgreich geändert.");
            this.close();
        } catch (e) { this._showError("Fehler beim Ändern."); }
    }

    async _handleAnonymize() {
        if (!this._isVerified) return;
        const user = localStorage.getItem('currentUser');
        if (!confirm(`Konto "${user}" wirklich löschen?`)) return;
        try {
            await this.backend.anonymizeAccount(this._pwdInput.value);
            localStorage.removeItem('currentUser');
            location.reload();
        } catch (e) { this._showError("Löschen fehlgeschlagen."); }
    }

    async _handleExport() {
        if (!this._isVerified) return;
        try {
            this._statusMsg.textContent = "Exportiere...";
            await this.backend.exportUserData(this._pwdInput.value);
            this._statusMsg.textContent = "✓ Export abgeschlossen.";
            this._setVerified(false);
            this._pwdInput.value = '';
        } catch (e) { this._showError("Export fehlgeschlagen."); }
    }
}