document.addEventListener("DOMContentLoaded", function () {

    function setCookie(name, value, days = 365) {
        const expires = new Date(Date.now() + days * 864e5).toUTCString();
        document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expires + "; path=/";
    }

    $(".multi-filter-select").each(function () {

        const $tableEl = $(this);

        //
        // AUTO-BUILD columnDefs from <th data-column="">
        //
        const columnDefs = [];
        $tableEl.find("thead th").each(function (index) {
            const colName = $(this).data("column") || "";
            columnDefs.push({
                targets: index,
                name: colName
            });
        });

        //
        // INITIALIZE DATATABLE
        //
        let table = $tableEl.DataTable({

            autoWidth: false,
            pageLength: $tableEl.attr("data-page-length") ? parseInt($tableEl.attr("data-page-length"), 10) : 10,
            dom: "<'row'<'col-sm-12 col-md-9'f><'pl-3 col-sm-12 col-md-3'l>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",

            language: {
                search: "",
                lengthMenu: "Entries _MENU_"
            },
            order: (function () {
                let idx = 0;
                $tableEl.find("thead th").each(function (i) {
                    if ($(this).data("column") === "server_hostname") {
                        idx = i;
                    }
                });
                return [[idx, 'asc']];
            })(),
            columnDefs: columnDefs,
            initComplete: function () {

                const dtApi = this.api();

                dtApi.columns().every(function () {

                    const colIndex = this.index();
                    const th = $tableEl.find("thead th").eq(colIndex);
                    const colName = th.data("column");

                    if (!colName) return;

                    const footerCell = $(this.footer());
                    if (!footerCell.length) return;

                    footerCell.empty();
                    const select = $('<select class="form-select"><option value=""></option></select>')
                        .appendTo(footerCell)
                        .on('change', function () {
                            const val = $.fn.dataTable.util.escapeRegex($(this).val());
                            dtApi.column(colName + ":name")
                                .search(val ? '^' + val + '$' : '', true, false)
                                .draw();
                        });

                    const uniqueValues = new Set();
                    this.nodes().each(function (cell) {
                        const cleanText = $(cell).data("filter") || $(cell).text().trim();
                        if (cleanText !== "") uniqueValues.add(cleanText);
                    });

                    Array.from(uniqueValues).sort().forEach(v => {
                        select.append('<option value="' + v + '">' + v + '</option>');
                    });
                });

                //
                // APPLY CHECKBOX VISIBILITY DEFAULTS
                //
                // Set initial visibility based on checkboxes
                const $checkboxes = $(".selectgroup-input");
                $checkboxes.each(function () {
                    const baseName = $(this).val();
                    const visible = $(this).is(":checked");

                    dtApi.columns().every(function () {
                        const name = this.settings()[0].aoColumns[this.index()].name || '';
                        if (name === baseName || name.startsWith(baseName + '_')) {
                            this.visible(visible);
                        }
                    });
                });

                $checkboxes.on("change", function () {
                    const selected = [];

                    $checkboxes.filter(":checked").each(function () {
                        selected.push($(this).val());
                    });

                    setCookie("serverTableColumns", JSON.stringify(selected), 365);

                    const baseName = $(this).val();
                    const visible = $(this).is(":checked");

                    table.columns(`[data-column^='${baseName}']`).visible(visible);
                });
            }
        });

        //
        // SEARCH FIELD ICON
        //
        $tableEl.closest('.dataTables_wrapper').find('[type=search]').each(function () {
            $(this).attr("placeholder", __('search'));
        });

        //
        // HANDLE CHECKBOX TOGGLE
        //
        $(".selectgroup-input").on("change", function () {
            const colName = $(this).val();
            table.column(colName + ":name").visible($(this).is(":checked"));
        });

    });
});