document.addEventListener('DOMContentLoaded', () => {
    // 1. Session & auth guard
    const userJson = localStorage.getItem('user');
    if (!userJson) {
        window.location.href = '../index.html';
        return;
    }
    const user = JSON.parse(userJson);

    // Hydrate user widget (same IDs as other pages)
    const fullnameEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    const initialEl = document.getElementById('user-initial');

    if (fullnameEl) fullnameEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';
    if (initialEl && user.FullName) {
        initialEl.textContent = user.FullName.charAt(0).toUpperCase();
    }

    // Role-based nav filter (copy from areas.js)
    const userRole = user.Role;
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        const allowedRoles = link.getAttribute('data-role');
        if (!allowedRoles || allowedRoles === 'all') return;
        if (userRole === 'Director') return;
        const rolesArray = allowedRoles.split(',').map(r => r.trim());
        if (!rolesArray.includes(userRole)) link.remove();
    });

    // 2. Parse area id
    const params = new URLSearchParams(window.location.search);
    const areaId = params.get('id');
    if (!areaId) {
        alert('No area selected.');
        window.location.href = 'areas.html';
        return;
    }

    // 3. Wire events
    const form = document.getElementById('editAreaForm');
    const deleteBtn = document.getElementById('btn-delete-area');

    if (form) {
        form.addEventListener('submit', e => handleUpdateArea(e, areaId));
    }
    if (deleteBtn) {
        deleteBtn.addEventListener('click', () => handleDeleteArea(areaId));
    }

    // Optional: preview file inputs
    setupImagePreview('input-layout', 'img-layout');
    setupImagePreview('input-front', 'img-front');
    // ... etc

    // 4. Load area details
    loadAreaDetails(areaId);
});

function setupImagePreview(inputId, imgId) {
    const input = document.getElementById(inputId);
    const img = document.getElementById(imgId);
    if (!input || !img) return;

    input.addEventListener('change', () => {
        const file = input.files[0];
        if (!file) return;
        img.src = URL.createObjectURL(file);
        img.classList.remove('hidden');
    });
}

async function loadAreaDetails(areaId) {
    const errorEl = document.getElementById('edit-error');
    try {
        const res = await fetch(`../api/get_area.php?id=${encodeURIComponent(areaId)}`);
        if (!res.ok) throw new Error('Failed to load area');
        const area = await res.json();

        // Fill header
        const titleEl = document.getElementById('area-title');
        const subEl = document.getElementById('area-subtitle');
        const idPill = document.getElementById('area-id-pill');
        if (titleEl) titleEl.textContent = area.Name || 'Manage Area';
        if (subEl) subEl.textContent = area.Description || 'Edit project configuration and images.';
        if (idPill) idPill.textContent = `ID: ${area.Id}`;

        // Fill form
        document.getElementById('area-name').value = area.Name || '';
        document.getElementById('area-description').value = area.Description || '';
        document.getElementById('area-base-price').value = area.BasePricePerPlot || '';
        document.getElementById('area-min-price').value = area.MinPrice || '';
        document.getElementById('area-max-price').value = area.MaxPrice || '';
        document.getElementById('area-development-type').value = area.DevelopmentType || '';
        document.getElementById('area-category').value = area.Category || 'Residential';
        document.getElementById('area-status').value = area.ProjectStatus || 'Ongoing';
        document.getElementById('area-show-website').value = area.ShowOnWebsite ? '1' : '0';
        document.getElementById('area-configurations').value = area.Configurations || '';

        // Existing images (optional: your API should return URLs)
        if (area.LayoutImageUrl) showImage('img-layout', area.LayoutImageUrl);
        if (area.FrontImageUrl) showImage('img-front', area.FrontImageUrl);
        // etc.
    } catch (err) {
        console.error(err);
        if (errorEl) {
            errorEl.textContent = 'Error loading area details.';
            errorEl.classList.remove('hidden');
        }
    }
}

function showImage(imgId, url) {
    const img = document.getElementById(imgId);
    if (!img) return;
    img.src = url;
    img.classList.remove('hidden');
}

async function handleUpdateArea(e, areaId) {
    e.preventDefault();
    const errorEl = document.getElementById('edit-error');

    // Role guard – only Director can update
    const userJson = localStorage.getItem('user');
    const user = userJson ? JSON.parse(userJson) : null;
    if (!user || user.Role !== 'Director') {
        if (errorEl) {
            errorEl.textContent = 'Only Directors can update areas.';
            errorEl.classList.remove('hidden');
        } else {
            alert('Only Directors can update areas.');
        }
        return;
    }

    const form = e.target;
    const submitBtn = form.querySelector('button[type="submit"]');
    if (!submitBtn) return;

    const formData = new FormData(form);
    formData.append('id', areaId);

    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Saving...';

    try {
        const res = await fetch('../api/update_area.php', {
            method: 'POST',
            body: formData        // allows file upload
        });

        const text = await res.text();
        let result;
        try { result = JSON.parse(text); } catch {
            throw new Error('Invalid server response.');
        }

        if (result.success) {
            alert('Area updated successfully.');
        } else {
            throw new Error(result.message || 'Failed to update area.');
        }
    } catch (err) {
        console.error(err);
        if (errorEl) {
            errorEl.textContent = err.message || 'Server error updating area.';
            errorEl.classList.remove('hidden');
        }
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-save mr-2"></i> Save Changes';
    }
}

async function handleDeleteArea(areaId) {
    if (!confirm('Are you sure? This will delete the area only if there are no plots.')) return;

    const errorEl = document.getElementById('edit-error');

    // Role guard
    const userJson = localStorage.getItem('user');
    const user = userJson ? JSON.parse(userJson) : null;
    if (!user || user.Role !== 'Director') {
        if (errorEl) {
            errorEl.textContent = 'Only Directors can delete areas.';
            errorEl.classList.remove('hidden');
        } else {
            alert('Only Directors can delete areas.');
        }
        return;
    }

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

        const text = await res.text();
        let result;
        try { result = JSON.parse(text); } catch {
            throw new Error('Invalid server response.');
        }

        if (result.success) {
            alert('Area deleted.');
            window.location.href = 'areas.html';
        } else {
            throw new Error(result.message || 'Failed to delete area. Make sure there are no plots.');
        }
    } catch (err) {
        console.error(err);
        if (errorEl) {
            errorEl.textContent = err.message || 'Server error deleting area.';
            errorEl.classList.remove('hidden');
        }
    }
}
