/**
 * @fileoverview address-sheet-ui.js
 * Vollständige Fassung inklusive aller Styles & HTML.
 * Optimiert für iOS: Fokus & Tastatur funktionieren, Editieren bleibt möglich.
 */

import { mylog } from "./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 {
    searchInputCb = [];
    guiLocationRequestedCallbacks = [];
    currentLocationSelectedCallbacks = [];
    nextDirtyStoneSelectedCallbacks = [];

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

    constructor() {
        mylog("Address Sheet UI: Modal-Konstruktor (iPhone Optimized) gestartet.");

        this._savedScrollPos = undefined;

        this.panelHTML = `
    <div id="address-input-container" class="hidden">
        <div id="address-input-header">
            <div id="address-search-close-button-wrapper"></div>
            <form onsubmit="return false;" autocomplete="off">
                <input 
                    type="search"
                    id="address-search-input" 
                    placeholder="Suchen nach..." 
                    autocomplete="off" 
                    autocorrect="off"
                    autocapitalize="off"
                    spellcheck="false"
                    data-form-type="other"
                />
                <i id="address-search-clear-x" class="fas fa-times-circle hidden"></i>
            </form>
        </div>

        <div id="sc-search-validation-hint" class="hide-hint" style="padding: 0px 15px 0px 25px !important; background: #f5f5f5;">
            <div class="hint-text">
                Straße und Hausnummer <br>
                oder <br>Vor- und Nachname
            </div>
        </div>    
      
        <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-map-pin" style="color: #dc3545;"></i></div>
                    <div class="sc-address-result-text">
                        <div id="current-location-display-text" class="sc-address-result-line">Zum aktuellen Standort</div>
                    </div>
                </li>
            </ul>
        </div>

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

this.panelCSS = `
    .sc-modal-backdrop {
        position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
        background: rgba(0, 0, 0, 0.5); z-index: 10001;
    }
    .hide-hint { display: none !important; }
    #address-input-container {
        position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
        width: 95%; max-width: 550px; height: calc(100vh - 40px);
        background-color: #f5f5f5; border-radius: 20px; 
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4); z-index: 10002; 
        display: flex; flex-direction: column; overflow: hidden;
    }
    
    /* Header als Flex-Container für Input und Close-Button */
    #address-input-header { 
        padding: 15px; 
        background: #f5f5f5; 
        flex-shrink: 0; 
        position: relative; 
        display: flex; 
        align-items: center; 
    }
    
    /* Das Formular fungiert als Anker für das interne X */
    #address-input-header form { 
        margin: 0; 
        padding: 0; 
        position: relative; 
        flex-grow: 1; 
        margin-right: 45px; /* Platz für den äußeren Schließen-Button */
    }

    /* Das X im Suchfeld - Jetzt korrekt innerhalb des Inputs positioniert */
    #address-search-clear-x {
        position: absolute;
        right: 10px; 
        top: 50%;
        transform: translateY(-50%);
        font-size: 18px;
        color: #bbb;
        cursor: pointer;
        z-index: 11;
        transition: color 0.2s ease;
        padding: 5px;
        line-height: 1;
    }
    #address-search-clear-x:hover { color: #888; }

    #address-search-input {
        width: 100%; 
        padding: 12px 35px 12px 18px; /* Rechts 35px Platz für das X */
        border: 1px solid #e0e0e0; 
        border-radius: 25px; 
        font-size: 16px; 
        background: #fff; 
        outline: none; 
        -webkit-appearance: none; 
        appearance: none; 
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        box-sizing: border-box; /* Garantiert korrekte Breite inkl. Padding */
    }
    
    /* Der äußere Schließen-Button rechts oben */
    #address-search-close-button-wrapper { 
        position: absolute; 
        right: 15px; 
        top: 50%; 
        transform: translateY(-50%); 
        z-index: 10; 
    }

    #address-search-input:focus { -webkit-appearance: none; appearance: none; }
    #address-search-input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
    
    @supports (-webkit-touch-callout: none) {
        #address-search-input { font-size: 16px !important; }
    }

    #sc-search-validation-hint.hide-hint { display: none !important; }
    #sc-search-validation-hint { background: #f5f5f5; flex-shrink: 0; }
    #sc-search-validation-hint .hint-text { padding: 10px 15px 10px 25px; color: #666; font-size: 0.9rem; line-height: 1.5; }
    
    #sc-static-actions-container { padding: 10px 15px 15px 15px; flex-shrink: 0; background: #f5f5f5; display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }
    #sc-static-actions-list { width: 100%; display: flex; flex-direction: column; gap: 10px; align-items: flex-start; padding-left: 0; list-style: none; margin: 0; }
    #sc-static-actions-list .sc-address-result-item {
        display: inline-flex; align-items: center; padding: 12px 20px; cursor: pointer; 
        background: #fff; border-radius: 25px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        border: 1px solid #e0e0e0; transition: all 0.2s ease; width: auto; white-space: nowrap; list-style: none;
    }
    #sc-static-actions-list .sc-address-result-item:hover { background-color: #fafafa; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15); transform: translateY(-1px); }
    
    #address-results-sheet { flex-grow: 1; overflow-y: auto; background: #f5f5f5; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; padding: 10px 15px; }
    #sc-dynamic-results-list { list-style: none; padding: 0; margin: 0; }
    #sc-dynamic-results-list .sc-address-result-item {
        display: flex; align-items: flex-start; padding: 14px 18px; cursor: pointer; 
        background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border: 1px solid #e0e0e0; margin-bottom: 8px; transition: all 0.2s ease; list-style: none;
    }
    .sc-address-result-icon { font-size: 1.1em; color: #555; margin-right: 12px; width: 20px; text-align: center; flex-shrink: 0; }
    .sc-address-result-text { flex-grow: 1; line-height: 1.4; }
    .sc-address-result-line { font-size: 0.95rem; color: #333; }
    .hidden { display: none !important; }
`;

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

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

        this.addressInputContainer = document.getElementById('address-input-container');
        this.searchInputEl = document.getElementById('address-search-input');
        this.dynamicResultsList = document.getElementById('sc-dynamic-results-list');
        this.currentLocationDisplayTextElement = document.getElementById('current-location-display-text');
        this.currentLocationItem = document.getElementById('current-location-item');

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

    _injectCSS() {
        const style = document.createElement('style');
        style.id = 'sc-address-modal-styles-iphone-ready';
        style.textContent = this.panelCSS;
        document.head.appendChild(style);
    }

    _injectHTML() {
        if (!document.getElementById('address-input-container')) {
            document.body.insertAdjacentHTML('beforeend', this.panelHTML);
        }
    }
_addEventListeners() {
    const clearBtn = document.getElementById('address-search-clear-x');

    // 1. Logik beim Tippen (Ein-/Ausblenden des X)
    this.searchInputEl.addEventListener('input', () => {
        const query = this.searchInputEl.value.trim();
        
        if (query.length > 0) {
            clearBtn.classList.remove('hidden');
            this.updateActionsVisibility(true);
            this.setValidationHint(false);
        } else {
            clearBtn.classList.add('hidden');
            this.updateActionsVisibility(false);
            this.setValidationHint(true);
            if (this.dynamicResultsList) this.dynamicResultsList.innerHTML = '';
        }

        if (query.length < 3 && this.dynamicResultsList) {
            this.dynamicResultsList.innerHTML = '';
        }
        
        // Weitergabe an den Coordinator
        this.searchInputCb.forEach(cb => cb(query));
    });

    // 2. Klick-Logik für das X-Icon
    clearBtn.addEventListener('click', (e) => {
        // Wichtig, damit das Modal oder das Form-Submit nicht getriggert wird
        e.preventDefault();
        e.stopPropagation();

        // Feld leeren
        this.searchInputEl.value = '';
        
        // UI-Zustand zurücksetzen
        clearBtn.classList.add('hidden');
        if (this.dynamicResultsList) this.dynamicResultsList.innerHTML = '';
        this.updateActionsVisibility(false);
        this.setValidationHint(true);
        
        // Fokus behalten für neue Eingabe
        this.searchInputEl.focus();
        
        // Coordinator informieren, dass die Suche leer ist
        this.searchInputCb.forEach(cb => cb(''));
    });
     
        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') {
                this.currentLocationSelectedCallbacks.forEach(cb => cb());
                this.closeResults();
            } else if (type === 'next-dirty-stone') {
                this.nextDirtyStoneSelectedCallbacks.forEach(cb => cb());
                this.closeResults();
            } else if (type === 'location-selection') {
                const lat = parseFloat(listItem.dataset.lat);
                const lng = parseFloat(listItem.dataset.lng);
                const rawGid = listItem.dataset.gid;
                const gid_as_integer = (rawGid && rawGid !== "null") ? parseInt(rawGid, 10) : null;
                if (!isNaN(lat) && !isNaN(lng)) {
                    this.guiLocationRequestedCallbacks.forEach(cb => cb({
                        lat, lng, gid: gid_as_integer,
                        street: listItem.dataset.street,
                        houseNr: listItem.dataset.houseNr,
                        localDistrict: listItem.dataset.localDistrict, // ✅ NEU: Den Stadtteil mitgeben!
                        displayName: listItem.dataset.textToDisplay,
                        source: listItem.dataset.source
                    }));
                    this.closeResults();
                }
            }
        });

        // ⭐ iOS-FIX: Klick-Listener statt touchstart/focus-Blockern
        this.searchInputEl.addEventListener('click', () => {
            this.searchInputEl.focus();
        });
    }

    _applyState() {
        if (this._currentState === STATE_INPUT_ONLY) {
            this.addressInputContainer.classList.add('hidden');
            const b = document.querySelector('.sc-modal-backdrop');
            if (b) b.remove();

            document.body.style.position = '';
            document.body.style.overflow = '';

            if (this._savedScrollPos !== undefined) {
                window.scrollTo(0, this._savedScrollPos);
                this._savedScrollPos = undefined;
            }
        } else {
            this._savedScrollPos = window.pageYOffset || document.documentElement.scrollTop || 0;
            this.addressInputContainer.classList.remove('hidden');

            if (!document.querySelector('.sc-modal-backdrop')) {
                const b = document.createElement('div');
                b.className = 'sc-modal-backdrop';
                b.onclick = () => this.closeResults();
                document.body.appendChild(b);
            }

            document.body.style.position = 'fixed';
            document.body.style.top = `-${this._savedScrollPos}px`;
            document.body.style.left = '0';
            document.body.style.width = '100%';
            document.body.style.overflow = 'hidden';
        }
    }

    setValidationHint(show) {
        const hintEl = document.getElementById('sc-search-validation-hint');
        if (!hintEl) return;
        show ? hintEl.classList.remove('hide-hint') : hintEl.classList.add('hide-hint');
    }

    updateActionsVisibility(hasInput) {
        const container = document.getElementById('sc-static-actions-container');
        if (container) hasInput ? container.classList.add('hidden') : container.classList.remove('hidden');
    }

    openResults() {
        this._currentState = STATE_RESULTS_OPEN;
        this._applyState();

        const currentQuery = this.searchInputEl.value.trim();
        this.setValidationHint(currentQuery.length === 0);
        this.updateActionsVisibility(currentQuery.length > 0);

        // ⭐ FOKUS ERZWINGEN (für die Tastatur)
        this.searchInputEl.focus();

        if (currentQuery.length > 0) {
            // Text markieren statt select() für bessere iOS Kompatibilität
            setTimeout(() => {
                this.searchInputEl.setSelectionRange(0, 9999);
            }, 50);
        }

        requestAnimationFrame(() => {
            window.scrollTo(0, this._savedScrollPos || 0);
        });
    }

    closeResults() {
        this._currentState = STATE_INPUT_ONLY;
        this.searchInputEl.value = '';
        this._applyState();
    }

    renderResults(data) {
        renderAddressSheetResults(this.dynamicResultsList, this.searchInputEl, data);
    }

    updateCurrentLocationButton(isEnabled) {
        if (this.currentLocationDisplayTextElement) {
            this.currentLocationDisplayTextElement.textContent = isEnabled ? 'Zum aktuellen Standort' : 'Standort deaktiviert';
            this.currentLocationItem.style.opacity = isEnabled ? "1" : "0.5";
        }
    }
    updateNextDirtyStoneButton(isEnabled) {
        const item = document.getElementById('next-dirty-stone-item');
        if (item) {
            // Bei deaktiviertem Standort ausblenden oder halbtransparent machen
            item.style.display = isEnabled ? "inline-flex" : "none";
            // Alternativ: item.style.opacity = isEnabled ? "1" : "0.5";
        }
    }

    registerSearchInputCb(cb) { this.searchInputCb.push(cb); }
    searchResultSelected(cb) { this.guiLocationRequestedCallbacks.push(cb); }
    onCurrentLocationSelected(cb) { this.currentLocationSelectedCallbacks.push(cb); }
    onNextDirtyStoneSelected(cb) { this.nextDirtyStoneSelectedCallbacks.push(cb); }
    isOpen() { return this._currentState === STATE_RESULTS_OPEN; }
}