import { showToast } from "./sc-utilities";

export class BsUI {
    static instance = null;
    _displayedObject = null;
    isExpanded = false;
    _currentCoords = null;
    closeCallbacks = [];
    _addStoneClickCallback = null;
    _onResizeCallback = null;
    contentRef = null;
    // Variablen für die Wisch-Logik
    _swipeStartX = 0;
    _swipeStartY = 0;
    _isDragging = false;
    _swipeDirection = null;
    _swipeThreshold = 50;
    _maxSwipeXDeviation = 20;
    _isTouchOnInteractiveElement = false;

    constructor(wrapperId, elementId, contentAreaId, actionsAreaId) {
        if (BsUI.instance) {
            return BsUI.instance;
        }
        BsUI.instance = this;
        this.wrapperId = wrapperId;
        this.elementId = elementId;
        this.contentAreaId = contentAreaId;
        this.actionsAreaId = actionsAreaId;
        this.panelHTML = `
            <div id="${this.wrapperId}" class="bottom-sheet-wrapper hidden">
                <div class="bottom-sheet-toggle-handle">
                    <i class="fas fa-chevron-up"></i>
                </div>
                <div id="${this.elementId}" class="bottom-sheet">
                    <div class="bottom-sheet-content-wrapper">
                        <div class="bottom-sheet-header">
                            <h4 id="bottom-sheet-header-text" class="bottom-sheet-header-text"></h4>
                        </div>
                        <div id="nav-prev-button" class="bottom-sheet-nav-button nav-left hidden-via-js"><i class="fas fa-chevron-left"></i></div>
                        <div id="nav-next-button" class="bottom-sheet-nav-button nav-right hidden-via-js"><i class="fas fa-chevron-right"></i></div>
                        <div class="bottom-sheet-expanded">
                            <div class="bottom-sheet-content">
                                <div id="${this.contentAreaId}"></div>
                            </div>
                        </div>
                    </div>
                    <div class="bottom-sheet-actions" id="${this.actionsAreaId}">
                        <div class="expanded-actions-container">
                            <div id="caretaker-checkbox-container" class="hidden">
                                <label>
                                    <input type="checkbox" id="caretaker-checkbox" />
                                    <span id="caretaker-label">Patenschaft</span>
                                </label>
                            </div>
                            <div id="add-stolperstein-button" class="ctrl-button bottom-sheet-add-button hidden">
                                <i id="add-icon" class="fas fa-plus"></i>
                            </div>
                            <div id="edit-stolperstein-button" class="ctrl-button bottom-sheet-edit-button hidden">
                                <i id="edit-icon" class="fas fa-pen"></i>
                            </div>
                        </div>
                        <div id="bottom-sheet-main-actions" class="bottom-sheet-main-actions hidden">
                            <button id="poi-clean-button" class="btn primary hidden"></button>
                            <button id="poi-dirty-button" class="btn secondary hidden"></button>
                            <button id="cluster-clean-button" class="btn primary hidden"></button>
                            <button id="cluster-dirty-button" class="btn secondary hidden"></button>
                        </div>
                        <button id="fallback-button" class="btn hidden"></button>
                    </div>
                </div>
            </div>
        `;

        this.panelCSS = `
            .bottom-sheet-wrapper {
                position: fixed; bottom: 0; left: 0; width: 100%;
                height: auto;
                transform: translateY(100%);
                transition: transform 0.3s ease-out;
                z-index: 1000;
                display: flex; flex-direction: column-reverse; align-items: center;
                overflow: visible;
                touch-action: pan-y;
            }
            .bottom-sheet-wrapper.open { transform: translateY(0); }
            .bottom-sheet-wrapper.hidden { display: none !important; }
            .bottom-sheet-wrapper.expanded {
                height: auto;
                max-height: 60vh;
            }
            .bottom-sheet {
                width: 100%;
                min-height: 150px;
                height: auto;
                max-height: 60vh;
                color: #333; background-color: #fff;
                box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
                border-top-left-radius: 15px; border-top-right-radius: 15px;
                transition: height 0.3s ease-out;
                z-index: 1;
                display: flex; flex-direction: column;
                overflow: hidden;
                position: relative;
            }
            .bottom-sheet.expanded { height: auto; }
            .bottom-sheet-content-wrapper {
                height: auto;
                display: flex;
                flex-direction: column;
                flex-grow: 0;
                overflow: hidden;
            }
            .bottom-sheet-toggle-handle {
                position: absolute; left: 50%; top: -30px;
                transform: translateX(-50%);
                width: 50px; height: 30px;
                display: flex; justify-content: center; align-items: center;
                cursor: pointer;
                background-color: rgba(255, 255, 255, 0.9);
                border-top-left-radius: 15px; border-top-right-radius: 15px;
                border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;
                box-shadow: 0 -2px 5px rgba(0,0,0,0.2);
                z-index: 2;
            }
            .bottom-sheet-toggle-handle.hidden-via-js { opacity: 0; pointer-events: none; }
            .bottom-sheet-toggle-handle i { font-size: 1.5em; color: #666; transition: transform 0.3s ease-out; }
            .bottom-sheet-header {
                padding: 15px; display: flex; justify-content: space-between; align-items: center;
                border-bottom: 1px solid #eee; background-color: #f9f9f9;
                cursor: grab;
                user-select: none;
                position: relative; min-height: 20px; z-index: 1;
            }
            .bottom-sheet-header h4 {
                margin: 0; text-align: left; line-height: 1.2; color: #333; font-size: 1.2em;
                flex-grow: 1;
            }
            .bottom-sheet-expanded {
                display: none; flex-direction: column;
                height: auto;
                overflow: hidden;
                flex-grow: 0;
            }
            .bottom-sheet.expanded .bottom-sheet-expanded {
                display: flex;
                flex-grow: 1;
            }
            .bottom-sheet-content {
                flex-grow: 0;
                padding: 0 50px;
                overflow-y: auto;
                -webkit-overflow-scrolling: touch;
                margin: 0;
            }
            #bottom-sheet-content-area p {
                margin-block-start: 0 !important; margin-bottom: 0 !important; margin-block-end: 0 !important;
            }
            .bottom-sheet-actions {
                display: flex;
                flex-direction: column;
                padding: 10px;
                border-top: 1px solid #eee;
                width: 100%;
                box-sizing: border-box;
                flex-shrink: 0;
            }
            .expanded-actions-container {
                display: none;
                flex-grow: 1;
                justify-content: flex-start;
                align-items: center;
                margin-bottom: 10px;
            }
            .bottom-sheet.expanded .expanded-actions-container {
                display: flex;
            }
            .ctrl-button {
                display: flex; align-items: center; justify-content: center;
                width: 40px; height: 40px; border-radius: 50%;
                font-size: 1.2em; cursor: pointer; box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                flex-shrink: 0;
                margin: 0 5px;
            }
            .ctrl-button.disabled {
                background-color: #ccc !important;
                color: #888 !important;
                cursor: not-allowed !important;
                box-shadow: none !important;
            }
            .bottom-sheet-add-button { background-color: #28a745; color: white; }
            .bottom-sheet-edit-button { background-color: #ffc107; color: #212529; }
            .btn {
                padding: 10px 15px; border-radius: 5px; border: none; cursor: pointer;
                font-size: 1em; box-sizing: border-box;
            }
            .btn.primary { background-color: #28a745; color: white; }
            .btn.secondary { background-color: pink; color: black; }
            .hidden { display: none !important; }
            .bottom-sheet-main-actions {
                display: flex;
                gap: 10px;
                width: 100%;
                box-sizing: border-box;
            }
            .bottom-sheet-main-actions .btn {
                flex-grow: 1;
                min-width: 0;
            }
            .bottom-sheet-main-actions .btn.secondary {
                background-color: #dc3545;
                color: white;
            }
            #fallback-button {
                flex-grow: 1;
                background-color: #511ba6ff;
                width: 100%;
            }
            .bottom-sheet-nav-button {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                width: 35px;
                height: 35px;
                background-color: rgba(255, 255, 255, 0.8);
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                z-index: 10;
            }
            .bottom-sheet-nav-button.nav-left {
                left: 5px;
            }
            .bottom-sheet-nav-button.nav-right {
                right: 5px;
            }
            .bottom-sheet-nav-button i {
                font-size: 1.2em;
                color: #333;
            }
            .bottom-sheet-nav-button.disabled {
                opacity: 0.3;
                pointer-events: none;
            }
            .bottom-sheet.expanded .bottom-sheet-header .bottom-sheet-nav-button {
                display: flex;
            }
            .bottom-sheet-header .bottom-sheet-nav-button,
            .hidden-via-js {
                display: none !important;
            }
            .read-biography-btn {
                font-size: inherit;
                line-height: 1 !important;
                margin: 0;
                padding: 0 !important;
                height: auto !important;
                width: auto !important;
                vertical-align: middle;
            }
            .poi-list-item {
                margin: 0 !important;
                line-height: 1.3;
            }
            .poi-list-item p {
                margin: 0;
                padding: 0;
            }
        `;

        this._injectCSS();
        this._injectHTML();
        this.wrapper = document.getElementById(this.wrapperId);
        this.bottomSheet = document.getElementById(this.elementId);
        this.contentArea = document.getElementById(this.contentAreaId);
        this.actionsArea = document.getElementById(this.actionsAreaId);
        this.toggleHandle = this.wrapper.querySelector('.bottom-sheet-toggle-handle');
        this.HeaderTextElement = document.getElementById('bottom-sheet-header-text');
        this.expandedContainer = this.bottomSheet.querySelector('.bottom-sheet-expanded');
        this.navPrevButton = document.getElementById('nav-prev-button');
        this.navNextButton = document.getElementById('nav-next-button');
        this._expandedActionsContainer = this.bottomSheet.querySelector('.expanded-actions-container');
        this._caretakerContainer = document.getElementById('caretaker-checkbox-container');
        this._caretakerCheckbox = document.getElementById('caretaker-checkbox');
        this._caretakerLabel = document.getElementById('caretaker-label');
        this.addButton = document.getElementById('add-stolperstein-button');
        this.editButton = document.getElementById('edit-stolperstein-button');
        this._mainActionDiv = document.getElementById('bottom-sheet-main-actions');
        this._poiCleanButton = document.getElementById('poi-clean-button');
        this._poiDirtyButton = document.getElementById('poi-dirty-button');
        this._clusterCleanButton = document.getElementById('cluster-clean-button');
        this._clusterDirtyButton = document.getElementById('cluster-dirty-button');
        this._fallbackButton = document.getElementById('fallback-button');

        if (!this.wrapper || !this.bottomSheet || !this.contentArea || !this.actionsArea || !this.toggleHandle || !this.HeaderTextElement || !this._expandedActionsContainer || !this._mainActionDiv || !this._fallbackButton || !this._poiCleanButton || !this._clusterCleanButton) {
            console.error("Fehler: Mindestens ein Bottom Sheet DOM-Element wurde nicht gefunden. Bitte HTML-IDs/Klassen prüfen!");
        }

        this._addEventListeners();
        this._addSwipeListeners();
        this.close();
    }

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

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

 _addSwipeListeners() {
    const header = this.bottomSheet.querySelector('.bottom-sheet-header');
    if (!header) return;

    const SWIPE_THRESHOLD = this._swipeThreshold || 30; // px Bewegung bis Aktion
    let startX = 0, startY = 0;
    let isDragging = false;
    let swipeDirection = null;

    // ----- TOUCH HANDLER -----
    const onTouchStart = (e) => {
        startX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
        isDragging = true;
        swipeDirection = null;
    };

    const onTouchMove = (e) => {
        if (!isDragging) return;
        const currentX = e.touches[0].clientX;
        const currentY = e.touches[0].clientY;
        const deltaX = currentX - startX;
        const deltaY = currentY - startY;

        // Richtung festlegen, wenn noch unklar
        if (!swipeDirection) {
            if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 10) {
                swipeDirection = 'vertical';
            } else if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 10) {
                swipeDirection = 'horizontal';
            }
        }

        // bei erkanntem Swipe Scrollen verhindern
        if (swipeDirection) e.preventDefault();
    };

    const onTouchEnd = (e) => {
        if (!isDragging) return;
        isDragging = false;

        const endY = e.changedTouches[0].clientY;
        const deltaY = endY - startY;

        if (swipeDirection === 'vertical') {
            if (deltaY > SWIPE_THRESHOLD) {
                this.setSheetState(false); // nach unten → schließen
            } else if (deltaY < -SWIPE_THRESHOLD) {
                this.setSheetState(true); // nach oben → öffnen
            }
        } else if (
            swipeDirection === 'horizontal' &&
            typeof this._onHeaderSwipeHorizontal === 'function'
        ) {
            const endX = e.changedTouches[0].clientX;
            this._onHeaderSwipeHorizontal(endX > startX ? 'PREVIOUS' : 'NEXT');
        }

        swipeDirection = null;
    };

    // ----- MOUSE HANDLER -----
    const onMouseDown = (e) => {
        startX = e.clientX;
        startY = e.clientY;
        isDragging = true;
        swipeDirection = null;
        header.style.cursor = 'grabbing';
        header.style.userSelect = 'none';

        // globale Listener hinzufügen
        document.addEventListener('mousemove', onMouseMove, { passive: false });
        document.addEventListener('mouseup', onMouseUp, { passive: false });
    };

    const onMouseMove = (e) => {
        if (!isDragging) return;

        const currentX = e.clientX;
        const currentY = e.clientY;
        const deltaX = currentX - startX;
        const deltaY = currentY - startY;

        if (!swipeDirection) {
            if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 5) {
                swipeDirection = 'vertical';
            } else if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 5) {
                swipeDirection = 'horizontal';
            }
        }

        if (swipeDirection) e.preventDefault();
    };

    const onMouseUp = (e) => {
        if (!isDragging) return;
        isDragging = false;

        const endY = e.clientY;
        const deltaY = endY - startY;

        if (swipeDirection === 'vertical') {
            if (deltaY > SWIPE_THRESHOLD) {
                this.setSheetState(false); // nach unten
            } else if (deltaY < -SWIPE_THRESHOLD) {
                this.setSheetState(true); // nach oben
            }
        } else if (
            swipeDirection === 'horizontal' &&
            typeof this._onHeaderSwipeHorizontal === 'function'
        ) {
            const endX = e.clientX;
            this._onHeaderSwipeHorizontal(endX > startX ? 'PREVIOUS' : 'NEXT');
        }

        swipeDirection = null;
        header.style.cursor = '';
        header.style.userSelect = '';

        // globale Listener wieder entfernen
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
    };

    // ----- Event Listener registrieren -----
    header.addEventListener('touchstart', onTouchStart, { passive: true });
    header.addEventListener('touchmove', onTouchMove, { passive: false });
    header.addEventListener('touchend', onTouchEnd, { passive: true });

    header.addEventListener('mousedown', onMouseDown, { passive: false });
}


    _addEventListeners() {
        const header = this.bottomSheet.querySelector('.bottom-sheet-header');
        if (header) {
            header.addEventListener('click', (event) => {
                if (this._headerClickCallback && typeof this._headerClickCallback === 'function') {
                    console.log("Header geklickt, rufe externen Callback auf.");
                    this._headerClickCallback();
                } else {
                    console.warn("Header-Klick-Callback ist nicht definiert.");
                }
            });
        }
        if (this.toggleHandle) {
            this.toggleHandle.addEventListener('click', (event) => {
                event.stopPropagation();
                if (this.isOpen()) {
                    this.setSheetState(!this.isExpanded);
                }
            });
        }
        if (this.addButton) {
            this.addButton.addEventListener('click', (event) => {
                event.stopPropagation();
                if (typeof this._addStoneClickCallback === 'function' && this._currentCoords) {
                    this._addStoneClickCallback(this._currentCoords);
                } else {
                    console.warn("Add Stone Callback nicht definiert oder Koordinaten fehlen.");
                }
            });
        }
        if (this.editButton) {
            this.editButton.addEventListener('click', (event) => {
                event.stopPropagation();
                console.log("Edit Button geklickt!");
            });
        }
    }

    onResize(callback) {
        if (typeof callback === 'function') {
            this._onResizeCallback = callback;
        }
    }

    onClose(callback) {
        if (typeof callback === 'function') {
            this.closeCallbacks.push(callback);
        }
    }

    onHeaderSwipeHorizontal(callback) {
        this._onHeaderSwipeHorizontal = callback;
    }

    onAddStoneClick(callback) {
        if (typeof callback === 'function') {
            this._addStoneClickCallback = callback;
        } else {
            console.error("BsUI: Der übergebene onAddStoneClick-Callback ist keine Funktion.");
            this._addStoneClickCallback = null;
        }
    }

    setSheetState(expand) {
        if (this.isExpanded === expand) {
            return;
        }
        this.isExpanded = expand;
        if (this.bottomSheet && this.wrapper && this.toggleHandle) {
            if (this.isExpanded) {
                this.bottomSheet.classList.add('expanded');
                this.wrapper.classList.add('expanded');
                this.toggleHandle.querySelector('i').style.transform = 'rotate(180deg)';
                if (this._onResizeCallback) {
                    this._onResizeCallback();
                }
            } else {
                this.bottomSheet.classList.remove('expanded');
                this.wrapper.classList.remove('expanded');
                this.toggleHandle.querySelector('i').style.transform = 'rotate(0deg)';
            }
        }
    }

    isSheetExpanded() {
        return this.isExpanded;
    }

    open(contentRef = null) {
        this.contentRef = contentRef;
        if (this.wrapper) {
            this.wrapper.classList.remove('hidden');
            this.wrapper.classList.add('open');
            this.setSheetState(this.isExpanded);
            if (this._onResizeCallback) {
                this._onResizeCallback();
            }
        }
    }

    close() {
        if (this.wrapper) {
            setTimeout(() => {
                this.wrapper.classList.remove('open');
                this.wrapper.classList.add('hidden');
            }, 300);
            this.HeaderTextElement.innerHTML = '';
            this.contentArea.innerHTML = '';
            this.setNavButtonsState(false, false);
            this.setActions({
                showCaretaker: false,
                isCaretaker: false,
                caretakerLabelText: '',
                showAddButton: false,
                showEditButton: false,
                showMainActionDiv: false,
                showFallbackButton: false,
            });
            this._currentCoords = null;
            this._displayedObject = null;
            this.contentRef = null;
            if (this.closeCallbacks) {
                this.closeCallbacks.forEach(callback => {
                    try {
                        callback();
                    } catch (e) {
                        console.error("Fehler beim Ausführen eines onClose-Callbacks:", e);
                    }
                });
            }
        }
    }

    isOpen() {
        if (!this.wrapper) {
            return false;
        }
        return this.wrapper.classList.contains('open') && !this.wrapper.classList.contains('hidden');
    }

    setActions(options) {
        this._caretakerContainer.classList.add('hidden');
        this.addButton.classList.add('hidden');
        this.editButton.classList.add('hidden');
        this._mainActionDiv.classList.add('hidden');
        this._poiCleanButton.classList.add('hidden');
        this._poiDirtyButton.classList.add('hidden');
        this._clusterCleanButton.classList.add('hidden');
        this._clusterDirtyButton.classList.add('hidden');
        this._fallbackButton.classList.add('hidden');

        if (options.showCaretaker) {
            this._caretakerContainer.classList.remove('hidden');
            this._caretakerCheckbox.checked = options.isCaretaker;
            this._caretakerLabel.textContent = options.caretakerLabelText;
        }

        if (options.showMainActionDiv || options.showFallbackButton) {
            this._mainActionDiv.classList.remove('hidden');
        }

        if (options.showCleanButton) {
            this._poiCleanButton.classList.remove('hidden');
        }
        if (options.showDirtyButton) {
            this._poiDirtyButton.classList.remove('hidden');
        }

        if (options.showAddButton) {
            this.addButton.classList.remove('hidden');
            this.addButton.classList.remove('disabled');
        } else {
            this.addButton.classList.add('hidden');
            this.addButton.classList.add('disabled');
        }
        if (options.showEditButton) {
            this.editButton.classList.remove('hidden');
            this.editButton.classList.remove('disabled');
        } else {
            this.editButton.classList.add('hidden');
            this.editButton.classList.add('disabled');
        }
    }

    setCoords(coords) {
        if (coords && typeof coords.lat === 'number' && typeof coords.lng === 'number') {
            this._currentCoords = { lat: coords.lat, lng: coords.lng };
        } else {
            this._currentCoords = { lat: null, lng: null };
        }
    }

    setBsHeaderText(name) {
        if (this.HeaderTextElement) {
            this.HeaderTextElement.innerHTML = name;
        }
    }

    setContent(contentHtml) {
        if (this.contentArea) {
            this.contentArea.innerHTML = contentHtml;
        }
    }

    getCoords() {
        if (this._currentCoords && this._currentCoords.lat !== null && this._currentCoords.lng !== null) {
            return { lat: this._currentCoords.lat, lng: this._currentCoords.lng };
        }
        return null;
    }

    contains(targetElement) {
        return this.wrapper && this.wrapper.contains(targetElement);
    }

    onHeaderClick(panToCallback, markers) {
        if (typeof panToCallback === 'function' && markers) {
            this._headerClickCallback = () => {
                if (!this._displayedObject) {
                    return;
                }
                if (this._displayedObject.getAllChildMarkers) {
                    const firstMarkerInCluster = this._displayedObject.getAllChildMarkers()[0];
                    if (firstMarkerInCluster) {
                        markers.zoomToShowLayer(firstMarkerInCluster, () => {
                            panToCallback();
                        });
                    }
                } else {
                    markers.zoomToShowLayer(this._displayedObject, () => {
                        panToCallback();
                    });
                }
            };
        }
    }

    getDisplayCoords() {
        if (this._displayedObject && typeof this._displayedObject.getLatLng === 'function') {
            return this._displayedObject.getLatLng();
        }
        return null;
    }

    setClickedObject(objectToDisplay) {
        this._displayedObject = objectToDisplay;
    }

    getDisplayedObject() {
        return this._displayedObject;
    }

    openWithMarker(marker) {
        if (!marker) {
            console.error("openWithMarker: Marker ist null oder nicht definiert.");
            return;
        }
        this.setClickedObject(marker);
        const data = marker.options.data;
        this.setCoords({ lat: data.original_lat, lng: data.original_lon });
        this.open(marker);
    }

    setNavButtonsState(canGoBack, canGoForward) {
        const shouldBeVisible = canGoBack || canGoForward;
        if (this.navPrevButton) {
            if (shouldBeVisible) {
                this.navPrevButton.classList.remove('hidden-via-js');
            } else {
                this.navPrevButton.classList.add('hidden-via-js');
            }
            if (canGoBack) {
                this.navPrevButton.classList.remove('disabled');
            } else {
                this.navPrevButton.classList.add('disabled');
            }
        }
        if (this.navNextButton) {
            if (shouldBeVisible) {
                this.navNextButton.classList.remove('hidden-via-js');
            } else {
                this.navNextButton.classList.add('hidden-via-js');
            }
            if (canGoForward) {
                this.navNextButton.classList.remove('disabled');
            } else {
                this.navNextButton.classList.add('disabled');
            }
        }
    }
}

export function readBiography(url, utterance, onendCallback) {
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Netzwerk-Antwort war nicht ok');
            }
            return response.text();
        })
        .then(text => {
            utterance.text = text;
        })
        .catch(error => {
            console.error('Fehler beim Abrufen der Biografie:', error);
            utterance.text = 'Entschuldigung, die Biografie konnte nicht geladen werden.';
        })
        .finally(() => {
            if (onendCallback) {
                onendCallback();
            }
        });
}

export async function getBiographyText(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Netzwerk-Antwort war nicht ok: ${response.statusText}`);
        }
        const htmlText = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlText, 'text/html');
        const contentContainer = doc.querySelector('.biography-text .field__item');
        if (contentContainer) {
            console.log('DEBUG: Biografie-Text erfolgreich geparst und gefunden.');
            return contentContainer.textContent.trim();
        } else {
            console.error('FEHLER: Biografie-Container nicht gefunden. Überprüfe den HTML-Selektor.');
            return 'Entschuldigung, der Biografie-Text konnte nicht auf der Seite gefunden werden.';
        }
    } catch (error) {
        console.error('Fehler beim Abrufen oder Verarbeiten der Biografie:', error);
        return 'Entschuldigung, die Biografie konnte nicht geladen werden.';
    }
}

let isSpeaking = false;

export function cancelSpeech() {
    isSpeaking = false;
    window.speechSynthesis.cancel();
}

export async function speakChunks(text, lang) {
    if (isSpeaking) {
        return;
    }
    isSpeaking = true;
    const sentences = text.split(/(?<=[.?!;])\s*/);
    for (const sentence of sentences) {
        if (!isSpeaking) break;
        if (sentence.trim() === '') continue;
        await new Promise(resolve => {
            const utterance = new SpeechSynthesisUtterance(sentence.trim());
            utterance.lang = lang;
            utterance.onerror = function (event) {
                console.error('Sprachfehler im Chunk:', event.error);
                resolve();
            };
            utterance.onend = function () {
                resolve();
            };
            window.speechSynthesis.speak(utterance);
        });
    }
    isSpeaking = false;
}
