/**
 * @fileoverview sc-settings-ui.js
 * Verwaltet die Benutzeroberfläche für das Einstellungs-Panel.
 */
import { ScCloseButton } from './close-button.js';
import { initializeLocationSettings } from './sc-settings-location.js';
import { initializeAuthSettings } from './settings-auth.js';
import { HelpSettings } from './sc-settings-help.js';
import { ScIntroButton } from './intro-button.js';
import { SettingsStats } from './settings-stats.js';

export class SettingsUI {
    constructor() {
        // Komponenten vorbereiten
        this.closeButtonComponent = new ScCloseButton('settings-close-button');
        this.introButtonComponent = new ScIntroButton('panel-intro-icon');

        this._closeButtonListeners = [];
        this._helpButtonListeners = [];

        this.panelHTML = `
            <div id="settings-overlay" class="settings-overlay">
                <div id="settings-panel" class="settings-panel" tabindex="-1">
                    <div class="settings-header">
                        <h2 id="settings-title">Info und Einstellungen</h2> 
                        <div id="settings-close-button-placeholder"></div> 
                    </div>
                    <div class="settings-content-scroll-area">
                        <div id="settings-static-content"></div>
                        <div id="settings-dynamic-content" style="display:none;"></div>
                    </div>
                </div>
            </div>
        `;
this.panelCSS = `
            .settings-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 10002; opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease; backdrop-filter: blur(2px); }
            .settings-overlay.visible { opacity: 1; visibility: visible; }
            .settings-panel { background-color: white; padding: 15px; border-radius: 12px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3); width: 95%; max-width: 400px; display: flex; flex-direction: column; max-height: 85vh; overflow: hidden; }
            
            .settings-header { display: flex; justify-content: space-between; align-items: center; background-color: #f5f5f7; padding: 6px 15px; margin: -15px -15px 0 -15px; border-bottom: 1px solid #e5e5e5; flex-shrink: 0; min-height: 38px; }
            .settings-header h3 { font-size: 18px; font-weight: 700; color: #000; margin: 0; padding: 0; line-height: 1; letter-spacing: -0.5px; }
            
            .settings-content-scroll-area { overflow-y: auto; flex-grow: 1; -webkit-overflow-scrolling: touch; padding-top: 5px; padding-right: 5px; }
  .settings-group-divider {
                border: none;
                border-bottom: 1px solid #d1d1d6; 
                margin: 12px 0;
                height: 0;
                width: 100%;
                display: block;}
            .location-settings-row { margin-top: 0 !important; padding-top: 0 !important; }
            #settings-static-content, #settings-dynamic-content { width: 100%; }
            .settings-content-scroll-area > div:not(.settings-group-divider) { margin-bottom: 0px !important; }
            #settings-close-button-placeholder { display: flex; align-items: center; justify-content: center; height: 100%; }
        `;

        // 1. DOM vorbereiten
        this._injectCSS();
        this._injectHTML();
        this._cacheElements(); // Hier werden staticContentArea & Placeholder zugewiesen

        // 2. Module initialisieren (Reihenfolge mit Trennstrichen)
        
        // Gruppe: Hilfe
        this.helpSettings = new HelpSettings(this.staticContentArea, this.dynamicContentArea, this.settingsTitle);
        this.staticContentArea.insertAdjacentHTML('beforeend', '<div class="settings-group-divider"></div>');

        // Gruppe: Standort
        this._scSettingsLocation = initializeLocationSettings(this.staticContentArea);
        this.staticContentArea.insertAdjacentHTML('beforeend', '<div class="settings-group-divider"></div>');

        // Gruppe: Auth
        this._settingsAuth = initializeAuthSettings(this.staticContentArea);
        this.staticContentArea.insertAdjacentHTML('beforeend', '<div class="settings-group-divider"></div>');

        // Gruppe: Statistik
        this._stats = new SettingsStats(this.staticContentArea);

        this._injectIntroButton();
        this._addEventListeners();
    }

    _injectCSS() {
        if (!document.getElementById('sc-settings-ui-styles')) {
            const style = document.createElement('style');
            style.id = 'sc-settings-ui-styles';
            style.textContent = this.panelCSS;
            document.head.appendChild(style);
        }
    }

    _injectHTML() {
        if (!document.getElementById('settings-overlay')) {
            document.body.insertAdjacentHTML('beforeend', this.panelHTML);
        }
    }

    _cacheElements() {
        this.settingsOverlay = document.getElementById('settings-overlay');
        this.settingsPanel = document.getElementById('settings-panel');
        this.settingsTitle = document.getElementById('settings-title');
        this.staticContentArea = document.getElementById('settings-static-content');
        this.dynamicContentArea = document.getElementById('settings-dynamic-content');

        // Close-Button in den Header einsetzen
        const closePlaceholder = document.getElementById('settings-close-button-placeholder');
        if (closePlaceholder) {
            closePlaceholder.innerHTML = ''; // Sicherstellen, dass er leer ist
            closePlaceholder.appendChild(this.closeButtonComponent.getElement());
        }
        
        this.settingsIcon = document.getElementById('settings-icon');
    }

    _injectIntroButton() {
        const infoPlaceholder = document.getElementById('info-icon-placeholder');
        if (infoPlaceholder) {
            infoPlaceholder.appendChild(this.introButtonComponent.getElement());
        }
    }

    _addEventListeners() {
        if (this.settingsIcon) {
            this.settingsIcon.onclick = (e) => {
                e.preventDefault();
                this.open();
            };
        }

        this.closeButtonComponent.onClick(() => this._handleClosePanelOrHelpReturn());

        if (this.helpSettings && this.helpSettings.onHelpButtonClick) {
            this.helpSettings.onHelpButtonClick(() => {
                this._helpButtonListeners.forEach(callback => callback());
            });
        }
    }

    _handleClosePanelOrHelpReturn() {
        if (this.helpSettings && this.helpSettings.isHelpContentVisible()) {
            this.helpSettings.hideHelpContent();
        } else {
            this.close();
        }
        this._closeButtonListeners.forEach(handler => handler());
    }

    _handleOverlayClick(event) {
        if (this.settingsPanel && !this.settingsPanel.contains(event.target)) {
            this.close();
        }
    }

    open() {
        if (this.settingsOverlay) {
            this.settingsOverlay.classList.add('visible');
            if (this.helpSettings) this.helpSettings.hideHelpContent();
            
            this._overlayClickHandler = (e) => this._handleOverlayClick(e);
            this.settingsOverlay.addEventListener('click', this._overlayClickHandler);
        }
    }

    close() {
        if (this.settingsOverlay) {
            this.settingsOverlay.classList.remove('visible');
            if (this._overlayClickHandler) {
                this.settingsOverlay.removeEventListener('click', this._overlayClickHandler);
            }
        }
    }

    onCloseButtonClick(handler) {
        if (typeof handler === 'function') this._closeButtonListeners.push(handler);
    }

    onHelpButtonClick(handler) {
        if (typeof handler === 'function') this._helpButtonListeners.push(handler);
    }

    updateLocationToggle(isEnabled) {
        if (this._scSettingsLocation) {
            this._scSettingsLocation.setLocationToggle(isEnabled);
        }
    }

    isOpen() { 
        return this.settingsOverlay && this.settingsOverlay.classList.contains('visible'); 
    }

    getAuthSettings() {
        return this._settingsAuth;
    }

    getSettingsContainer() {
        return this.staticContentArea;
    }

    getStatsComponent() {
        return this._stats;
    }
}