/**
 * @fileoverview poi-gallery.js
 * Modul für die Anzeige der Reinigungshistorie und Lightbox.
 */
import { mylog } from "./utilities.js";

export class PoiGallery {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.lightbox = null;
        this._injectGalleryCSS();
    }

    /**
     * Rendert die Galerie in den Zielcontainer.
     */
    render(photos, poiName) {
        if (!this.container) return;
        mylog(`[Gallery] Rendering ${photos.length} photos for ${poiName}`);

        let html = `<div class="gallery-scroll-container">`;

        if (photos.length === 0) {
            html += `<div style="text-align:center; padding:40px; color:#777;">Keine Fotos vorhanden.</div>`;
        } else {
            photos.forEach((p, index) => {
                const date = this._formatPhotoDate(p.upload_at);
                const user = p.username || p.uploader_name || "Anonym";
                const desc = p.description && p.description !== "null" ? `<span class="gallery-description">${p.description}</span>` : "";

                html += `
                    <div class="gallery-item">
                        <img src="${p.url}" class="gallery-img clickable-photo" data-index="${index}">
                        ${desc} 
                        <div class="gallery-meta">
                            Hochgeladen am <strong>${date}</strong> von <strong>${user}</strong>
                        </div>
                    </div>`;
            });
        }

        html += `</div>`;
        this.container.innerHTML = html;

        this.container.querySelectorAll('.clickable-photo').forEach(img => {
            img.onclick = () => this.openLightbox(photos[img.dataset.index]);
        });
    }

    openLightbox(photo) {
        if (!this.lightbox) this._createLightbox();
        
        const img = this.lightbox.querySelector('.lightbox-img');
        const caption = this.lightbox.querySelector('.lightbox-caption');
        
        img.src = photo.url;
        img.style.transform = 'translate(0px, 0px) scale(1)';
        caption.textContent = photo.description || "";
        
        this.lightbox.style.display = 'flex';
        setTimeout(() => this.lightbox.classList.add('active'), 10);
    }

    _createLightbox() {
        this.lightbox = document.createElement('div');
        this.lightbox.id = 'gallery-lightbox';
        this.lightbox.className = 'gallery-lightbox-overlay';
        this.lightbox.innerHTML = `
            <div class="lightbox-close-btn">&times;</div>
            <div class="lightbox-zoom-container"><img class="lightbox-img"></div>
            <div class="lightbox-caption"></div>
        `;
        document.body.appendChild(this.lightbox);

        this.lightbox.querySelector('.lightbox-close-btn').onclick = () => {
            this.lightbox.classList.remove('active');
            setTimeout(() => this.lightbox.style.display = 'none', 300);
        };
        this._initPinchToZoom(this.lightbox);
    }

    _injectGalleryCSS() {
        if (document.getElementById('gallery-styles')) return;
        const css = `
            .gallery-scroll-container { display: flex; flex-direction: column; gap: 20px; padding: 20px; }
            .gallery-item {
                background: #fff; border: 1px solid #eee; border-radius: 16px;
                padding: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            }
            .gallery-img { width: 100%; border-radius: 10px; display: block; margin-bottom: 10px; cursor: zoom-in; }
            .gallery-description { display: block; font-weight: 400; color: #111; font-size: 1rem; margin-bottom: 5px; }
            .gallery-meta { font-size: 0.8rem; color: #777; }

            .gallery-lightbox-overlay {
                position: fixed; top: 0; left: 0; width: 100vw; height: 100vh;
                background: rgba(0, 0, 0, 0.9); backdrop-filter: blur(15px);
                z-index: 12000; display: none; align-items: center; justify-content: center;
                flex-direction: column; touch-action: none;
            }
            .lightbox-zoom-container { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; overflow: hidden; }
            .lightbox-img { max-width: 95%; max-height: 85%; border-radius: 12px; transition: transform 0.1s ease-out; will-change: transform; }
            .lightbox-close-btn { position: absolute; top: 20px; right: 20px; color: white; font-size: 40px; z-index: 13000; cursor: pointer; }
            .lightbox-caption { color: #fff; margin-top: 20px; text-align: center; padding: 0 20px; }
            .gallery-lightbox-overlay.active .lightbox-img { transform: scale(1); }
        `;
        const style = document.createElement('style');
        style.id = 'gallery-styles';
        style.textContent = css;
        document.head.appendChild(style);
    }

    _initPinchToZoom(overlay) {
        const img = overlay.querySelector('.lightbox-img');
        let scale = 1, lastScale = 1, startDist = 0;
        let posX = 0, posY = 0, startX = 0, startY = 0;

        overlay.addEventListener('touchstart', e => {
            if (e.touches.length === 2) {
                startDist = Math.hypot(e.touches[0].pageX - e.touches[1].pageX, e.touches[0].pageY - e.touches[1].pageY);
            } else if (e.touches.length === 1 && scale > 1) {
                startX = e.touches[0].pageX - posX; startY = e.touches[0].pageY - posY;
            }
        });

        overlay.addEventListener('touchmove', e => {
            if (e.touches.length === 2 || scale > 1) e.preventDefault();
            if (e.touches.length === 2) {
                const dist = Math.hypot(e.touches[0].pageX - e.touches[1].pageX, e.touches[0].pageY - e.touches[1].pageY);
                scale = Math.min(Math.max(1, lastScale * (dist / startDist)), 4);
            } else if (e.touches.length === 1 && scale > 1) {
                posX = e.touches[0].pageX - startX; posY = e.touches[0].pageY - startY;
            }
            img.style.transform = `translate(${posX}px, ${posY}px) scale(${scale})`;
        }, { passive: false });

        overlay.addEventListener('touchend', () => {
            lastScale = scale;
            if (scale <= 1) { posX = posY = 0; img.style.transform = `translate(0, 0) scale(1)`; }
        });
    }

    _formatPhotoDate(dateStr) {
        const date = new Date(dateStr);
        if (isNaN(date)) return dateStr;
        const months = ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
        return `${String(date.getDate()).padStart(2, '0')}. ${months[date.getMonth()]} ${String(date.getFullYear()).slice(-2)}`;
    }
}