// Global variable to store the current floor
let currentFloor = 1;

// Fallback data in case API fails
const fallbackSensors = {
    1: [
        { id: 1, x: 100, y: 100, floor: 1, location: "Room A", value: "22°C" },
        { id: 2, x: 200, y: 200, floor: 1, location: "Room B", value: "24°C" },
    ],
    2: [
        { id: 3, x: 150, y: 150, floor: 2, location: "Living Room", value: "23°C" },
        { id: 4, x: 250, y: 250, floor: 2, location: "Kitchen", value: "21°C" },
    ],
    3: [
        { id: 5, x: 120, y: 120, floor: 3, location: "Hallway", value: "22°C" },
        { id: 6, x: 220, y: 220, floor: 3, location: "Bathroom", value: "23°C" },
    ]
};

// Function to fetch sensors from the API
async function fetchSensors() {
    try {
        const response = await fetch('/api/sensors');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log("Fetched sensors:", data);
        
        if (data.length === 0) {
            console.warn("No sensors returned from API, using fallback data");
            return fallbackSensors[currentFloor];
        }
        
        return data;
    } catch (error) {
        console.error("Could not fetch sensors:", error);
        console.warn("Using fallback sensor data due to API error");
        return fallbackSensors[currentFloor];
    }
}

// Function to display the map for the corresponding floor
function showFloor(floor) {
    console.log(`Showing floor ${floor}`);
    currentFloor = floor;
    const map = document.getElementById('map');
    map.src = `images/floor${floor}.png`;
    
    // Fetch and display sensors for this floor
    fetchSensors().then(sensors => {
        // Filter sensors for the current floor
        const floorSensors = sensors.filter(sensor => parseInt(sensor.floor) === parseInt(floor));
        console.log(`Sensors for floor ${floor}:`, floorSensors);
        
        if (floorSensors.length === 0) {
            console.warn(`No sensors found for floor ${floor}, adding test sensors`);
            // Add test sensors if none found
            addTestSensors();
        } else {
            addSensorsToMap(floorSensors);
        }
        
        // Clear the sensor data table
        const table = document.getElementById('sensor-data');
        table.innerHTML = `
            <tr>
                <th>ID</th>
                <th>Location</th>
                <th>Value</th>
            </tr>
        `;
    });
}

// Add sensor points to the map
function addSensorsToMap(floorSensors) {
    // First clear all previous points
    const mapContainer = document.getElementById('map-container');
    const existingPoints = document.querySelectorAll('.sensor');
    existingPoints.forEach(point => point.remove());
    
    console.log("Map container:", mapContainer);
    
    // Check if we have sensors to display
    if (!floorSensors || floorSensors.length === 0) {
        console.warn("No sensors found for this floor");
        return;
    }

    // Create new points
    floorSensors.forEach(sensor => {
        console.log(`Creating sensor point at x:${sensor.x}, y:${sensor.y}`);
        const sensorPoint = document.createElement('div');
        sensorPoint.classList.add('sensor');
        sensorPoint.style.position = 'absolute';
        sensorPoint.style.left = `${sensor.x}px`;
        sensorPoint.style.top = `${sensor.y}px`;
        sensorPoint.style.width = '15px';
        sensorPoint.style.height = '15px';
        sensorPoint.style.borderRadius = '50%';
        sensorPoint.style.backgroundColor = 'red';
        sensorPoint.style.border = '2px solid black';
        sensorPoint.style.zIndex = '1000';
        sensorPoint.setAttribute('data-id', sensor.id);
        sensorPoint.addEventListener('click', () => showSensorData(sensor));

        mapContainer.appendChild(sensorPoint);
    });
}

// Add test sensors if API sensors aren't working
function addTestSensors() {
    const testSensors = fallbackSensors[currentFloor];
    addSensorsToMap(testSensors);
}

// Display sensor data in the dashboard
function showSensorData(sensor) {
    const table = document.getElementById('sensor-data');
    
    // Clear the table
    table.innerHTML = `
        <tr>
            <th>ID</th>
            <th>Location</th>
            <th>Value</th>
        </tr>
    `;

    // Add a new row with sensor data
    const row = table.insertRow(1);
    row.insertCell(0).textContent = sensor.id;
    row.insertCell(1).textContent = sensor.location;
    row.insertCell(2).textContent = sensor.value;
}

// Initialize the app by showing floor 1 when the page loads
window.onload = function() {
    console.log("Page loaded, initializing app...");
    showFloor(1);
    
    // Add additional test sensor directly to verify positioning
    setTimeout(() => {
        const mapContainer = document.getElementById('map-container');
        const testPoint = document.createElement('div');
        testPoint.style.position = 'absolute';
        testPoint.style.left = '300px';
        testPoint.style.top = '300px';
        testPoint.style.width = '20px';
        testPoint.style.height = '20px';
        testPoint.style.borderRadius = '50%';
        testPoint.style.backgroundColor = 'blue';
        testPoint.style.border = '3px solid yellow';
        testPoint.style.zIndex = '9999';
        
        mapContainer.appendChild(testPoint);
        console.log("Test point added to verify positioning");
    }, 3000);
};