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

export class AppStartPageCoordinator {
    #onStartDoneCallback;
    #currentSlide = 0;
    #totalSlides = 6;
    #storageKey = 'onboarding_complete';

    constructor(appStartPageUI, onStartDoneCallback) {
        this.#onStartDoneCallback = onStartDoneCallback;
        appStartPageUI.injectIntoDOM(this.#totalSlides);
    }

    start() {
        const grantBtn = document.getElementById('grant-location-button');
        if (grantBtn) {
            grantBtn.onclick = () => {
                if (localStorage.getItem(this.#storageKey) === 'true') {
                    this.#finish();
                } else {
                    this.#startOnboarding();
                }
            };
        }
        document.getElementById('onboarding-next').onclick = () => this.#nextSlide();
        document.getElementById('onboarding-skip').onclick = () => this.#finish();
        this.#initPWALogic();
    }

    #startOnboarding() {
        document.getElementById('start-actions-container')?.classList.add('hidden-btn');
        document.getElementById('onboarding-container')?.classList.remove('hidden');
        this.#currentSlide = 0;
        this.#syncUI();
    }

    #nextSlide() {
        if (this.#currentSlide < this.#totalSlides - 1) {
            this.#currentSlide++;
            this.#syncUI();
        } else {
            this.#finish();
        }
    }

    #syncUI() {
        const slides = document.querySelectorAll('.onboarding-slide');
        const dots = document.querySelectorAll('.dot');
        if (slides.length === 0) return;
        slides.forEach((s, i) => s.classList.toggle('active', i === this.#currentSlide));
        dots.forEach((d, i) => d.classList.toggle('active', i === this.#currentSlide));
        
        const nextBtn = document.getElementById('onboarding-next');
        if (this.#currentSlide === this.#totalSlides - 1 && nextBtn) {
            nextBtn.textContent = "Loslegen";
        }
    }

    #finish() {
        localStorage.setItem(this.#storageKey, 'true');
        const overlay = document.getElementById('location-permission-overlay');
        if (overlay) {
            overlay.style.opacity = '0';
            overlay.style.transition = 'opacity 0.4s';
            setTimeout(() => {
                overlay.remove();
                if (this.#onStartDoneCallback) this.#onStartDoneCallback();
            }, 400);
        }
    }

    #initPWALogic() {
        const pwaBtn = document.getElementById('pwa-info-open-btn');
        const modal = document.getElementById('pwa-install-modal');
        const body = document.getElementById('pwa-modal-body');
        // KORREKTUR: Die ID aus deiner AppStartPageUI nutzen
        const pwaCheckbox = document.getElementById('pwa-hide-permanently');

        if (!pwaBtn || !modal || !body) return;

        // 1. Initialer Check beim Laden
        if (localStorage.getItem('pwa_info_hidden') === 'true') {
            pwaBtn.style.display = 'none';
        }

        // 2. Listener auf die Checkbox
        if (pwaCheckbox) {
            pwaCheckbox.onchange = () => {
                if (pwaCheckbox.checked) {
                    mylog("PWA permanent ausblenden aktiviert.");
                    localStorage.setItem('pwa_info_hidden', 'true');
                    
                    // Button sofort weg
                    pwaBtn.style.display = 'none';
                    
                    // Modal nach kurzem Delay schließen
                    setTimeout(() => {
                        modal.classList.add('hidden');
                    }, 400);
                }
            };
        }

        // 3. Modal öffnen & Markdown laden
        pwaBtn.onclick = async () => {
            if (body.getAttribute('data-loaded') !== 'true') {
                try {
                    const response = await fetch('./pwa-install.md');
                    const markdownText = await response.text();
                    const htmlContent = marked.parse(markdownText);
                    
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = htmlContent;
                    const fragment = document.createDocumentFragment();
                    let activeSection = null;

                    Array.from(tempDiv.children).forEach(el => {
                        if (el.tagName === 'H2' || el.tagName === 'H3') {
                            const section = document.createElement('div');
                            section.className = 'accordion-section';
                            const header = document.createElement('div');
                            header.className = 'accordion-header';
                            header.innerHTML = `<span>${el.innerHTML}</span><span class="toggle-icon">+</span>`;
                            activeSection = document.createElement('div');
                            activeSection.className = 'section-content';
                            section.appendChild(header);
                            section.appendChild(activeSection);
                            fragment.appendChild(section);

                            header.onclick = () => {
                                const open = header.classList.toggle('active');
                                activeSection.style.maxHeight = open ? activeSection.scrollHeight + "px" : "0px";
                                header.querySelector('.toggle-icon').textContent = open ? "-" : "+";
                            };
                        } else if (activeSection) {
                            activeSection.appendChild(el.cloneNode(true));
                        }
                    });

                    body.innerHTML = '';
                    body.appendChild(fragment);
                    body.setAttribute('data-loaded', 'true');
                } catch (e) {
                    body.innerHTML = `<p>Fehler: ${e.message}</p>`;
                }
            }
            modal.classList.remove('hidden');
        };

        document.getElementById('pwa-modal-close').onclick = () => modal.classList.add('hidden');
    }

    showButton() {
        const spinner = document.getElementById('loading-spinner-content');
        if (spinner) spinner.style.display = 'none';
        const actions = document.getElementById('start-actions-container');
        if (actions) actions.classList.remove('hidden-btn');
    }
}