// markerInfoWindow.js

// ================= VALUE MAPS =================
const valueMaps = {
    // Χώροι Στάθμευσης
    status: { 1: "Δημόσιο", 2: "Ιδιωτικό" },
    vehicle_type: { 1: "Συμβατικό", 2: "Ηλεκτρικό" },

    // Διαβάσεις
    typos_odou: {
        1: "Τοπικός δρόμος / χαμηλής κυκλοφορίας",
        2: "Δρόμος συλλέκτης / μέτριας κυκλοφορίας",
        3: "Κύρια αρτηρία πόλης / υψηλής κυκλοφορίας",
        4: "Πεζόδρομος"
    },
    street_lights_type: {
        1: "cat's eye",
        2: "Τύπου LED",
        3: "Φωτεινές γραμμές"
    },

    // Ράμπες εισόδου κτιρίων
    door_type: {
        1: "Χειροκίνητη",
        2: "Συρόμενη",
        3: "Αυτόματη"
    },
    handrails: {
        0: "Όχι",
        1: "Μεταλλική",
        2: "Χτιστή",
        3: "Ξύλινη"
    }
};

// ================= GENERATE HTML =================

function generateInfoHTML(data) {
    const fieldLabels = fieldLabelsMap[data.category] || {};

    function getLabel(key, val) {
        if (val === null || val === undefined || val === '') return '';

        if (valueMaps[key] && valueMaps[key][val] !== undefined)
            return valueMaps[key][val];

        if (fieldLabels[`${key}_${val}`] !== undefined)
            return fieldLabels[`${key}_${val}`];

        if (val === true || val === "1" || val === 1) {
            if (fieldLabels[`${key}_yes`] !== undefined)
                return fieldLabels[`${key}_yes`];
        }

        if (val === false || val === "0" || val === 0) {
            if (fieldLabels[`${key}_no`] !== undefined)
                return fieldLabels[`${key}_no`];
        }

        return val;
    }

    let infoHTML = `
    <div style="
        max-width:500px;
        min-width:400px;
        font-family: Arial, sans-serif;
        font-size:12px;
        line-height:1.4;
        color:#333;
    ">
        <h4 style="
            margin:0 0 8px 0;
            color:#003366;
            font-weight:bold;
            text-align:center;
        ">
            ${data.category}
        </h4>
        <table style="width:100%; border-collapse:collapse;">
    `;

    const hiddenKeys = ['id','marker','category','category_id','dimos_id', 'lng', 'lat'];

    for (let key in data) {
        if (hiddenKeys.includes(key)) continue;

        let val = data[key];
        if (val instanceof File) val = val.name;

        if (val) {
            if (key === 'street_view') {
                val = `<a href="${val}" target="_blank" style="color:#0066cc; text-decoration:underline;">Προβολή</a>`;
            }
            else if (key === 'image1' || key === 'image2') {
                const imgUrl = `/images/${val}`;
                val = `<a href="${imgUrl}" target="_blank" style="color:#0066cc; text-decoration:underline;">Προβολή</a>`;
            }
            else {
                val = getLabel(key, val);
            }
        } else {
            val = getLabel(key, val);
        }

        infoHTML += `
        <tr>
            <td style="color:#003366; font-weight:bold; padding:6px 4px; white-space:nowrap;">
                ${fieldLabels[key] || key}
            </td>
            <td style="padding:6px 4px;">
                ${val}
            </td>
        </tr>`;
    }

    // --- Edit + Delete κουμπιά ---
    infoHTML += `
        </table>
        <div style="margin-top:6px; display:flex; gap:6px; justify-content:center;">
            <button class="btn btn-warning btn-sm editMarkerBtn" style="font-size:12px;">
                Edit
            </button>
            <button class="btn btn-danger btn-sm deleteMarkerBtn" style="font-size:12px;">
                Delete
            </button>
        </div>
    `;

    return infoHTML;
}



// ================= INFOWINDOW HANDLING =================


let currentInfoWindow = null;

function attachInfoWindow(marker, data, map) {

    marker.addListener('click', () => {

        if (currentInfoWindow) currentInfoWindow.close();

        const infoWindow = new google.maps.InfoWindow({
            content: generateInfoHTML(data),
            maxWidth: 500
        });

        infoWindow.open(map, marker);
        currentInfoWindow = infoWindow;

        google.maps.event.addListener(infoWindow, 'domready', () => {

            /* ========= EDIT ========= */
            const editBtn = document.querySelector('.editMarkerBtn');
            if (editBtn) {
                editBtn.onclick = () => openFormWithData(data);
            }

            /* ========= DELETE ========= */
            const iw = document.querySelector('.gm-style-iw');
            if (!iw) return;

            const deleteBtn = iw.querySelector('.deleteMarkerBtn');
            if (!deleteBtn) return;

            deleteBtn.onclick = () => {

                const alertBox = document.getElementById('deleteAlertContainer');
                if (!alertBox) return;

                alertBox.innerHTML = `
                    <div class="alert alert-warning fade in">
                        <strong>Προσοχή!</strong>
                        Είστε σίγουρος/η ότι θέλετε να διαγράψετε την εγγραφή;
                        <div style="margin-top:10px; text-align:right;">
                            <button id="confirmDeleteBtn"
                                    class="btn btn-danger btn-sm">
                                Ναι, διαγραφή
                            </button>
                        </div>
                    </div>
                `;

                document.getElementById('confirmDeleteBtn').onclick = async () => {

                    const category_id = categoryToIdMap[data.category];
                    if (!category_id) return;

                    try {
                        const res = await fetch('/va/delete_marker.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                id: data.id,
                                category_id: category_id
                            })
                        });

                        const result = await res.json();

                        if (!result.success) throw new Error();

                        marker.setMap(null);
                        if (currentInfoWindow) currentInfoWindow.close();

                        alertBox.innerHTML = `
                            <div class="alert alert-success fade in">
                                ✅ Η εγγραφή διαγράφηκε επιτυχώς
                            </div>
                        `;

                        setTimeout(() => alertBox.innerHTML = '', 3000);

                    } catch (e) {
                        alertBox.innerHTML = `
                            <div class="alert alert-danger fade in">
                                ❌ Σφάλμα διαγραφής
                            </div>
                        `;
                    }
                };
            };
        });
    });
}
