/**
 * settings-auth.js
 * Zentraler Koordinator für den Auth-Status.
 * Ersetzt das Zahnrad durch den "Mein Bereich" Button.
 */
import { AuthLogin } from "./auth-login.js";
import { AuthMgmt } from "./auth-mgmt.js";
import { BackendService } from './backend-db.js';

let settingsAuthInstance = null;

export class SettingsAuth {
    constructor(parentElement) {
        this._injectCSS();
        this._parentElement = parentElement;

        this._AuthLogin = new AuthLogin();
        this._mgmtModal = new AuthMgmt();

        this._injectSettingsRow();

        this._statusPrefixElement = document.getElementById('auth-status-prefix');
        this._statusTextElement = document.getElementById('auth-status-text');
        this._authActionArea = document.getElementById('auth-action-area');

        this._AuthLogin.onSuccess((result) => this._finalizeLogin(result));

        // Start-Check beim Initialisieren
        this.ensureValidSession();
    }

    _injectCSS() {
        if (document.getElementById('sc-auth-styles')) return;
        const style = document.createElement('style');
        style.id = 'sc-auth-styles';
        style.textContent = `
            .auth-settings-row { 
                display: flex; 
                justify-content: space-between; 
                align-items: center; 
                padding: 0 !important; 
                margin: 0 !important; 
            }
            .auth-info-container { display: flex; flex-direction: column; }
            .auth-label { font-size: 11px; color: #8e8e93; line-height: 1.2; }
            .auth-status { font-size: 15px; line-height: 1.2; }
            
            .settings-action-button { 
                -webkit-appearance: none; 
                background-color: #007AFF; 
                color: white; 
                border: none; 
                padding: 8px 16px; 
                border-radius: 8px; 
                font-weight: 600; 
                font-size: 14px; 
                cursor: pointer; 
            }

            .auth-actions-container { 
                display: flex; 
                align-items: center; 
                gap: 10px; 
            }

            /* Der neue "Mein Bereich" Button */
            .btn-user-area { 
                background: none; 
                border: 1px solid #007AFF; 
                color: #007AFF; 
                padding: 7px 14px; 
                border-radius: 8px; 
                font-size: 13px; 
                font-weight: 500; 
                cursor: pointer; 
                white-space: nowrap;
                transition: all 0.2s ease;
            }

            .btn-user-area:disabled { 
                border-color: #ccc; 
                color: #ccc; 
                cursor: not-allowed; 
            }
            
            .btn-user-area:active:not(:disabled) {
                background-color: rgba(0, 122, 255, 0.1);
            }
        `;
        document.head.appendChild(style);
    }

    _injectSettingsRow() {
        this._parentElement.insertAdjacentHTML('beforeend', `
            <div class="settings-row auth-settings-row">
                <div class="auth-info-container">
                    <span id="auth-status-prefix" class="auth-label">angemeldet als</span>
                    <span id="auth-status-text" class="auth-status">Prüfe...</span>
                </div>
                <div id="auth-action-area"></div>
            </div>`);
    }
/*
    async ensureValidSession() {
        try {
            const result = await BackendService.getInstance().checkSession();
            if (result && result.success && result.uid > 1) {
                this._finalizeLogin(result, false);
            } else {
                this._handleLogout(false);
            }
        } catch (e) {
            const lastKnown = localStorage.getItem('last_known_user');
            if (lastKnown && lastKnown !== 'Gast') {
                this._handleSessionExpired(lastKnown);
            } else {
                this._handleLogout(false);
            }
        }
    }*/
   async ensureValidSession(retries = 3, delay = 1500) {
    try {
        const result = await BackendService.getInstance().checkSession();
        if (result && result.success && result.uid > 1) {
            this._finalizeLogin(result, false);
        } else {
            this._handleLogout(false);
        }
    } catch (e) {
        // Prüfen, ob es ein Netzwerk-Problem ist (typisch bei Kamera-Wechsel & Mobile Daten)
        const isNetworkError = e.message?.toLowerCase().includes('fetch') || 
                               e.message?.toLowerCase().includes('network') ||
                               e.name === 'TypeError';

        if (isNetworkError && retries > 0) {
            mylog(`Auth-Check fehlgeschlagen (Netzwerk). Retry in ${delay}ms... (${retries} Versuche übrig)`);
            
            // UI kurz auf "Warten" stellen
            if (this._statusTextElement) {
                this._statusTextElement.textContent = "Verbindung wird aufgebaut...";
            }

            // Wartezeit (dem Modem Zeit geben)
            await new Promise(resolve => setTimeout(resolve, delay));
            
            // Rekursiver Aufruf mit einem Versuch weniger
            return this.ensureValidSession(retries - 1, delay);
        }

        // Wenn alle Retries fehlschlagen ODER es ein echter Server-Fehler ist (z.B. 401)
        const lastKnown = localStorage.getItem('last_known_user');
        if (lastKnown && lastKnown !== 'Gast') {
            this._handleSessionExpired(lastKnown);
        } else {
            this._handleLogout(false);
        }
    }
}

    _handleSessionExpired(lastUser) {
        localStorage.setItem('auth_session_expired', 'true');
        this._updateUIState();
        this._AuthLogin.open(lastUser, true);
    }

    _finalizeLogin(result, notify = true) {
        localStorage.setItem('currentUser', result.username);
        localStorage.removeItem('auth_session_expired');
        this._updateUIState();
        
        if (this._parentElement) {
            this._parentElement.style.display = 'block';
        }

        if (window.app && window.app.settingsCoordinator) {
            window.app.settingsCoordinator.initializeSettingsState();
        }

        if (notify) {
            window.dispatchEvent(new CustomEvent('sc-auth-changed', {
                detail: { status: 'user', username: result.username, source: 'SettingsAuth' }
            }));
        }
    }

    async _handleLogout(notifyServer = true) {
        const wasGuest = localStorage.getItem('currentUser') === 'Gast';
        if (notifyServer) {
            try {
                await BackendService.getInstance().logoutUser();
            } catch (e) { console.warn("Logout fehlgeschlagen", e); }
        }
        localStorage.setItem('currentUser', 'Gast');
        this._updateUIState();
        if (!wasGuest) {
            window.dispatchEvent(new CustomEvent('sc-auth-changed', {
                detail: { source: 'SettingsAuth', status: 'guest', reason: 'logout' }
            }));
        }
    }

    _updateUIState() {
        const user = localStorage.getItem('currentUser') || 'Gast';
        const isGuest = (user === 'Gast');

        if (!this._statusTextElement || !this._authActionArea || !this._statusPrefixElement) return;

        if (!isGuest) {
            // UI für eingeloggte User: Abmelden + Aktiver Bereich-Button
            this._statusPrefixElement.style.display = 'block';
            this._statusPrefixElement.textContent = 'angemeldet als';
            this._statusTextElement.innerHTML = `<strong>${user}</strong>`;

            this._authActionArea.innerHTML = `
                <div class="auth-actions-container">
                    <button id="logout-btn-inner" class="settings-action-button" style="background: #ff3b30;">Abmelden</button>
                    <button id="auth-mgmt-user-btn" class="btn-user-area">Mein Bereich</button>
                </div>`;
            
            document.getElementById('logout-btn-inner').onclick = (e) => {
                e.preventDefault();
                this._handleLogout(true);
            };
            document.getElementById('auth-mgmt-user-btn').onclick = (e) => {
                e.preventDefault();
                this._mgmtModal.open();
            };
        } else {
            // UI für Gäste: Anmelden + Deaktivierter Bereich-Button
            this._statusPrefixElement.style.display = 'none';
            this._statusTextElement.textContent = 'Gast';

            this._authActionArea.innerHTML = `
                <div class="auth-actions-container">
                    <button id="auth-login-trigger" class="settings-action-button">Anmelden</button>
                    <button id="auth-mgmt-user-btn" class="btn-user-area" disabled>Mein Bereich</button>
                </div>`;

            const btn = document.getElementById('auth-login-trigger');
            if (btn) {
                btn.onclick = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    if (this._AuthLogin) this._AuthLogin.open();
                };
            }
        }
    }
}

export function initializeAuthSettings(parentElement) {
    if (!settingsAuthInstance) settingsAuthInstance = new SettingsAuth(parentElement);
    return settingsAuthInstance;
}