// insert-poi-ui.js
import { showToast } from './sc-utilities.js';

export class InsertPoiUI {
    constructor(buttonId, iconId, dependencies = {}) {
        this.buttonElement = document.getElementById(buttonId);
        this.iconElement = document.getElementById(iconId);
        this.onSaveCallback = dependencies.onSave;
        this.popupElement = null;
        this.coords = null; 
        this._setupButtonListener();
    }

    _setupButtonListener() {
        if (this.buttonElement) {
            this.buttonElement.addEventListener('click', () => {
                // Hinzufügen-Funktion benötigt Koordinaten vom Bottom Sheet
            });
        }
    }

    _setupNumberInputValidation() {
        // Diese Methode wird jetzt in showPopup() aufgerufen
        const birthYearInput = this.popupElement.querySelector("#birthYear");
        if (birthYearInput) {
            birthYearInput.addEventListener('input', (event) => {
                event.target.value = event.target.value.replace(/[^0-9]/g, '');
            });
        }
    }

    showPopup(stoneData = {}, coords = null) {
        if (this.popupElement) {
            this.closePopup();
        }

        if (!stoneData.id && !coords) {
            console.error("Fehler: Koordinaten sind obligatorisch, um einen neuen Stein hinzuzufügen.");
            return;
        }

        if (coords) {
            this.coords = coords;
        } else if (stoneData.id && stoneData.Lat && stoneData.Lon) {
            this.coords = { lat: stoneData.Lat, lng: stoneData.Lon };
        }

        this.popupElement = document.createElement('div');
        this.popupElement.id = 'add-stone-popup';
        this.popupElement.classList.add('add-stone-popup-overlay');
        
        this.popupElement.innerHTML = `
            <style>
                .add-stone-popup-overlay {
                    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                    background-color: rgba(0, 0, 0, 0.6); display: flex;
                    justify-content: center; align-items: center; z-index: 1000;
                }
                .add-stone-popup-content {
                    background-color: #fff; padding: 30px; border-radius: 10px;
                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3); width: 90%;
                    max-width: 400px; text-align: center; position: relative;
                    box-sizing: border-box;
                }
                .add-stone-popup-content h3 {
                    margin-top: 0; color: #333; margin-bottom: 20px;
                }
                .add-stone-popup-content label {
                    display: block; text-align: left; margin-bottom: 5px;
                    font-weight: bold; color: #555; width: 100%; box-sizing: border-box;
                }
                .add-stone-popup-content input, .add-stone-popup-content textarea {
                    width: 100%; padding: 10px; margin-bottom: 10px;
                    border: 1px solid #ccc; border-radius: 5px;
                    font-size: 1em; box-sizing: border-box;
                    background-color: #f8f8f8; color: #333; text-align: left;
                }
                .add-stone-popup-content textarea#stonePosition {
                    min-height: 80px; resize: vertical; overflow-y: auto;
                }
                .add-stone-popup-content .popup-buttons {
                    margin-top: 20px; display: flex;
                    justify-content: space-around; gap: 10px; flex-wrap: wrap;
                }
                .add-stone-popup-content button {
                    padding: 10px 20px; border: none; border-radius: 50px;
                    cursor: pointer; font-size: 1em; font-weight: bold;
                    transition: background-color 0.2s ease, transform 0.1s ease;
                    flex-grow: 1; min-width: 120px;
                }
                .add-stone-popup-content button:hover { transform: translateY(-2px); }
                .add-stone-popup-content button#saveStoneButton { background-color: #28a745; color: white; }
                .add-stone-popup-content button#saveStoneButton:hover { background-color: #218838; }
                .add-stone-popup-content button#closePopupButton { background-color: #dc3545; color: white; }
                .add-stone-popup-content button#closePopupButton:hover { background-color: #c82333; }
            </style>
            <div class="add-stone-popup-content">
                <h3>Stolperstein hinzufügen/bearbeiten</h3>
                <label for="firstName">Vorname:</label>
                <input type="text" id="firstName" name="firstName" required>
                <label for="lastName">Nachname:</label>
                <input type="text" id="lastName" name="lastName" required>
                <label for="birthYear">Geburtsjahr (1840 - 1945):</label>
                <input type="number" id="birthYear" name="birthYear" min="1840" max="1945" required>
                <label for="stonePosition">Besonderer Verlegeort:</label>
                <textarea id="stonePosition" name="stonePosition" placeholder="leer = 'vor der Haustür'" required></textarea>
                <div class="popup-buttons">
                    <button id="saveStoneButton">Speichern</button>
                    <button id="closePopupButton">Schließen</button>
                </div>
            </div>
        `;

                 
        document.body.appendChild(this.popupElement);

        if (Object.keys(stoneData).length > 0) {
            this.popupElement.querySelector("#firstName").value = stoneData.first_name || '';
            this.popupElement.querySelector("#lastName").value = stoneData.last_name || '';
            this.popupElement.querySelector("#birthYear").value = stoneData.year_of_birth || '';
            this.popupElement.querySelector("#stonePosition").value = stoneData.position || 'vor der Haustür';
        }

        this._setupNumberInputValidation();

        const saveButton = this.popupElement.querySelector('#saveStoneButton');
        const closeButton = this.popupElement.querySelector('#closePopupButton');
        
        if (saveButton) {
            saveButton.addEventListener('click', () => {
                const firstName = this.popupElement.querySelector("#firstName").value;
                const lastName = this.popupElement.querySelector("#lastName").value;
                const birthYearInput = this.popupElement.querySelector("#birthYear");
                const birthYear = parseInt(birthYearInput.value, 10);
                const stonePosition = this.popupElement.querySelector("#stonePosition").value;
                
                const minYear = parseInt(birthYearInput.min);
                const maxYear = parseInt(birthYearInput.max);

                if (isNaN(birthYear) || birthYear < minYear || birthYear > maxYear) {
                    alert(`Fehler: Das Geburtsjahr muss zwischen ${minYear} und ${maxYear} liegen.`);
                    return;
                }
                
                const dataToSave = {
                    firstName,
                    lastName,
                    birthYear,
                    position: stonePosition,
                    coords: this.coords 
                };
                if (stoneData.id) {
                    dataToSave.id = stoneData.id;
                }

                if (typeof this.onSaveCallback === 'function') {
                    this.onSaveCallback(dataToSave);
                    this.closePopup();
                } else {
                    console.error("Fehler: onSaveCallback ist nicht definiert oder keine Funktion. Stein kann nicht gespeichert werden.");
                }
            });
        }
        
        if (closeButton) {
            closeButton.addEventListener('click', () => {
                this.closePopup();
            });
        }
    }
    
    editStone(stoneData) {
        this.showPopup(stoneData);
    }
    
    closePopup() {
        if (this.popupElement && this.popupElement.parentNode) {
            this.popupElement.parentNode.removeChild(this.popupElement);
            this.popupElement = null;
            this.coords = null; 
        }
    }
    
    show() {
        if (this.buttonElement) {
            this.buttonElement.classList.remove("hidden");
        }
    }

    hide() {
        if (this.buttonElement) {
            this.buttonElement.classList.add("hidden");
        }
    }
    
    contains(targetElement) {
        return this.popupElement && this.popupElement.contains(targetElement);
    }
}