/**
 * @fileoverview bs-poi-co.js
 * Steuert die Anzeige für Einzel-POIs mit async/await Foto-Logik und Adress-Editor.
 */
import { getAdminMode } from './admin-mode-co.js';
import { attachSwipeListeners } from './bs-cluster-co.js';
import { getPoiData } from './poi-store.js';
import { LocationTrackingCoordinator } from './loc-tracking-co.js';
import { handleReadBiography, cancelSpeech } from './poi-speech-service.js';
import { Poi } from './poi.js';
import { checkDistance, mylog, getColorCodeAndText, showToast } from './utilities.js';
import { findMarkerByGid, getNearbyGids } from './map-gen-mgr.js';
import { ApplicationCoordinator } from './app-gen-co.js';
import { ScIntroButton } from './intro-button.js';
import { PhotoSheetUI } from './photo-sheet-ui.js';
import { PoiGallery } from './poi-gallery.js';

// --- NEU: Adress-Editor Modul ---
import { AddressEditor } from './specify_poi_address.js';
const addressEditor = new AddressEditor();

// --- CSS Injektion ---
const style = document.createElement('style');
style.textContent = `
    .photo-stack { position: relative; display: inline-block; z-index: 1; vertical-align: middle; }
    .photo-stack::before, .photo-stack::after {
        content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%;
        background: #fff; border: 1px solid #ccc; border-radius: 8px; z-index: -1;
    }
    .photo-stack::before { transform: translate(4px, 4px); }
    .photo-stack::after { transform: translate(8px, 8px); opacity: 0.5; }

    .poi-main-img { 
        display: block; width: auto; max-width: 100%; height: 180px !important; 
        object-fit: contain; border-radius: 8px; border: 2px solid #fff; 
        box-shadow: 0 2px 8px rgba(0,0,0,0.2); cursor: pointer; 
    }

    .poi-photo-flex-container { display: flex; align-items: center; justify-content: center; gap: 15px; }

    .poi-photo-badge-side {
        background: rgba(0,0,0,0.7); color: white; padding: 5px 12px; border-radius: 20px; 
        font-size: 1.6rem; font-weight: bold; white-space: nowrap; cursor: pointer;
    }

    /* Unauffälliger Trigger für GID */
    .gid-label-trigger { cursor: default; user-select: none; }
    .admin-active .gid-label-trigger { cursor: help; }
`;
document.head.appendChild(style);

// --- Hilfsfunktionen ---

async function getBiographyText(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error(`Bio-Fetch Fehler: ${response.status}`);
        const htmlText = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(htmlText, 'text/html');
        const contentContainer = doc.querySelector('.biography-text .field__item');
        return contentContainer ? contentContainer.textContent.trim() : null;
    } catch (error) {
        console.error('Fehler Biografie:', error);
        return null;
    }
}

function getPOIContentHtml(poiData) {
    const data = poiData;
    const color = getColorCodeAndText(data.last_cleaned).colorCode;
    const biographyUrl = data.url_kodb;
    const firstNameEnc = encodeURIComponent(data.first_name || "").replace(/-/g, '%2D');
    const lastNameEnc = encodeURIComponent(data.last_name || "").replace(/-/g, '%2D');
    const localDistrict = data.localdistrict || "Mitte";
    const wikipediaUrl = `https://de.wikipedia.org/wiki/Liste_der_Stolpersteine_in_Berlin-${localDistrict}#:~:text=${firstNameEnc}%20${lastNameEnc}`;
    const fullName = `${data.first_name || ""} ${data.last_name || ""}`.trim();
    let biographyRow = (biographyUrl && biographyUrl !== "null" && biographyUrl.trim() !== "")
        ? `<span id="biography-row-container" style="display: inline-block; vertical-align: middle;">
            <a href="${biographyUrl}" target="_blank">Biografie</a>
            <span id="audio-slot" style="display: inline-block; min-width: 110px; vertical-align: middle; position: relative; margin-left: 8px;">
                <span id="audio-controls" style="visibility: hidden; white-space: nowrap;">
                    <button class="read-biography-btn" data-url="${biographyUrl}" style="cursor: pointer; background: none; border: none; font-size: 1.5rem; color: #1e40af;"><i class="fas fa-play"></i></button>
                    <button class="pause-biography-btn" style="cursor: pointer; background: none; border: none; font-size: 1.5rem; color: #1e40af;"><i class="fas fa-pause"></i></button>
                </span>
                <span id="bio-loading-hint" style="display: none; font-size: 0.85em; color: #666;">(Prüfe Audio...)</span>
            </span>
            <span style="margin-left: 15px;"><a href="${wikipediaUrl}" target="_blank">Wikipedia</a></span>
           </span>`
        : `Biografie: Keine verfügbar | <a href="${wikipediaUrl}" target="_blank">Wikipedia</a>`;

    // GID als unauffälliger Trigger eingebaut
    return `
    <div class="poi-list-item ${color}-marker">
        <div style="margin-top: 8px;">
            ${biographyRow}
            <span class="gid-label-trigger" 
                  id="open-address-editor"
                  data-gid="${data.gid}" 
                  data-street="${data.street}" 
                  data-hn="${data.house_no || data.houseNr}" 
                  data-dist="${data.localdistrict}"
                  data-name="${fullName}"
                  style="font-size: 0.8em; color: #999; margin-left: 10px;">
                ${data.gid}
            </span>
        </div>
    </div>`;
}

// --- Hauptfunktion ---

export async function updateBsForPoi(gid, allParams) {
    const { bottomSheetUI, mapState, insertPoiUI, updatePoiUI, backendService, addDirectionHint } = allParams;
    cancelSpeech();
    const refreshParams = {
        bottomSheetUI, mapState, insertPoiUI, updatePoiUI, backendService, addDirectionHint
    };
    const clickedMarker = findMarkerByGid(gid);
    bottomSheetUI.setClickedObject(clickedMarker);
    const storeData = getPoiData(gid);
    if (!storeData) return;

    const PoiInstance = new Poi({ gid: gid }, backendService);
    const { contentHtml, options } = getBottomSheetDataAndActions(storeData);
    const showActive = options.showMainActionDiv;
    const lat = Number(storeData.lat);
    const lng = Number(storeData.lng);

    //bottomSheetUI.setBsTitle(`${storeData.first_name} ${storeData.last_name} (${storeData.year_of_birth})`);
    const rawTitle = `${storeData.first_name} ${storeData.last_name} (${storeData.year_of_birth})`;
    const finalTitle = addDirectionHint(rawTitle);
    bottomSheetUI.setBsTitle(finalTitle);

    bottomSheetUI.setBsLocation(storeData.stone_position ? `<span style="color: red;">Verlegeort:</span> ${storeData.stone_position}` : "");
    bottomSheetUI.updateAddress(storeData.street, storeData.houseNr, storeData.localdistrict);

    bottomSheetUI.setContent(contentHtml);
    bottomSheetUI.setCoords({ lat, lng });
    bottomSheetUI.setActions(options);

    // Admin-Status für den Trigger markieren
    if (getAdminMode.getStatus()) {
        const gidEl = document.getElementById('open-address-editor');
        if (gidEl) gidEl.parentElement.classList.add('admin-active');
    }

    if (storeData.url_kodb && storeData.url_kodb !== "null") {
        const audioControls = document.getElementById('audio-controls');
        const loadingHint = document.getElementById('bio-loading-hint');
        getBiographyText(storeData.url_kodb).then(text => {
            if (loadingHint) loadingHint.style.display = 'none';
            if (text && text.length > 40 && !text.includes('Fehler') && !text.includes('Entschuldigung')) {
                if (audioControls) audioControls.style.visibility = 'visible';
            }
        }).catch(() => { if (loadingHint) loadingHint.style.display = 'none'; });
    }

    try {
        const urlParams = new URLSearchParams(window.location.search);
        const dbParam = urlParams.get('db') ? `&db=${urlParams.get('db')}` : '';
        const response = await fetch(`fetch_poi_photos.php?gid=${gid}${dbParam}`);
        const photos = await response.json();

        if (Array.isArray(photos) && photos.length > 0) {
            bottomSheetUI.setPhoto(photos[0].url, photos.length - 1);
            const photoWrapper = document.getElementById('poi-photo-stack-wrapper');
            if (photoWrapper) {
                photoWrapper.onclick = () => {
                    const sheet = PhotoSheetUI.getInstance();
                    sheet.openEmpty(storeData, "Historie: " + storeData.last_name);
                    const gallery = new PoiGallery('photo-content-area');
                    gallery.render(photos, storeData.last_name);
                };
            }
        } else {
            bottomSheetUI.setPhoto(null);
        }
    } catch (err) {
        console.error("Foto-Fetch Fehler:", err);
        bottomSheetUI.setPhoto(null);
    }

    if (showActive && bottomSheetUI.introButton) {
        bottomSheetUI.introButton.innerHTML = '';
        bottomSheetUI.introButton.appendChild(new ScIntroButton('bs-poi-intro-btn').getElement());
    }

    const nearbyGids = getNearbyGids({ lat, lng });
    if (nearbyGids.length > 1) {
        bottomSheetUI.setNavButtonsState(true, true);
        attachSwipeListeners(bottomSheetUI, gid);
    } else {
        bottomSheetUI.setNavButtonsState(false, false);
    }

    attachActionListeners(bottomSheetUI, gid, PoiInstance, insertPoiUI, updatePoiUI, backendService, mapState, options,refreshParams);
    bottomSheetUI.mainActionsContainer?.querySelectorAll('.special-status-btn').forEach(btn => btn.remove());

    const { poiCleanButton, poiDirtyButton, introButton, mainActionsContainer, fallbackButton } = bottomSheetUI;
    if (showActive) {
        mainActionsContainer?.style.setProperty('display', 'flex', 'important');
        if (poiCleanButton) poiCleanButton.style.order = "1";
        if (introButton) introButton.style.order = "2";
        if (poiDirtyButton) poiDirtyButton.style.order = "3";
        fallbackButton?.style.setProperty('display', 'none', 'important');
    }
}

// PRÄZISE BROWSER-ERKENNUNG
const getBrowserName = () => {
    const ua = navigator.userAgent;
    const vendor = navigator.vendor || "";
    if (ua.includes("CriOS")) return "Google Chrome";
    if (ua.includes("FxiOS")) return "Firefox";
    if (ua.includes("EdgiOS")) return "Microsoft Edge";
    if (ua.includes("OPiOS")) return "Opera";
    if (ua.includes("Chrome") && vendor.includes("Google")) return "Google Chrome";
    if (ua.includes("Edg/")) return "Microsoft Edge";
    if (ua.includes("OPR") || ua.includes("Opera")) return "Opera";
    if (ua.includes("Firefox")) return "Firefox";
    if (ua.includes("Safari") && vendor.includes("Apple")) return "Safari";
    return "deinem Browser";
};

// --- Listeners ---

function attachActionListeners(bottomSheetUI, gid, PoiInstance, insertPoiUI, updatePoiUI, backendService, mapState, options,refreshParams) {
    const bus = ApplicationCoordinator.appEvents;
    const { poiCleanButton, poiDirtyButton, fallbackButton, caretakerCheckbox, editButton, addButton } = bottomSheetUI;

    // --- NEU: GID TRIGGER FÜR ADRESS-EDITOR ---
    const gidTrigger = document.getElementById('open-address-editor');
    if (gidTrigger && getAdminMode.getStatus()) {
        gidTrigger.onclick = (e) => {
            e.stopPropagation();
            const { gid, street, hn, dist, name } = gidTrigger.dataset;
            addressEditor.open(gid, street, hn, dist, name);
        };
    }

    if (options.showFallbackButton && fallbackButton) {
        fallbackButton.onclick = () => showToast("Bitte Adresse aufsuchen.");
        return;
    }

    if (options.showMainActionDiv) {
        const setupStatusButton = (button, isDirtyValue) => {
            if (!button) return;

            button.onclick = () => {
                bus.dispatchEvent(new CustomEvent('poi:executeStatusUpdate', { detail: { gid, isDirty: isDirtyValue } }));

                const photoBtn = document.createElement('button');
                photoBtn.id = "temp-photo-btn";
                photoBtn.innerHTML = `
                    <div style="display: flex; align-items: center; justify-content: center; gap: 10px; width: 100%;">
                        <div style="font-size: 1.62rem; font-weight: 900; white-space: nowrap;">Foto aufnehmen?</div>
                        <div style="font-size: 1.4rem; cursor: help; flex-shrink: 0;" id="camera-info-icon">
                            <i class="fas fa-info-circle" style="opacity: 0.8;"></i>
                        </div>
                    </div>
                `;

                // KORREKTUR: justifyContent ohne Tab/Leerzeichen
                Object.assign(photoBtn.style, {
                    position: 'fixed', bottom: '25%', left: '50%', transform: 'translateX(-50%)',
                    backgroundColor: '#1e40af', color: 'white', padding: '30px 25px',
                    borderRadius: '35px', zIndex: '2147483647', border: 'none',
                    boxShadow: '0 15px 45px rgba(0,0,0,0.6)', cursor: 'pointer',
                    width: '92%', maxWidth: '500px', textAlign: 'center',
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                });

                photoBtn.querySelector('#camera-info-icon').onclick = (e) => {
                    e.stopPropagation();
                    const browser = getBrowserName();
                    alert(`Nach der Bewertung können Sie den Stolperstein fotografieren und kommentieren.\n\nUm ein Foto hochzuladen, benötigt ${browser} Zugriff auf die Kamera.`);
                };

                photoBtn.addEventListener('click', (e) => {
                    if (e.target.closest('#camera-info-icon')) return;
                    e.preventDefault();
                    document.getElementById('temp-photo-btn')?.remove();

                    const sheet = PhotoSheetUI.getInstance();
                    const data = getPoiData(gid);
                    // Wir nutzen ein lokales Objekt für den Refresh

                    const uploadCallback = async (photoData) => {
                        const urlParams = new URLSearchParams(window.location.search);
                        const dbParam = urlParams.get('db') ? `?db=${urlParams.get('db')}` : '';

                        const formData = new FormData();
                        formData.append('action', 'upload_poi_photo');
                        formData.append('gid', gid);
                        formData.append('photo', photoData.file, 'photo.jpg');
                        formData.append('description', photoData.description || "");

                        showToast("Lade hoch...");
                        try {
                            const res = await fetch(`insert-upload-poi-photo.php${dbParam}`, { method: 'POST', body: formData });
                            if (!res.ok) throw new Error(`HTTP Fehler: ${res.status}`);
                            const json = await res.json();
                            if (json.success) {
                                await new Promise(r => setTimeout(r, 300));
                                sheet.close();
                                await updateBsForPoi(gid, refreshParams);
                                showToast("Gespeichert & Aktualisiert", "success");
                            } else {
                                showToast("Fehler: " + (json.message || "Upload fehlgeschlagen"), "error");
                            }
                        } catch (err) {
                            console.error("Upload Error:", err);
                            showToast("Server-Fehler beim Upload", "error");
                        }
                    };

                    sheet.open(data, uploadCallback);
                    setTimeout(() => {
                        const input = document.getElementById('poi-photo-capture');
                        if (input) input.click();
                    }, 150);
                });

                document.body.appendChild(photoBtn);
                setTimeout(() => { document.getElementById('temp-photo-btn')?.remove(); }, 2000);
            };
        };

        setupStatusButton(poiCleanButton, 0); //glänzend
        setupStatusButton(poiDirtyButton, 4);  // stumpf
    }

    if (caretakerCheckbox) {
        caretakerCheckbox.onchange = function () {
            bus.dispatchEvent(new CustomEvent('poi:executeCaretakerUpdate', { detail: { gid, isChecked: this.checked } }));
        };
    }
    if (editButton) {
        editButton.onclick = (e) => {
            e.stopPropagation();
            bus.dispatchEvent(new CustomEvent('poi:requestEdit', { detail: { gid } }));
        };
    }
    if (addButton) {
        addButton.onclick = (e) => {
            e.stopPropagation();
            bus.dispatchEvent(new CustomEvent('poi:openInsertPopup', { detail: { coords: bottomSheetUI._currentCoords, addressData: bottomSheetUI.currentAddress } }));
        };
    }
}

export function attachActionListenersForNewAddress(bottomSheetUI) {
    const bus = ApplicationCoordinator.appEvents;
    const addButton = bottomSheetUI.addButton;
    if (!addButton) return;
    addButton.classList.remove('hidden');
    addButton.style.display = 'flex';
    addButton.onclick = (e) => {
        e.stopPropagation();
        bus.dispatchEvent(new CustomEvent('poi:openInsertPopup', { detail: { coords: bottomSheetUI._currentCoords, addressData: bottomSheetUI.currentAddress } }));
    };
}

export function initBsAudioEvents() {
    mylog("BS-POI-CO: Globaler Audio-Listener wird initialisiert.");
    document.body.addEventListener('click', (e) => {
        const playBtn = e.target.closest('.read-biography-btn');
        const pauseBtn = e.target.closest('.pause-biography-btn');
        if (playBtn) {
            e.stopPropagation();
            handleReadBiography(playBtn.dataset.url);
        } else if (pauseBtn) {
            e.stopPropagation();
            cancelSpeech();
        }
    });
}

function getBottomSheetDataAndActions(poiData) {
    const lat = Number(poiData.lat);
    const lng = Number(poiData.lng);
    const locCoord = LocationTrackingCoordinator.getInstance();
    const isAdmin = getAdminMode.getStatus();
    const isNearby = (locCoord.getUserPosition() && lat && lng) ? checkDistance(locCoord.getUserPosition()[0], locCoord.getUserPosition()[1], lat, lng, 99) : false;
    const showActiveState = isNearby || isAdmin;

    return {
        contentHtml: getPOIContentHtml(poiData),
        options: {
            showCaretaker: showActiveState,
            isCaretaker: !!poiData.caretaker,
            showPoiPhotoStack: true,
            showMainActionDiv: showActiveState,
            showFallbackButton: !showActiveState,
            showPoiCleanButton: showActiveState,
            showIntroButton: showActiveState,
            showPoiDirtyButton: showActiveState,
            showAddButton: showActiveState,
            showEditButton: showActiveState,
            fallbackButtonText: "Adresse aufsuchen, um den Zustand zu erfassen"
        }
    };
}