/**
 * @fileoverview bs-gen-ui.js
 * Verwaltet das BottomSheet UI, die Wisch-Gesten und die Integration der Sprachausgabe.
 */

import { showToast } from "./sc-utilities.js";
import { getMarkers } from "./map-markers-co.js";
import { getPoiData } from "./poi-store.js";

// Import des zentralen Sprach-Services
import { cancelSpeech } from "./poi-speech-service.js";

export class BsUI {
    static instance = null;
    _displayedObject = null;
    isExpanded = false;
    _currentCoords = null;
    
    // Zentraler Speicher für die Adresse (wichtig für handleSaveStone)
    currentAddress = {
        street: '',
        houseNr: '',
        localDistrict: ''
    };

    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">Adresse aufsuchen, um den Zustand zu erfassen</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: 100px; 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 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-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;
            }
            .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; }
            #fallback-button { flex-grow: 1; background-color: #511ba6ff; width: 100%; color: white; }
            .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.disabled { opacity: 0.3; pointer-events: none; }
            .hidden-via-js { display: none !important; }
        `;

        this._injectCSS();
        this._injectHTML();

        // DOM Referenzen
        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.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();
    }

    /**
     * Setzt die Adressdaten am BottomSheet (wichtig für handleSaveStone).
     */
    updateAddress(street, houseNr, localDistrict) {
        this.currentAddress = {
            street: street || '',
            houseNr: houseNr || '',
            localDistrict: localDistrict || ''
        };
    }

    _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;
        let startX = 0, startY = 0;
        let isDragging = false;
        let swipeDirection = null;

        const onStart = (x, y) => {
            startX = x; startY = y;
            isDragging = true; swipeDirection = null;
        };

        const onMove = (e, currentX, currentY) => {
            if (!isDragging) return;
            const deltaX = currentX - startX;
            const deltaY = currentY - startY;

            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';
            }
            if (swipeDirection) e.preventDefault();
        };

        const onEnd = (endX, endY) => {
            if (!isDragging) return;
            isDragging = false;
            const deltaY = endY - startY;

            if (swipeDirection === 'vertical') {
                if (deltaY > SWIPE_THRESHOLD) this.setSheetState(false);
                else if (deltaY < -SWIPE_THRESHOLD) this.setSheetState(true);
            } else if (swipeDirection === 'horizontal' && this._onHeaderSwipeHorizontal) {
                this._onHeaderSwipeHorizontal(endX > startX ? 'PREVIOUS' : 'NEXT');
            }
        };

        header.addEventListener('touchstart', (e) => onStart(e.touches[0].clientX, e.touches[0].clientY), { passive: true });
        header.addEventListener('touchmove', (e) => onMove(e, e.touches[0].clientX, e.touches[0].clientY), { passive: false });
        header.addEventListener('touchend', (e) => onEnd(e.changedTouches[0].clientX, e.changedTouches[0].clientY), { passive: true });

        header.addEventListener('mousedown', (e) => {
            onStart(e.clientX, e.clientY);
            const mouseMove = (me) => onMove(me, me.clientX, me.clientY);
            const mouseUp = (ue) => {
                onEnd(ue.clientX, ue.clientY);
                document.removeEventListener('mousemove', mouseMove);
                document.removeEventListener('mouseup', mouseUp);
            };
            document.addEventListener('mousemove', mouseMove, { passive: false });
            document.addEventListener('mouseup', mouseUp, { passive: false });
        });
    }

    _addEventListeners() {
        const header = this.bottomSheet.querySelector('.bottom-sheet-header');
        if (header) {
            header.addEventListener('click', () => {
                if (this._headerClickCallback) this._headerClickCallback();
            });
        }
        this.toggleHandle.addEventListener('click', (e) => {
            e.stopPropagation();
            if (this.isOpen()) this.setSheetState(!this.isExpanded);
        });
        this.addButton.addEventListener('click', (e) => {
            e.stopPropagation();
            if (this._addStoneClickCallback && this._currentCoords) this._addStoneClickCallback(this._currentCoords);
        });
    }

    setSheetState(expand) {
        if (this.isExpanded === expand) return;
        this.isExpanded = expand;
        this.bottomSheet.classList.toggle('expanded', expand);
        this.wrapper.classList.toggle('expanded', expand);
        this.toggleHandle.querySelector('i').style.transform = expand ? 'rotate(180deg)' : 'rotate(0deg)';
        if (this._onResizeCallback) this._onResizeCallback();
    }

    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) {
            cancelSpeech(); // Stoppt Audio sofort

            setTimeout(() => {
                this.wrapper.classList.remove('open');
                this.wrapper.classList.add('hidden');
                this.updateAddress('', '', '');
                this._currentCoords = null;
            }, 300);

            this.HeaderTextElement.innerHTML = '';
            this.contentArea.innerHTML = '';
            this.setNavButtonsState(false, false);
            this.setActions({ showCaretaker: false, showAddButton: false });

            if (this.closeCallbacks) {
                this.closeCallbacks.forEach(cb => { try { cb(); } catch (e) {} });
            }
        }
    }

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

    setActions(options) {
        const elements = [this._caretakerContainer, this.addButton, this.editButton, this._mainActionDiv, this._poiCleanButton, this._poiDirtyButton, this._clusterCleanButton, this._clusterDirtyButton, this._fallbackButton];
        elements.forEach(el => el?.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');
        if (options.showEditButton) this.editButton.classList.remove('hidden');
    }

    setCoords(coords) { this._currentCoords = coords ? { lat: coords.lat, lng: coords.lng } : null; }
    getCoords() { return this._currentCoords; }
    getDisplayCoords() {
        if (this._displayedObject && typeof this._displayedObject.getLatLng === 'function') return this._displayedObject.getLatLng();
        return this._currentCoords;
    }

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

    onHeaderClick(panToCallback) {
        this._headerClickCallback = () => {
            const markers = getMarkers();
            if (!markers || !this._displayedObject) return;
            const target = this._displayedObject.getAllChildMarkers ? this._displayedObject.getAllChildMarkers()[0] : this._displayedObject;
            markers.zoomToShowLayer(target, () => panToCallback());
        };
    }
// 1. Das aktuell angezeigte Objekt zurückgeben
    getDisplayedObject() {
        return this._displayedObject;
    }

    // 2. Das Objekt setzen (Wird beim Klick auf einen Marker/Cluster aufgerufen)
    setClickedObject(obj) { this._displayedObject = obj; }
    
    openWithMarker(marker) { if (marker) { this.setClickedObject(marker); this.open(marker); } }

    setNavButtonsState(prev, next) {
        const visible = prev || next;
        [this.navPrevButton, this.navNextButton].forEach(btn => {
            if (btn) btn.classList.toggle('hidden-via-js', !visible);
        });
        if (this.navPrevButton) this.navPrevButton.classList.toggle('disabled', !prev);
        if (this.navNextButton) this.navNextButton.classList.toggle('disabled', !next);
    }

    onResize(cb) { this._onResizeCallback = cb; }
    onClose(cb) { this.closeCallbacks.push(cb); }
    onHeaderSwipeHorizontal(cb) { this._onHeaderSwipeHorizontal = cb; }
    onAddStoneClick(cb) { this._addStoneClickCallback = cb; }
}