/**
 * @fileoverview address-sheet-ui.js
 * Managt die Benutzeroberfläche für die Adresssuche.
 */

import { mylog } from "./sc-utilities.js";
import { renderAddressSheetResults } from "./addrs-ui-render-results.js";
import { ScCloseButton } from './close-button.js';

const STATE_INPUT_ONLY = 'input-only';
const STATE_RESULTS_OPEN = 'results-open';

export class AddressSheetUI {

    searchInputCallbacks = [];
    guiLocationRequestedCallbacks = [];
    currentLocationSelectedCallbacks = [];
    nextDirtyStoneSelectedCallbacks = [];

    /** @type {ScCloseButton} */
    closeButtonComponent;

    constructor() {
        mylog("Address Sheet UI: Konstruktor gestartet.");

        this.panelHTML = `
            <div id="address-input-container" class="hidden"> 
                
                <div id="sc-static-actions-container">
                    <ul id="sc-static-actions-list" class="sc-address-results-list">
  
                        <li id="next-dirty-stone-item" class="sc-address-result-item" data-type="next-dirty-stone">
                            <div class="sc-address-result-icon"><i class="fas fa-broom" style="color: #dc3545;"></i></div>
                            <div class="sc-address-result-text">
                                <div class="sc-address-result-line" style="color: #dc3545; font-weight: bold;">Wo kann ich putzen?</div>
                            </div>
                        </li>
                                              <li id="current-location-item" class="sc-address-result-item" data-type="current-location">
                            <div class="sc-address-result-icon"><i class="fas fa-location-crosshairs"></i></div>
                            <div class="sc-address-result-text">
                                <div id="current-location-display-text" class="sc-address-result-line">Standortfreigabe deaktiviert</div>
                            </div>
                        </li>
                    </ul>
                    <div id="address-search-close-button-wrapper"></div>
                </div>

                <div class="sc-address-divider"></div>

                <div id="address-input-header">
                    <input type="text" id="address-search-input" placeholder="Vor/Nachname oder Straße/Nr finden..." autocomplete="off" />
                </div>

                <div id="address-results-sheet" class="hidden">
                    <ul id="sc-dynamic-results-list" class="sc-address-results-list"></ul>
                </div>
            </div>
        `;

        this.panelCSS = `
            #address-input-container {
                position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
                width: 50%; max-width: 500px; background-color: #fff;
                border-radius: 25px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
                z-index: 1000; transition: all 0.3s ease-in-out;
                overflow: hidden; display: flex; flex-direction: column;
                max-height: 90vh;
            }
            #address-input-container.fullscreen-mode {
                top: 0; left: 0; width: 100%; height: 100dvh; 
                max-width: none; border-radius: 0; transform: translateX(0);
                z-index: 10002; max-height: 100dvh;
            }

            /* Container für Actions und den Close-Button */
            #sc-static-actions-container { 
                background: #fff; 
                display: flex;
                align-items: flex-start; /* Items oben ausrichten */
                position: relative;
                padding: 5px 0;
            }

            #sc-static-actions-list {
                flex-grow: 1;
            }

            /* Close Button Positionierung zentriert zum ersten Li (ca. 48px hoch) */
            #address-search-close-button-wrapper {
                margin-top: 6px; /* Feinjustierung für optische Mitte des ersten Items */
                margin-right: 15px;
                display: flex;
                align-items: center;
                height: 48px; /* Höhe eines Standard-Listitems */
            }
            
            .sc-address-divider {
                height: 1px;
                background-color: #eee;
                margin: 0 15px;
            }

            #address-input-header {
                display: flex; align-items: center; padding: 10px 15px;
                min-height: 60px; box-sizing: border-box; background-color: #fff;
            }
            
            #address-search-input {
                flex-grow: 1; padding: 12px 18px; border: none;
                border-radius: 25px; font-size: 1.1em; outline: none;
                background: #f5f5f5;
            }

            #address-results-sheet {
                flex-grow: 1; background-color: white; overflow-y: auto; padding: 0;
            }

            .sc-address-results-list { padding: 0; margin: 0; list-style: none; }
            .sc-address-result-item {
                display: flex; align-items: center; padding: 14px 20px;
                cursor: pointer; transition: background-color 0.2s ease;
            }
            .sc-address-result-item:hover:not(.disabled-location) { background-color: #f9f9f9; }
            .sc-address-result-icon { font-size: 1.2em; color: #555; margin-right: 12px; width: 25px; text-align: center; }
            .sc-address-result-text { flex-grow: 1; }
            
            .sc-address-result-item.enabled-location .sc-address-result-line { color: #007bff; font-weight: bold; }
            .sc-address-result-item.disabled-location { cursor: not-allowed; opacity: 0.5; }
            .hidden { display: none !important; }
        `;

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

        this.closeButtonComponent = new ScCloseButton('address-search-close-button');
        const wrapper = document.getElementById('address-search-close-button-wrapper');
        if (wrapper) wrapper.appendChild(this.closeButtonComponent.getElement());

        this.addressInputContainer = document.getElementById('address-input-container');
        this.addressSearchInput = document.getElementById('address-search-input');
        this.addressResultsSheet = document.getElementById('address-results-sheet');
        this.currentLocationDisplayTextElement = document.getElementById('current-location-display-text');
        this.currentLocationItem = document.getElementById('current-location-item');
        this.nextDirtyStoneItem = document.getElementById('next-dirty-stone-item');
        this.dynamicResultsList = document.getElementById('sc-dynamic-results-list');

        this._currentState = STATE_INPUT_ONLY;
        this._applyState();
        this._addEventListeners();
        this.updateCurrentLocationButton(false);
    }

    _injectCSS() {
        if (!document.getElementById('sc-address-sheet-styles')) {
            const style = document.createElement('style');
            style.id = 'sc-address-sheet-styles';
            style.textContent = this.panelCSS;
            document.head.appendChild(style);
        }
    }

    _injectHTML() {
        if (!document.getElementById('address-input-container')) {
            document.body.insertAdjacentHTML('beforeend', this.panelHTML);
        }
    }

    _addEventListeners() {
        this.addressSearchInput.addEventListener('input', () => {
            const query = this.addressSearchInput.value.trim();
            this.searchInputCallbacks.forEach(cb => cb(query));
        });

        this.closeButtonComponent.onClick(() => this.closeResults());

        this.addressInputContainer.addEventListener('click', (event) => {
            const listItem = event.target.closest('.sc-address-result-item');
            if (!listItem) return;

            const type = listItem.dataset.type;

            if (type === 'current-location' && !listItem.classList.contains('disabled-location')) {
                this.currentLocationSelectedCallbacks.forEach(cb => cb());
                this.closeResults();
            }
            else if (type === 'next-dirty-stone') {
                this.nextDirtyStoneSelectedCallbacks.forEach(cb => cb());
                this.closeResults();
            }
            else if (!type || (type !== 'current-location' && type !== 'next-dirty-stone')) {
                const lat = parseFloat(listItem.dataset.lat);
                const lng = parseFloat(listItem.dataset.lng);
                if (!isNaN(lat) && !isNaN(lng)) {
                    this.guiLocationRequestedCallbacks.forEach(cb => cb({
                        lat, lng,
                        street: listItem.dataset.street,
                        houseNr: listItem.dataset.houseNr,
                        displayName: listItem.dataset.textToDisplay,
                        source: listItem.dataset.source,
                        gid: listItem.dataset.gid
                    }));
                    this.closeResults();
                }
            }
        });

        document.addEventListener('click', (event) => {
            if (this.isOpen() && !this.addressInputContainer.contains(event.target)) {
                if (!event.target.closest('#search-address-trigger')) {
                    this.closeResults();
                }
            }
        });
    }

    _applyState() {
        if (this._currentState === STATE_INPUT_ONLY) {
            this.addressInputContainer.classList.add('hidden');
            this.addressResultsSheet.classList.add('hidden');
            this.closeButtonComponent.hide();
            this.addressInputContainer.classList.remove('fullscreen-mode');
        } else {
            this.addressInputContainer.classList.remove('hidden');
            this.addressResultsSheet.classList.remove('hidden');
            this.closeButtonComponent.show();
            this.addressInputContainer.classList.add('fullscreen-mode');
            this.addressSearchInput.focus();
        }
    }

    openResults() {
        if (this._currentState !== STATE_RESULTS_OPEN) {
            this._currentState = STATE_RESULTS_OPEN;
            this.addressSearchInput.value = '';
            this.setInitialResultsContent();
            this._applyState();
        }
    }

    closeResults() {
        if (this._currentState !== STATE_INPUT_ONLY) {
            this._currentState = STATE_INPUT_ONLY;
            this.addressSearchInput.value = '';
            this._applyState();
        }
    }

    setInitialResultsContent() {
        if (this.dynamicResultsList) this.dynamicResultsList.innerHTML = '';
        const placeholder = document.getElementById('address-search-placeholder');
        if (placeholder) placeholder.classList.remove('hidden');
    }

    renderResults(data) {
        const placeholder = document.getElementById('address-search-placeholder');
        if (placeholder) placeholder.classList.add('hidden');
        renderAddressSheetResults(this.dynamicResultsList, this.addressSearchInput, data);
    }

    updateCurrentLocationButton(isEnabled) {
        if (this.currentLocationDisplayTextElement && this.currentLocationItem) {
            if (isEnabled) {
                this.currentLocationDisplayTextElement.textContent = 'Zum aktuellen Standort';
                this.currentLocationItem.classList.add('enabled-location');
                this.currentLocationItem.classList.remove('disabled-location');
                this.currentLocationItem.style.pointerEvents = 'auto';
                if (this.nextDirtyStoneItem) this.nextDirtyStoneItem.classList.remove('hidden');
            } else {
                this.currentLocationDisplayTextElement.textContent = 'Standortfreigabe deaktiviert';
                this.currentLocationItem.classList.add('disabled-location');
                this.currentLocationItem.classList.remove('enabled-location');
                this.currentLocationItem.style.pointerEvents = 'none';
                if (this.nextDirtyStoneItem) this.nextDirtyStoneItem.classList.add('hidden');
            }
        }
    }

    onSearchInput(callback) { if (typeof callback === 'function') this.searchInputCallbacks.push(callback); }
    searchResultSelected(callback) { if (typeof callback === 'function') this.guiLocationRequestedCallbacks.push(callback); }
    onCurrentLocationSelected(callback) { if (typeof callback === 'function') this.currentLocationSelectedCallbacks.push(callback); }
    onNextDirtyStoneSelected(callback) { if (typeof callback === 'function') this.nextDirtyStoneSelectedCallbacks.push(callback); }

    isOpen() { return this._currentState === STATE_RESULTS_OPEN; }
}