/**
 * @fileoverview app-startpage-ui.js
 * Start-Overlay und Onboarding.
 */
import { HelpSettings } from './sc-settings-help.js';

export class AppStartPageUI {
    #carouselIndex = 0;
    #totalSlides = 6;
    #helpSystem = null;

    injectIntoDOM(totalSlides) {
        this.#totalSlides = totalSlides || 6;
        this.#injectCSS();
        this.#injectHTML(this.#totalSlides);
        this.#initHelpSystem();
        this.#setupEventListeners();
        this.#setupPwaAccordion(); 
    }

    #initHelpSystem() {
        const modalBody = document.getElementById('pwa-modal-body');
        const modalTitle = document.querySelector('.modal-header h3');
        const dummyContainer = document.createElement('div');
        
        try {
            this.#helpSystem = new HelpSettings(dummyContainer, modalBody, modalTitle);
        } catch (e) {
            console.error("AppStartPageUI: Fehler beim Initialisieren der Help-Engine:", e);
        }
    }

    #injectCSS() {
        if (document.getElementById('start-page-styles')) return;
        const style = document.createElement('style');
        style.id = 'start-page-styles';
        style.textContent = `
            #location-permission-overlay {
                position: fixed; top: 0; left: 0; right: 0; bottom: 0;
                width: 100vw; height: 100svh;
                background: rgba(0, 0, 0, 0.05); 
                display: flex; flex-direction: column; 
                justify-content: center; align-items: center; 
                z-index: 10000; color: white;
                margin: 0; padding: 0;
                -webkit-transform: translateZ(0); transform: translateZ(0);
            }

            #start-actions-container { 
                display: flex; flex-direction: column; align-items: center; gap: 20px; 
                transform: translateY(10) !important;
            }
            #start-actions-container.hidden-btn { display: none !important; }
            
            #grant-location-button {
                background: linear-gradient(135deg, #349d4c 0%, #28a745 100%);
                padding: 25px 40px !important;
                color: white; border: none; border-radius: 22px; cursor: pointer;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            }

            .btn-main { font-size: 3rem; font-weight: 800; display: block; line-height: 1; }
            .btn-sub { font-size: 1.1rem; opacity: 0.9; margin-top: 10px; display: block; }

            #onboarding-container {
                width: 100%; max-width: 450px; height: 100%;
                text-align: center; display: flex; flex-direction: column; 
                align-items: center; justify-content: center;
                transform: translateY(-10vh) !important;
            }
            #onboarding-container.hidden { display: none !important; }
            
            .onboarding-carousel { width: 100%; }
            .onboarding-slide { display: none; width: 100%; padding-top: 40px; }
            .onboarding-slide.active { display: block !important; animation: fadeIn 0.5s ease-out; }
            
            .onboarding-img { 
                width: 85%; height: auto; display: block; margin: 0 auto;
                max-height: 60vh; object-fit: contain;
                filter: drop-shadow(0 15px 30px rgba(0,0,0,0.4)); 
                border-radius: 20px;
            }
            
            .onboarding-nav { display: flex; gap: 10px; justify-content: center; margin: 20px 0; }
            .dot { width: 10px; height: 10px; border-radius: 50%; background: rgba(255,255,255,0.3); transition: transform 0.2s; }
            .dot.active { background: #349d4c; transform: scale(1.3); }

            #onboarding-next {
                background: #349d4c; color: white; border: none; padding: 18px; 
                border-radius: 16px; font-size: 1.2rem; font-weight: bold; 
                width: 90%; cursor: pointer; margin-top: 10px;
            }

            .modal-overlay { 
                position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                background: rgba(0,0,0,0.85); z-index: 10001; 
                display: flex; align-items: center; justify-content: center;
            }
            .modal-overlay.hidden { display: none !important; }
            .modal-content { 
                position: relative;
                background: #fff; color: #333; width: 90%; max-width: 440px; 
                border-radius: 24px; overflow: hidden; display: flex; flex-direction: column;
                box-shadow: 0 20px 60px rgba(0,0,0,0.5);
            }
            .modal-header { 
                padding: 18px 22px; background: #f2f2f2; display: flex; 
                justify-content: space-between; align-items: center; border-bottom: 1px solid #eee; 
            }
            .modal-header h3 { margin: 0; color: #28a745; font-size: 1.2rem; font-weight: bold; }
            #pwa-modal-body { padding: 20px; overflow-y: auto; max-height: 60vh; min-height: 200px; }

            .modal-footer { padding: 15px; background: #f9f9f9; border-top: 1px solid #eee; }

            #pwa-modal-body .accordion-section { margin-bottom: 10px; border: 1px solid #ddd; border-radius: 8px; overflow: hidden; background: #fff; }
            #pwa-modal-body .accordion-header { 
                display: flex; justify-content: space-between; align-items: center; 
                padding: 12px 15px; background-color: #f9f9f9; cursor: pointer; 
                font-weight: bold; color: #333; transition: background 0.2s;
            }
            #pwa-modal-body .accordion-header.active { background-color: #28a745 !important; color: white !important; }
            #pwa-modal-body .section-content { padding: 0 15px; background: #fff; max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out; }

            @keyframes fadeIn { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }
        `;
        document.head.appendChild(style);
    }

    #injectHTML(totalSlides) {
        if (document.getElementById('location-permission-overlay')) return;
        
        const cb = Date.now();
        const count = totalSlides || 6;
        let slidesHTML = '';
        let dotsHTML = '';
        
        for (let i = 0; i < count; i++) {
            slidesHTML += `<div class="onboarding-slide" data-index="${i}"><img src="./onboarding_${i}.png?v=${cb}" class="onboarding-img"></div>`;
            dotsHTML += `<div class="dot"></div>`;
        }

        const html = `
            <div id="location-permission-overlay">
                <div id="start-actions-container">
                    <button id="grant-location-button">
                        <span class="btn-main">stolperClean</span>
                        <span class="btn-sub">Erinnerung sichtbar machen</span>
                    </button>
                    <button id="pwa-info-open-btn" style="font-size: 1.3rem !important; background:none; border:none; color:white; margin-top:15px; text-decoration:underline; cursor:pointer;">als App installieren</button>
                </div>
                <div id="onboarding-container" class="hidden">
                    <div class="onboarding-carousel">${slidesHTML}</div>
                    <div class="onboarding-nav">${dotsHTML}</div>
                    <button id="onboarding-next">Weiter</button>
                    <button id="onboarding-skip" style="font-size: 1.3rem !important;background:none; border:none; color:rgba(255,255,255,0.6); margin-top:10px; cursor:pointer; text-decoration:underline;">Überspringen</button>
                </div>
                <div id="pwa-install-modal" class="modal-overlay hidden">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3>App Installation als Icon</h3>
                            <button id="pwa-modal-close" style="background:none; border:none; font-size:2.5rem; cursor:pointer; color:#ccc; line-height:1;">&times;</button>
                        </div>
                        <div id="pwa-modal-body"></div>
                        <div class="modal-footer">
                            <label style="color:#666; font-size:0.9rem; cursor:pointer;">
                                <input type="checkbox" id="pwa-hide-permanently"> Nicht mehr anzeigen
                            </label>
                        </div>
                    </div>
                </div>
            </div>`;
        document.body.insertAdjacentHTML('beforeend', html);
    }

    #setupEventListeners() {
        const btnOpen = document.getElementById('pwa-info-open-btn');
        const btnClose = document.getElementById('pwa-modal-close');
        const modal = document.getElementById('pwa-install-modal');

        if (btnOpen) {
            btnOpen.onclick = async () => {
                modal.classList.remove('hidden');
                if (this.#helpSystem) {
                    await this.#helpSystem.loadAndDisplayHelpContent();
                }
            };
        }

        if (btnClose) {
            btnClose.onclick = () => modal.classList.add('hidden');
        }

        document.getElementById('grant-location-button').onclick = () => {
            document.getElementById('start-actions-container').classList.add('hidden-btn');
            document.getElementById('onboarding-container').classList.remove('hidden');
            this.#updateCarousel();
        };

        document.getElementById('onboarding-next').onclick = () => {
            if (this.#carouselIndex < this.#totalSlides - 1) {
                this.#carouselIndex++;
                this.#updateCarousel();
            } else {
                this.#finish();
            }
        };

        document.getElementById('onboarding-skip').onclick = () => this.#finish();
    }

    #updateCarousel() {
        const slides = document.querySelectorAll('.onboarding-slide');
        const dots = document.querySelectorAll('.dot');
        slides.forEach((s, i) => s.classList.toggle('active', i === this.#carouselIndex));
        dots.forEach((d, i) => d.classList.toggle('active', i === this.#carouselIndex));
    }

#setupPwaAccordion() {
        const modalBody = document.getElementById('pwa-modal-body');
        if (!modalBody) return;

        const initHeader = (header) => {
            if (header.dataset.hasListener) return;
            header.dataset.hasListener = "true";

            header.onclick = (e) => {
                e.preventDefault();
                e.stopPropagation();

                const content = header.nextElementSibling;
                const isOpen = content.style.maxHeight && content.style.maxHeight !== '0px';

                // Alle anderen schließen
                modalBody.querySelectorAll('.section-content').forEach(c => {
                    c.style.maxHeight = '0px';
                    c.previousElementSibling.classList.remove('active');
                });

                if (!isOpen) {
                    header.classList.add('active');
                    
                    // KORREKTUR: Puffer nur für den letzten Block (Block 4), 
                    // um Abschneiden zu verhindern, sonst exakte Höhe.
                    const isLastBlock = !header.parentElement.nextElementSibling;
                    const padding = isLastBlock ? 60 : 0;
                    content.style.maxHeight = (content.scrollHeight + padding) + "px";
                    
                    // KORREKTUR: Scroll nur, wenn der Header aus dem Sichtfeld rutscht
                    // 'block: nearest' verhindert das aggressive Springen nach oben.
                    setTimeout(() => {
                        header.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                    }, 150); 
                }
            };
        };

        const observer = new MutationObserver(() => {
            modalBody.querySelectorAll('.accordion-header').forEach(initHeader);
        });

        observer.observe(modalBody, { childList: true, subtree: true });
        // Initial-Check falls Content schon da
        modalBody.querySelectorAll('.accordion-header').forEach(initHeader);
    }

    #finish() {
        document.dispatchEvent(new CustomEvent('startpage:complete'));
        document.getElementById('location-permission-overlay')?.remove();
    }
}