document.addEventListener("DOMContentLoaded", () => {
    // 1. Define element references
    const mapForm = document.getElementById("mapForm");
    const deptList = document.getElementById("deptList");
    const tableBody = document.getElementById("tableBody");
    const deptSelect = document.getElementById("deptSelect");

    // 2. SAFETY CHECK: If the elements aren't here, stop the script.
    // This prevents the TypeError seen in image_4ccbf7.png
    if (!mapForm || !deptList || !tableBody || !deptSelect) {
        console.log("MapLabDepartments: Required elements not found. Skipping execution.");
        return;
    }

    const API = {
        FETCH: "../../dripend/systemSetup/laboratory/fetchMapLabDepartments.php",
        PROCESS: "../../dripend/systemSetup/laboratory/processAddMapLabDepartments.php"
    };

    let departments = [];
    let investigations = [];

    async function load() {
        const res = await fetch(API.FETCH);
        const json = await res.json();

        if (!json.success) return;

        departments = json.data.departments;
        investigations = json.data.investigations;

        renderDepartments();
        renderDropdown();
        renderTable();
    }

    function renderDepartments() {
        deptList.innerHTML = departments.map(d => `
            <div class="lrm-filter-item" data-id="${d.id}">
                ${d.sub_dept_name}
            </div>
        `).join("");

        deptList.querySelectorAll(".lrm-filter-item").forEach(el => {
            el.onclick = () => {
                deptSelect.value = el.dataset.id;
            };
        });
    }

    function renderDropdown() {
        deptSelect.innerHTML = `
            <option value="">Select Sub Department</option>
            ${departments.map(d => `
                <option value="${d.id}">${d.sub_dept_name}</option>
            `).join("")}
        `;
    }

    function renderTable() {
        tableBody.innerHTML = investigations.map(i => `
            <tr>
                <td><input type="checkbox" class="chk" value="${i.service_id}"></td>
                <td>${i.service_name}</td>
                <td>${i.sub_dept_name ?? 'Unassigned'}</td>
            </tr>
        `).join("");
    }

    mapForm.addEventListener("submit", async (e) => {
        e.preventDefault();

        const selected = [...document.querySelectorAll(".chk:checked")].map(x => x.value);
        const dept = deptSelect.value;

        if (!dept || selected.length === 0) {
            alert("Select department and investigations");
            return;
        }

        const form = new FormData();
        form.append("target_department", dept);
        form.append("action", "update_mappings");
        selected.forEach(s => form.append("selected_services[]", s));

        const res = await fetch(API.PROCESS, { method: "POST", body: form });
        const json = await res.json();
        alert(json.message);
        load();
    });

    load();
});