import { getPoiData } from './poi-store.js';
import { BackendService } from './backend-db.js';
import { mylog, showToast } from './utilities.js';
import { L } from './map-service.js';
import { fetchLocationFromAddressNominatim } from './backend-geo.js';
import { refreshPoiAndClusters } from './map-poi-mgr.js';
import { Poi } from './poi.js'; // KORREKTUR: Import hinzugefügt für instanceof-Prüfung
/**
 * HTML-Template für das Korrektur-Modal mit Live-Koordinaten
 */
const ADDRESS_MODAL_HTML = `
<div id="address-modal" style="display:none; position:fixed; z-index:100001; left:0; top:0; width:100%; height:100%; background:rgba(0,0,0,0.7); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;">
    <div style="background:white; margin:6vh auto; padding:20px; width:92%; max-width:450px; border-radius:24px; box-shadow:0 20px 40px rgba(0,0,0,0.4); box-sizing: border-box; position: relative;">
        
        <h3 style="margin: 0 0 15px 0; color: #222; text-align: center; font-size: 1.2rem;">Standort präzisieren</h3>
        
        <div style="display:flex; justify-content: space-around; background: #f2f2f7; padding: 10px; border-radius: 12px; margin-bottom: 15px; font-family: 'SF Mono', Menlo, monospace; font-size: 13px; color: #333; border: 1px solid #e5e5ea;">
            <div style="display:flex; flex-direction:column; align-items:center;">
                <span style="font-size:9px; color:#8e8e93; text-transform:uppercase;">Breitengrad (Lat)</span>
                <span id="display-lat" style="font-weight:600;">0.0000000</span>
            </div>
            <div style="width:1px; background:#d1d1d6; height:20px; align-self:center;"></div>
            <div style="display:flex; flex-direction:column; align-items:center;">
                <span style="font-size:9px; color:#8e8e93; text-transform:uppercase;">Längengrad (Lng)</span>
                <span id="display-lng" style="font-weight:600;">0.0000000</span>
            </div>
        </div>

        <div style="margin-bottom:12px;">
            <label style="font-size:11px; color:#8e8e93; text-transform: uppercase; font-weight: bold; margin-left: 4px;">Straße</label>
            <input type="text" id="in-street" placeholder="Straße" style="width:100%; padding:12px; border:1px solid #d1d1d6; border-radius:12px; font-size:16px; box-sizing: border-box; margin-top: 4px;">
        </div>
        
        <div style="display:flex; gap:12px; margin-bottom:18px;">
            <div style="flex:1;">
                <label style="font-size:11px; color:#8e8e93; text-transform: uppercase; font-weight: bold; margin-left: 4px;">Haus-Nr.</label>
                <input type="text" id="in-hn" placeholder="Nr." style="width:100%; padding:12px; border:1px solid #d1d1d6; border-radius:12px; font-size:16px; box-sizing: border-box; margin-top: 4px;">
            </div>
            <div style="flex:2;">
                <label style="font-size:11px; color:#8e8e93; text-transform: uppercase; font-weight: bold; margin-left: 4px;">Ortsteil</label>
                <input type="text" id="in-dist" placeholder="Bezirk" style="width:100%; padding:12px; border:1px solid #d1d1d6; border-radius:12px; font-size:16px; box-sizing: border-box; margin-top: 4px;">
            </div>
        </div>

        <div style="position: relative; width: 100%; height: 250px; margin-bottom: 22px; border-radius:16px; overflow: hidden; border: 1px solid #e5e5ea; background:#f8f8f8;">
            <div id="modal-map" style="width:100%; height:100%;"></div>
            
            <div id="map-crosshair" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000; pointer-events: none;">
                <div style="position: absolute; width: 30px; height: 2px; background: #ff3b30; left: -15px;"></div>
                <div style="position: absolute; height: 30px; width: 2px; background: #ff3b30; top: -15px;"></div>
                <div style="width: 10px; height: 10px; border: 2px solid #ff3b30; border-radius: 50%; background: rgba(255,59,48,0.1);"></div>
            </div>
        </div>

        <div style="display:flex; gap:12px;">
            <button id="btn-address-save" style="flex:1.6; background:#34c759; color:white; border:none; padding:16px; border-radius:14px; font-weight:bold; font-size:17px; cursor:pointer;">Speichern</button>
            <button id="btn-address-cancel" style="flex:1; background:#f2f2f7; color:#3a3a3c; border:none; padding:16px; border-radius:14px; font-weight:bold; font-size:17px; cursor:pointer;">Abbruch</button>
        </div>
    </div>
</div>
`;

export class AddressEditor {
    constructor() {
        this.modalMap = null;
        this.currentGid = null;
        this.modalElement = null;
        this.addressMarker = null;
        this.wikiMarker = null;
        this.searchTimeout = null;

        this.liveLat = 52.5200;
        this.liveLng = 13.4050;
        this.anchorLat = 52.5200;
        this.anchorLng = 13.4050;

        this.save = this.save.bind(this);
        this.close = this.close.bind(this);
    }

    ensureHtmlInjected() {
        if (!document.getElementById('address-modal')) {
            document.body.insertAdjacentHTML('beforeend', ADDRESS_MODAL_HTML);
            this.modalElement = document.getElementById('address-modal');
            this.bindButtons();
        } else {
            this.modalElement = document.getElementById('address-modal');
        }
    }

    async open(gid, street, hn, dist, fullName) {
        window.addressEditor = this;
        this.currentGid = gid;
        this.ensureHtmlInjected();

        this.setFieldValue('in-street', street);
        this.setFieldValue('in-hn', hn);
        this.setFieldValue('in-dist', dist);

        const poi = getPoiData(gid);
        if (poi) {
            this.anchorLat = parseFloat(poi.lat) || 52.5200;
            this.anchorLng = parseFloat(poi.lng) || 13.4050;
            this.liveLat = this.anchorLat;
            this.liveLng = this.anchorLng;
            this.updateCoordinateDisplay(this.liveLat, this.liveLng);
        }

        this.modalElement.style.display = 'block';
        this.initMap(this.liveLat, this.liveLng);
        this.bindInputListeners();

        const searchTasks = [this.findOnMap()];
        if (dist && street && fullName) {
            searchTasks.push(this.fetchWikiPrecision(dist, street, hn, fullName));
        }

        await Promise.allSettled(searchTasks);
        this.triggerFinalSequence();
    }

    triggerFinalSequence() {
        if (!this.modalMap) return;

        // Wir nutzen den Anker, um Drift durch Karten-Events zu vermeiden
        const dbPoint = L.latLng(this.anchorLat, this.anchorLng);
        const points = [dbPoint];

        if (this.addressMarker) points.push(this.addressMarker.getLatLng());
        if (this.wikiMarker) points.push(this.wikiMarker.getLatLng());

        if (points.length > 1) {
            const bounds = L.latLngBounds(points);
            const targetZoom = this.modalMap.getBoundsZoom(bounds, false, [40, 40]);

            // Phase 1: Übersicht (Sofort)
            this.modalMap.fitBounds(bounds, { padding: [40, 40], animate: false });

            // Phase 2: Nach 0,5 Sek Panning zur DB-Koordinate (Anker)
            setTimeout(() => {
                this.modalMap.flyTo(dbPoint, targetZoom, {
                    animate: true,
                    duration: 0.8
                });
            }, 500);
        } else {
            this.modalMap.flyTo(dbPoint, 19, { animate: true });
        }
    }

    async findOnMap() {
        const street = document.getElementById('in-street')?.value.trim();
        const houseNr = document.getElementById('in-hn')?.value.trim();
        const localdistrict = document.getElementById('in-dist')?.value.trim();

        if (this.addressMarker && this.modalMap) {
            this.modalMap.removeLayer(this.addressMarker);
            this.addressMarker = null;
        }
        if (!street || !this.modalMap) return;

        try {
            const addressObj = { street, houseNr, localdistrict };
            const location = await fetchLocationFromAddressNominatim(addressObj);
            if (location && this.modalMap) {
                this.addressMarker = L.marker([location.lat, location.lng], {
                    icon: L.icon({
                        iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-blue.png',
                        shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41]
                    }),
                    zIndexOffset: 1000,
                    interactive: false
                }).addTo(this.modalMap);
                mylog(`[AddressEditor] Nominatim geladen`);
            }
        } catch (e) { mylog(`Geocoding failed: ${e.message}`); }
    }

    async fetchWikiPrecision(dist, street, hn, name) {
        const url = `get_wiki_coord.php?district=${encodeURIComponent(dist)}&street=${encodeURIComponent(street)}&hn=${encodeURIComponent(hn)}&name=${encodeURIComponent(name)}`;
        try {
            const response = await fetch(url);
            const data = await response.json();
            if (data.success && this.modalMap) {
                if (this.wikiMarker) this.modalMap.removeLayer(this.wikiMarker);
                this.wikiMarker = L.marker([data.lat, data.lng], {
                    icon: L.icon({
                        iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
                        shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
                        iconSize: [25, 41],
                        iconAnchor: [12, 41]
                    }),
                    zIndexOffset: 1100
                }).addTo(this.modalMap).bindTooltip("Wikipedia Präzision");
                mylog(`[AddressEditor] Wiki-Koordinaten geladen`);
            }
        } catch (e) { mylog(`Wiki-Fetch failed: ${e.message}`); }
    }

    initMap(lat, lng) {
        const initialZoom = 19;
        const maxAvailableZoom = 21;

        if (this.modalMap) {
            this.modalMap.setView([lat, lng], initialZoom);
        } else {
            this.modalMap = L.map('modal-map', {
                zoomControl: true,
                attributionControl: false,
                maxZoom: maxAvailableZoom
            }).setView([lat, lng], initialZoom);

            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: maxAvailableZoom,
                maxNativeZoom: 19
            }).addTo(this.modalMap);

            this.modalMap.on('move', () => {
                const center = this.modalMap.getCenter();
                this.liveLat = center.lat;
                this.liveLng = center.lng;
                this.updateCoordinateDisplay(this.liveLat, this.liveLng);
            });
        }

        setTimeout(() => {
            if (this.modalMap) this.modalMap.invalidateSize();
        }, 350);
    }

    updateCoordinateDisplay(lat, lng) {
        const latEl = document.getElementById('display-lat');
        const lngEl = document.getElementById('display-lng');
        if (latEl) latEl.textContent = parseFloat(lat).toFixed(7);
        if (lngEl) lngEl.textContent = parseFloat(lng).toFixed(7);
    }

    bindInputListeners() {
        ['in-street', 'in-hn', 'in-dist'].forEach(id => {
            const el = document.getElementById(id);
            if (el) {
                el.oninput = () => {
                    clearTimeout(this.searchTimeout);
                    this.searchTimeout = setTimeout(async () => {
                        await this.findOnMap();
                        this.triggerFinalSequence();
                    }, 600);
                };
            }
        });
    }

    async save() {
        if (!this.currentGid) return;

        try {
            const backend = BackendService.getInstance();
            const street = document.getElementById('in-street')?.value || '';
            const houseNr = document.getElementById('in-hn')?.value || '';
            const localdistrict = document.getElementById('in-dist')?.value || '';

            const result = await backend.updatePoiAddress(
                this.currentGid,
                street,
                houseNr,
                localdistrict,
                this.liveLat,
                this.liveLng
            );

            if (result?.success) {
                const existingStone = getPoiData(this.currentGid);

                // Wir vertrauen blind darauf, dass es existiert und eine Poi Instanz ist
                existingStone.set('street', street);
                existingStone.set('houseNr', houseNr);
                existingStone.set('localdistrict', localdistrict);
                existingStone.set('lat', this.liveLat);
                existingStone.set('lng', this.liveLng);

                await refreshPoiAndClusters(this.currentGid, existingStone);

                this.close();
                showToast("Standort erfolgreich gespeichert.");
            }
        } catch (err) { alert("Fehler: " + err.message); }
    }

    setFieldValue(id, value) {
        const el = document.getElementById(id);
        if (el) el.value = value || '';
    }

    bindButtons() {
        const saveBtn = document.getElementById('btn-address-save');
        const cancelBtn = document.getElementById('btn-address-cancel');
        if (saveBtn) saveBtn.onclick = (e) => { e.preventDefault(); this.save(); };
        if (cancelBtn) cancelBtn.onclick = (e) => { e.preventDefault(); this.close(); };
    }

    close() {
        if (this.modalElement) {
            this.modalElement.style.display = 'none';
            if (this.modalMap) {
                if (this.addressMarker) this.modalMap.removeLayer(this.addressMarker);
                if (this.wikiMarker) this.modalMap.removeLayer(this.wikiMarker);
            }
            this.addressMarker = null;
            this.wikiMarker = null;
        }
    }
}