document.addEventListener("DOMContentLoaded", () => {
    const levelSelectorNav = document.getElementById("level-selector");
    const floorPlanArea = document.getElementById("floor-plan-area");
    const unitButtonContainerParent = document.getElementById("unit-button-container");
    const detailsContent = document.getElementById("details-content");
    const currentYearSpan = document.getElementById("current-year");

    const magnifyModal = document.getElementById("magnify-modal");
    const modalImg = document.getElementById("magnified-img");
    const closeModalBtn = document.querySelector(".modal-close");

    const initialDetailsMessage = '<p>Select a unit button above to see its details.</p><div id="download-button-container"></div>';
    let currentUnitsData = []; // To store fetched units for the current level

    if (currentYearSpan) {
        currentYearSpan.textContent = new Date().getFullYear();
    }

    // --- Initialize Page based on PHP-provided constants ---
    // SELECTED_MALL_ID, SELECTED_MALL_SLUG, AVAILABLE_LEVELS are expected from PHP
    if (typeof SELECTED_MALL_ID === 'undefined' || typeof AVAILABLE_LEVELS === 'undefined') {
        console.error("Mall ID or Available Levels not defined. Check PHP script.");
        detailsContent.innerHTML = "<p>Error: Mall configuration missing. Please select a mall.</p>";
        return;
    }

    function generateLevelButtons() {
        levelSelectorNav.innerHTML = ''; // Clear existing buttons
        if (AVAILABLE_LEVELS.length === 0) {
            levelSelectorNav.innerHTML = '<p style="color: #fff;">No levels defined for this mall yet.</p>';
            clearUnitDisplay();
            return;
        }

        AVAILABLE_LEVELS.forEach((level, index) => {
            const button = document.createElement("button");
            button.classList.add("level-button");
            button.dataset.level = level; // Assuming level is like '1', '2', 'B1'
            button.textContent = `Level ${level.startsWith('L') ? level.substring(1) : level}`; // Display "Level 1" from "L1"
            if (index === 0) {
                button.classList.add("active");
            }
            levelSelectorNav.appendChild(button);
        });

        // Add event listeners to new buttons
        levelSelectorNav.addEventListener("click", handleLevelChange);

        // Load data for the first active level
        if (AVAILABLE_LEVELS.length > 0) {
            loadLevelData(AVAILABLE_LEVELS[0]);
        } else {
            clearUnitDisplay();
        }
    }

    function handleLevelChange(e) {
        if (e.target.classList.contains("level-button")) {
            const targetLevel = e.target.dataset.level;
            document.querySelectorAll("#level-selector .level-button").forEach(button => {
                button.classList.toggle("active", button.dataset.level === targetLevel);
            });
            loadLevelData(targetLevel);
        }
    }

    async function loadLevelData(level) {
        clearUnitDisplay();
        detailsContent.innerHTML = initialDetailsMessage; // Reset details panel

        try {
            // Fetch units for the selected mall and level
            const response = await fetch(`php/get_units.php?mall_id=${SELECTED_MALL_ID}&level=${level}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();

            if (data.error) {
                console.error("Error fetching units:", data.error);
                displayErrorMessageInUnits("Error loading unit data.");
                displayErrorMessageInFloorPlan("Error loading floor plan.");
                return;
            }
            
            currentUnitsData = data.units; // Store for later use
            displayFloorPlan(level, data.floor_plan_image_path); // Display general floor plan for the level
            displayUnitButtons(level, data.units);

        } catch (error) {
            console.error("Failed to load level data:", error);
            displayErrorMessageInUnits("Could not load unit information. Please try again.");
            displayErrorMessageInFloorPlan("Could not load floor plan. Please try again.");
        }
    }

    function displayFloorPlan(level, floorPlanImagePath) {
        floorPlanArea.innerHTML = ''; // Clear previous floor plans

        const planDiv = document.createElement('div');
        planDiv.id = `level-${level}-plan`; // Use level directly for ID
        planDiv.classList.add('floor-plan', 'active'); // Always active as we load one at a time

        const planContainer = document.createElement('div');
        planContainer.classList.add('plan-container');

        if (floorPlanImagePath) {
            const img = document.createElement('img');
            img.src = floorPlanImagePath; // e.g., 'images/malls/321-clementi/level-1-plan.png'
            img.alt = `Level ${level} Floor Plan for ${SELECTED_MALL_SLUG}`;
            img.classList.add('clickable-plan');
            img.addEventListener('click', handleMagnify);
            planContainer.appendChild(img);
        } else {
            planContainer.innerHTML = `<p>No floor plan image available for Level ${level}.</p>`;
        }
        planDiv.appendChild(planContainer);
        floorPlanArea.appendChild(planDiv);
    }

    function displayUnitButtons(level, units) {
        unitButtonContainerParent.innerHTML = ''; // Clear previous containers

        const buttonsDiv = document.createElement('div');
        buttonsDiv.id = `level-${level}-buttons`;
        buttonsDiv.classList.add('unit-buttons', 'active'); // Always active

        if (units && units.length > 0) {
            units.forEach(unit => {
                const button = document.createElement('button');
                button.type = "button";
                button.classList.add('unit-selector-button', unit.status.toLowerCase()); // 'available' or 'leased'
                button.dataset.unitDbId = unit.id; // Store database ID if needed for edits/deletes
                // Store all data attributes directly from the unit object
                Object.keys(unit).forEach(key => {
                    if (unit[key] !== null && unit[key] !== undefined) {
                        button.dataset[toCamelCase(key)] = unit[key];
                    }
                });
                button.textContent = unit.unit_id_display;
                button.addEventListener('click', handleUnitButtonClick);
                buttonsDiv.appendChild(button);
            });
        } else {
            buttonsDiv.innerHTML = `<p style="text-align: center; color: #666;">No units defined for Level ${level} yet.</p>`;
        }
        unitButtonContainerParent.appendChild(buttonsDiv);
    }

    function toCamelCase(str) {
        return str.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
    }


    function handleUnitButtonClick(event) {
        const button = event.currentTarget;
        document.querySelectorAll('.unit-selector-button').forEach(btn => btn.classList.remove('selected'));
        button.classList.add('selected');

        // Retrieve all data attributes from the clicked button
        const unitData = { ...button.dataset }; // Shallow copy of dataset

        // Rename keys from dataset (camelCase) to what the old display logic expects (or adjust display logic)
        // For simplicity, we'll assume the display logic can use the camelCased keys from dataset
        // e.g. unitData.unitIdDisplay, unitData.acPower etc.

        const detailsGrid = document.createElement('div');
        detailsGrid.id = 'details-grid';
        // Ensure you have all the expected fields in your 'units' table and they are fetched in get_units.php
        let gridHTML = `
            <p><strong>Unit No:</strong> ${escapeHTML(unitData.unitIdDisplay || 'N/A')}</p>
            <p><strong>Status:</strong> ${escapeHTML(unitData.status || 'N/A')}</p>
            <p><strong>Area:</strong> ${escapeHTML(unitData.area || 'N/A')}</p>
            <p><strong>Water Point:</strong> ${escapeHTML(unitData.waterPoint || 'N/A')}</p>
            <p><strong>A/C Power:</strong> ${escapeHTML(unitData.acPower || 'N/A')}</p>
            <p><strong>FCU Units:</strong> ${escapeHTML(unitData.fcuUnits || 'N/A')}</p>
            <p><strong>Elect. Isolator:</strong> ${escapeHTML(unitData.elecIsolator || 'N/A')}</p>
            <p><strong>Elect. Phase:</strong> ${escapeHTML(unitData.elecPhase || 'N/A')}</p>
            <p><strong>Emergency Lights:</strong> ${escapeHTML(unitData.emergencyLight || 'N/A')}</p>
            <p><strong>Exit Signage:</strong> ${escapeHTML(unitData.exitSignage || 'N/A')}</p>
            <p><strong>PA Speaker:</strong> ${escapeHTML(unitData.paSpeaker || 'N/A')}</p>
            <p><strong>Fibre Port:</strong> ${escapeHTML(unitData.fibrePort || 'N/A')}</p>
            <p><strong>Data Ports:</strong> ${escapeHTML(unitData.dataPort || 'N/A')}</p>
            <p><strong>Water Pipe Ø:</strong> ${escapeHTML(unitData.waterPipeDia || 'N/A')}</p>
            <p><strong>Floor Traps:</strong> ${escapeHTML(unitData.floorTrap || 'N/A')}</p>
            <p><strong>Gas Pipe:</strong> ${escapeHTML(unitData.gasPipe || 'N/A')}</p>
            <p><strong>Kitchen EA:</strong> ${escapeHTML(unitData.kitchenEa || 'N/A')}</p>
            <p><strong>Kitchen FA:</strong> ${escapeHTML(unitData.kitchenFa || 'N/A')}</p>
            <p><strong>Sprinkler:</strong> ${escapeHTML(unitData.sprinkler || 'N/A')}</p>
            <p><strong>Notes:</strong> ${escapeHTML(unitData.otherNotes || 'N/A')}</p>
        `;
        detailsGrid.innerHTML = gridHTML;

        detailsContent.innerHTML = ''; // Clear previous content
        detailsContent.appendChild(detailsGrid);

        const downloadContainer = document.createElement('div');
        downloadContainer.id = 'download-button-container';
        detailsContent.appendChild(downloadContainer);

        if (unitData.detailPlanImagePath) {
            const planLink = document.createElement('a');
            planLink.href = unitData.detailPlanImagePath;
            planLink.download = `Unit_${unitData.unitIdDisplay}_Plan${getFileExtension(unitData.detailPlanImagePath)}`;
            planLink.textContent = 'Download Unit Plan';
            planLink.classList.add('download-button', 'plan');
            planLink.setAttribute('role', 'button');
            downloadContainer.appendChild(planLink);
        } else {
            const noPlanMsg = document.createElement('p');
            noPlanMsg.innerHTML = '<small>No detailed unit plan available.</small>';
            downloadContainer.appendChild(noPlanMsg);
        }

        // TXT Download (similar to original, adjust fields as needed)
        const infoLink = document.createElement('a');
        infoLink.textContent = 'Download Unit Info (TXT)';
        infoLink.classList.add('download-button', 'info');
        infoLink.setAttribute('role', 'button');
        infoLink.href = '#'; // Will be set by blob

        let textContent = `Unit Information - ${unitData.unitIdDisplay || 'N/A'}\n------------------------------------------\n`;
        const fieldsForTxt = [
            {label: "Unit No", value: unitData.unitIdDisplay}, {label: "Status", value: unitData.status},
            {label: "Area", value: unitData.area}, {label: "Water Point", value: unitData.waterPoint},
            {label: "A/C Power", value: unitData.acPower}, {label: "FCU Unit", value: unitData.fcuUnits},
            {label: "Elect. Isolator", value: unitData.elecIsolator}, {label: "Emergency Lights", value: unitData.emergencyLight},
            {label: "PA Speaker", value: unitData.paSpeaker}, {label: "Fibre Port", value: unitData.fibrePort},
            {label: "Data Port", value: unitData.dataPort}, {label: "Water Pipe Diameter", value: unitData.waterPipeDia},
            {label: "Floor Trap", value: unitData.floorTrap}, {label: "Gas Pipe Diamater", value: unitData.gasPipe},
            {label: "Kitchen EA", value: unitData.kitchenEa}, {label: "Kitchen FA", value: unitData.KitchenFa},
            {label: "Sprinkler", value: unitData.sprinkler},  {label: "Notes", value: unitData.otherNotes}
        ];
        fieldsForTxt.forEach(field => {
            textContent += `${field.label}: ${field.value || 'N/A'}\n`;
        });
        textContent += `------------------------------------------\nGenerated: ${new Date().toLocaleString()}\n`;

        const blob = new Blob([textContent], { type: 'text/plain' });
        const infoFileURL = URL.createObjectURL(blob);
        infoLink.href = infoFileURL;
        infoLink.download = `Unit_${unitData.unitIdDisplay}_Info.txt`;
        infoLink.addEventListener('click', () => setTimeout(() => URL.revokeObjectURL(infoFileURL), 100));
        downloadContainer.appendChild(infoLink);

        if (unitData.status && unitData.status.toLowerCase() === 'leased') {
            const leasedMsg = document.createElement('p');
            leasedMsg.style.color = 'red';
            leasedMsg.style.fontWeight = 'bold';
            leasedMsg.style.marginTop = '1rem';
            leasedMsg.style.textAlign = 'center';
            leasedMsg.textContent = 'Note: This unit is currently leased.';
            detailsContent.appendChild(leasedMsg);
        }
    }


    function displayErrorMessageInUnits(message) {
        unitButtonContainerParent.innerHTML = `<p style="text-align: center; color: red;">${message}</p>`;
    }
    function displayErrorMessageInFloorPlan(message) {
        floorPlanArea.innerHTML = `<p style="text-align: center; color: red;">${message}</p>`;
    }

    function clearUnitDisplay() {
        floorPlanArea.innerHTML = '';
        unitButtonContainerParent.innerHTML = '<p style="text-align: center; color: #666;">Select a level to see units.</p>';
    }

    // --- Magnify Floor Plan Logic (from original, ensure clickable-plan class is added to new images) ---
    function handleMagnify(event) {
        if (magnifyModal && modalImg && event.currentTarget.classList.contains('clickable-plan')) {
            magnifyModal.style.display = "block";
            modalImg.src = event.currentTarget.src;
            modalImg.alt = event.currentTarget.alt;
        }
    }

    if (closeModalBtn) {
        closeModalBtn.onclick = function() {
            if (magnifyModal) magnifyModal.style.display = "none";
        }
    }
    if (magnifyModal) {
        magnifyModal.onclick = function(event) {
            if (event.target == magnifyModal) magnifyModal.style.display = "none";
        }
    }

    // --- Helper Functions (from original) ---
    function getFileExtension(filename) {
        if (!filename || typeof filename !== 'string') return "";
        const lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex === -1) return "";
        return filename.substring(lastDotIndex);
    }

    function escapeHTML(str) {
        if (str === null || typeof str === 'undefined') return "N/A"; // Handle null or undefined
        str = String(str); // Ensure it's a string
        return str.replace(/[&<>"']/g, function (match) {
            return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[match];
        });
    }

    // --- Initialization ---
    generateLevelButtons(); // Generate level buttons and load data for the first level
});