/**
 * @fileoverview sc-settings-help.js
 * Kapselt die UI und Logik für den Info-Bereich.
 */

import { marked } from 'https://cdn.jsdelivr.net/npm/marked@12.0.1/lib/marked.esm.js'; 

export class HelpSettings {
    constructor(staticContentArea, dynamicContentArea, settingsTitleElement) {
        this.staticContentArea = staticContentArea;
        this.dynamicContentArea = dynamicContentArea;
        this.settingsTitleElement = settingsTitleElement;

        this._injectHTML();
        this._injectCSS();
        this._cacheElements();
        this._addEventListeners();

        console.log("HelpSettings: Instanziiert.");
    }

    _injectHTML() {
        const htmlContent = `
            <div class="settings-help-container">
                <div id="info-icon-placeholder"></div>
                
                <div class="help-buttons-group" style="display: flex; flex-direction: row; gap: 8px; flex-grow: 1;">
                    <button type="button" id="open-help-button" class="help-button">So gehts</button>
                    <button type="button" id="reset-onboarding-button" class="help-button reset-btn-custom">
                        Starthinweise
                    </button>
                </div>
            </div>
        `;
        if (this.staticContentArea) {
            this.staticContentArea.insertAdjacentHTML('afterbegin', htmlContent);
        }
    }

    _injectCSS() {
        const cssContent = `
            .settings-help-container {
                display: flex !important;
                flex-direction: row !important;
                align-items: center !important;
                gap: 12px !important;
                margin-top: 10px;
                margin-bottom: 10px;
                width: 100%;
                box-sizing: border-box;
            }

            #info-icon-placeholder {
                width: 42px !important;
                height: 42px !important;
                flex-shrink: 0 !important;
            }

            .help-button {
                flex: 1 !important; /* Beide Buttons nehmen gleichen Platz ein */
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 8px; /* Etwas moderner abgerundet */
                height: 42px;
                padding: 0 10px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                transition: background-color 0.2s ease, transform 0.1s ease;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                display: flex;
                align-items: center;
                justify-content: center;
                white-space: nowrap;
            }

            .help-button:hover { 
                background-color: #0056b3; 
            }

            /* Spezifische Zustände für den Reset-Button */
            .reset-btn-active { 
                background-color: #28a745 !important; 
                pointer-events: none; 
            }

            /* Akkordeon & Content Styling */
            .accordion-section {
                margin-bottom: 10px;
                border: 1px solid #ddd;
                border-radius: 8px;
                overflow: hidden; 
                background-color: #fff;
            }

            .accordion-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12px 15px;
                background-color: #f2f2f2;
                cursor: pointer;
                font-weight: bold;
                color: #333;
                border-bottom: 1px solid #eee;
                transition: background-color 0.2s ease;
            }

            .accordion-header:hover { background-color: #e9e9e9; }
            .accordion-header.active { background-color: #007bff; color: white; }

            .toggle-icon {
                font-size: 1.4em;
                line-height: 1;
                margin-left: 10px;
                transition: transform 0.3s ease;
            }

            .section-content {
                padding: 0 15px;
                max-height: 0; 
                overflow: hidden;
                transition: max-height 0.3s ease-out, padding 0.3s ease-out;
                background-color: #fff;
            }
        `;
        if (!document.getElementById('sc-help-settings-styles')) {
            const styleElement = document.createElement('style');
            styleElement.id = 'sc-help-settings-styles';
            styleElement.textContent = cssContent;
            document.head.appendChild(styleElement);
        }
    }

    _cacheElements() {
        this.openHelpButton = this.staticContentArea.querySelector('#open-help-button');
        this.resetOnboardingButton = this.staticContentArea.querySelector('#reset-onboarding-button');
    }

    _addEventListeners() {
        if (this.openHelpButton) {
            this.openHelpButton.addEventListener('click', (e) => {
                e.preventDefault();
                this.loadAndDisplayHelpContent();
            });
        }

        if (this.resetOnboardingButton) {
            this.resetOnboardingButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();

                localStorage.removeItem('onboarding_complete');
                localStorage.removeItem('pwa_info_hidden');
                
                this.resetOnboardingButton.textContent = "✓ Neustart...";
                this.resetOnboardingButton.classList.add('reset-btn-active');

                setTimeout(() => {
                    window.location.reload();
                }, 800);
            });
        }
    }

    async loadAndDisplayHelpContent() {
        if (!this.dynamicContentArea) return;

        this.dynamicContentArea.innerHTML = `<p style="padding:15px;">Lade Anleitung...</p>`;
        this.dynamicContentArea.style.display = 'block'; 
        this.staticContentArea.style.display = 'none'; 
        this.settingsTitleElement.textContent = "Anleitung & Info"; 

        try {
            const response = await fetch('./sc-help.md'); 
            if (!response.ok) throw new Error(`Fehler: ${response.status}`);

            const markdownText = await response.text();
            const htmlContent = marked.parse(markdownText); 

            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = htmlContent;
            const children = Array.from(tempDiv.children);
            tempDiv.innerHTML = ''; 

            let currentContentDiv = null; 

            children.forEach(element => {
                if (element.tagName === 'H2' || element.tagName === 'H3') {
                    const headerWrapper = document.createElement('div');
                    headerWrapper.className = 'accordion-header';
                    headerWrapper.innerHTML = `<span>${element.innerHTML}</span><span class="toggle-icon">+</span>`;

                    currentContentDiv = document.createElement('div');
                    currentContentDiv.className = 'section-content';
                    
                    const accordionSectionDiv = document.createElement('div');
                    accordionSectionDiv.className = 'accordion-section';
                    accordionSectionDiv.appendChild(headerWrapper);
                    accordionSectionDiv.appendChild(currentContentDiv);
                    
                    tempDiv.appendChild(accordionSectionDiv); 
                } else if (currentContentDiv) {
                    currentContentDiv.appendChild(element);
                }
            });

            this.dynamicContentArea.innerHTML = tempDiv.innerHTML;
            this._initializeCollapsibles();

        } catch (error) {
            this.dynamicContentArea.innerHTML = `<p style="padding:15px;">Fehler beim Laden: ${error.message}</p>`;
        }
    }

    _initializeCollapsibles() {
        this.dynamicContentArea.querySelectorAll('.accordion-header').forEach(header => {
            header.addEventListener('click', (e) => {
                const content = header.nextElementSibling;
                const icon = header.querySelector('.toggle-icon');

                if (content.style.maxHeight && content.style.maxHeight !== '0px') {
                    content.style.maxHeight = '0px';
                    content.style.paddingTop = '0px';
                    content.style.paddingBottom = '0px';
                    icon.textContent = '+';
                    header.classList.remove('active');
                } else {
                    content.style.maxHeight = content.scrollHeight + 'px';
                    content.style.paddingTop = '10px';
                    content.style.paddingBottom = '10px';
                    icon.textContent = '-';
                    header.classList.add('active');
                }
            });
        });
    }

    hideHelpContent() {
        if (this.dynamicContentArea) {
            this.dynamicContentArea.innerHTML = ''; 
            this.dynamicContentArea.style.display = 'none'; 
        }
        if (this.staticContentArea) {
            this.staticContentArea.style.display = 'block'; 
        }
        if (this.settingsTitleElement) {
            this.settingsTitleElement.textContent = "Info und Einstellungen"; 
        }
    }

    isHelpContentVisible() {
        return this.dynamicContentArea && this.dynamicContentArea.style.display === 'block';
    }
}