$(function () {
    // === 1. VARIABEL GLOBAL & KONSTANTA ===
    let isLoadingTable = false;
    window.activeViewTable = window.activeViewTable || null;
    const SKIP_FORM_COLS = ['created_at', 'updated_at', 'deleted_at', 'timestamp', 'created_by', 'updated_by'];

    // --- UTILITY: Mendapatkan Nama Tabel Aktif ---
    function getActiveTable(element = null) {
        // Cek urutan: activeViewTable > data-table dari elemen > window.currentTable
        const table = window.activeViewTable || (element ? $(element).data('table') : null) || window.currentTable;
        if (!table) {
            Swal.fire('Error', 'Nama tabel tidak ditemukan.', 'error');
            console.error('Tabel aktif tidak dapat ditentukan.');
            return null;
        }
        return table;
    }

    // --- UTILITY: Mendapatkan ID Data dari Elemen ---
    function getDataId(element) {
        let id = $(element).data('id');
        if (!id && element.id) {
            // Logika untuk id dari ID elemen: btn-action-tableName-idData
            const parts = element.id.split('-');
            if (parts.length >= 4 && parts[0] === 'btn' && parts[2] === 'table') {
                id = parts.slice(3).join('-');
            } else if (element.id.startsWith('switch_')) {
                const switchParts = element.id.split('_');
                id = switchParts.length >= 4 ? switchParts.slice(3).join('_') : null;
            }
        }
        if (!id) {
            Swal.fire('Error', 'ID data tidak ditemukan.', 'error');
            console.error('ID data tidak dapat ditentukan.');
        }
        return id;
    }

    // --- UTILITY: Pemuatan Ulang Konten Tabel ---
    window.reloadTable = function (inputTable = null) {
        const targetTable = getActiveTable() || inputTable;
        if (!targetTable) return; // Error sudah ditangani di getActiveTable

        $('#crud-content').html(`
            <div class="text-center p-4"><i class="fa fa-spin fa-spinner"></i> Memuat ulang data <b>${targetTable}</b>...</div>
        `);

        $.get(`${CRUD.baseUrl}/crud/loadTableContent/${targetTable}`)
            .done(function (html) {
                $('#crud-content').html(html);
                window.initDataTable(targetTable);
            })
            .fail(() => {
                Swal.fire('Error', 'Gagal memuat ulang data tabel.', 'error');
            });
    };

    // --- UTILITY: Handler Response Sukses/Gagal (Swal) ---
    function handleResponse(res, successMessage = 'Operasi berhasil.', errorMessage = 'Operasi gagal.', successCallback = null) {
        if (res.status === 'success') {
            Swal.fire({
                icon: 'success',
                text: res.message || successMessage,
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                if (successCallback) successCallback(res);
            });
        } else {
            Swal.fire({
                icon: 'error',
                text: res.message || errorMessage,
                timer: 2000,
                showConfirmButton: false
            });
        }
    }

    // --- UTILITY: Fetch Data (Structure/Row) ---
    function fetchData(url) {
        return $.get(url, 'json').fail(xhr => {
            console.error('Gagal fetch data:', xhr);
            Swal.fire('Error', 'Terjadi kesalahan saat mengambil data dari server.', 'error');
        });
    }

    // --- UTILITY: Show Loading SweetAlert ---
    function showLoadingSwal(title = 'Memproses...', text = '') {
        Swal.fire({
            title: title,
            text: text,
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });
    }

    // -------------------------------------------------------------------
    // === 2. SIDEBAR: KLIK TABEL (Pemuatan Konten) ===
    // -------------------------------------------------------------------
    $(document).on('click', '.table-link', function (e) {
        e.preventDefault();

        if (isLoadingTable) {
            console.warn('Sedang memuat tabel, harap tunggu...');
            return;
        }

        const table = $(this).data('table');
        if (!table) return; // Error sudah ditangani di getActiveTable

        isLoadingTable = true;
        window.currentTable = table;
        localStorage.setItem('lastSidebarTable', table);

        // Simpan ke session tanpa menunggu response
        $.post(`${CRUD.baseUrl}/crud/saveLastTable`, { table })
            .done(() => console.log('lastSidebarTable tersimpan di session:', table))
            .fail(xhr => console.warn('Gagal menyimpan lastSidebarTable:', xhr.statusText));

        // Update UI dan tampilkan loading
        $('.table-link').removeClass('active');
        $(this).addClass('active');
        $('#crud-content').html(`
            <div class="text-center p-5"><i class="fa fa-spin fa-spinner"></i> Memuat data <b>${table}</b>...</div>
        `);

        // Load konten
        $.get(`${CRUD.baseUrl}/crud/loadTableContent/${table}`)
            .done(function (html) {
                $('#crud-content').html(html);
                window.initDataTable(table);
            })
            .fail(xhr => {
                console.error('Gagal memuat tabel:', xhr.responseText);
                Swal.fire('Error', `Gagal memuat tabel: ${table}`, 'error');
            })
            .always(() => isLoadingTable = false);
    });

    // -------------------------------------------------------------------
    // === 3. INIT DATATABLE ===
    // -------------------------------------------------------------------
    window.initDataTable = function (table) {
        window.currentTable = window.activeViewTable || table || window.currentTable;
        if (!window.currentTable) {
            Swal.fire('Error', 'Tabel aktif tidak ditemukan di initDataTable.', 'error');
            return;
        }

        const $table = $('#datatable');
        if (!$table.length) return;

        // Cegah error kolom kosong (jika tabel kosong)
        const $theadCols = $table.find('thead th').length;
        const $tbody = $table.find('tbody');

        if ($tbody.find('tr').length === 0) {
            const emptyRow = `<tr><td colspan="${$theadCols}"></td></tr>`;
            $tbody.html(emptyRow);
        }

        // Inisialisasi DataTable
        const dt = $table.DataTable({
            destroy: true,
            pageLength: 10,
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/id.json'
            }
        });

        $table.data('DataTableInstance', dt).data('tableName', window.currentTable);
    };

    // -------------------------------------------------------------------
    // === 4. SIMPAN DATA (Tambah/Edit) ===
    // -------------------------------------------------------------------
    $(document).off('submit', '#crudForm').on('submit', '#crudForm', function (e) {
        e.preventDefault();

        const table = getActiveTable(this);
        if (!table) return;

        const formData = $(this).serialize();
        const url = `${CRUD.baseUrl}/crud/save/${table}`;

        $.post(url, formData, 'json')
            .done(function (res) {
                handleResponse(res, 'Data berhasil disimpan.', 'Gagal menyimpan data.', function (res) {
                    $('#formModal').modal('hide');
                    // Muat ulang dan highlight baris baru
                    $.get(`${CRUD.baseUrl}/crud/loadTableContent/${table}`)
                        .done(function (html) {
                            $('#crud-content').html(html);
                            window.initDataTable(table);
                            if (res.last_id) {
                                const $row = $('#datatable tr[data-id="' + res.last_id + '"]');
                                $row.addClass('highlight');
                                setTimeout(() => $row.removeClass('highlight'), 2000);
                            }
                        });
                });
            })
            .fail(() => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Tidak dapat menghubungi server.',
                    timer: 2000,
                    showConfirmButton: false
                });
            });
    });

    // -------------------------------------------------------------------
    // === 5. VIEW DETAIL ===
    // -------------------------------------------------------------------
    $(document).on('click', '.view-btn, [id^="btn-view-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        const id = getDataId(this);
        if (!id) return;

        fetchData(`${CRUD.baseUrl}/crud/get/${table}/${id}`)
            .done(function (res) {
                if (res.status === 'success') {
                    let html = '<table class="table table-striped table-bordered"><tbody>';
                    for (const field in res.data) {
                        const safeValue = $('<div>').text(res.data[field] ?? '-').html();
                        html += `
                            <tr>
                                <th class="text-muted" style="width:30%; text-transform:capitalize;">${field.replace(/_/g, ' ')}</th>
                                <td class="fw-bold">${safeValue}</td>
                            </tr>`;
                    }
                    html += '</tbody></table>';

                    $('#viewContent').html(html);
                    $('#viewModal').modal('show');
                } else {
                    Swal.fire('Gagal', res.message || 'Tidak dapat mengambil data.', 'error');
                }
            });
    });

    // -------------------------------------------------------------------
    // === 6. GENERATE FORM FIELDS (internal function) ===
    // -------------------------------------------------------------------
    function generateFormFields(meta, data = {}) {
        const $tbody = $('#crudFormTable tbody').empty();
        const table = getActiveTable();
        if (!table) return;

        $('#crudForm').attr('data-table', table).find('input[type="hidden"]').remove();
        const pkCol = meta.find(c => c.key === 'PRI');

        // Tambahkan PK sebagai hidden field untuk Edit
        if (pkCol) {
            $('#crudForm').prepend(`
                <input type="hidden" name="${pkCol.name}" value="${data[pkCol.name] || ''}">
            `);
        }

        meta.forEach(col => {
            // Lewati kolom PK dan kolom skip
            if (col.key === 'PRI' || SKIP_FORM_COLS.includes(col.name.toLowerCase())) return;

            const type = col.type.toLowerCase();
            const value = data[col.name] ?? '';
            let input = '';
           // const isRequired = col.null !== 'YES';
const isRequired = false; //
            // Logika pembuatan input
            if (type.startsWith('enum') || type.startsWith('set')) {
                const options = type.match(/\((.*?)\)/)[1].replace(/'/g, '').split(',').map(opt => opt.trim());
                input = `<select name="${col.name}" class="form-control" ${isRequired ? 'required' : ''}>`;
                options.forEach(o => {
                    input += `<option value="${o}" ${o === value ? 'selected' : ''}>${o}</option>`;
                });
                input += `</select>`;
            } else if (type.includes('date') || type.includes('timestamp')) {
                const inputType = type.includes('time') ? 'datetime-local' : 'date';
                input = `<input type="${inputType}" name="${col.name}" class="form-control" value="${value}" ${isRequired ? 'required' : ''}>`;
            } else if (type.includes('int') || type.includes('decimal') || type.includes('float')) {
                input = `<input type="number" name="${col.name}" class="form-control" value="${value}" ${isRequired ? 'required' : ''}>`;
            } else if (type.includes('text')) {
                input = `<textarea name="${col.name}" class="form-control" rows="3" ${isRequired ? 'required' : ''}>${value}</textarea>`;
            } else {
                input = `<input type="text" name="${col.name}" class="form-control" value="${value}" ${isRequired ? 'required' : ''}>`;
            }

            $tbody.append(`
                <tr>
                    <td class="px-2 py-2" style="width:30%; font-weight:bold; color:#6c757d; text-transform:capitalize;">${col.name.replace(/_/g, ' ')} ${isRequired ? '<span class="text-danger">*</span>' : ''}</td>
                    <td class="px-2 py-2">${input}</td>
                </tr>
            `);
        });
    }

    // -------------------------------------------------------------------
    // === 7. TAMBAH DATA ===
    // -------------------------------------------------------------------
    $(document).on('click', '.btn-add, [id^="btn-tambah-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        fetchData(`${CRUD.baseUrl}/crud/structure/${table}`)
            .done(function (res) {
                if (res.status === 'success') {
                    generateFormFields(res.meta);
                    $('#formModal .modal-title').text('Tambah Data ' + table);
                    $('#formModal').modal('show');
                } else {
                    Swal.fire('Error', res.message || 'Gagal memuat struktur tabel.', 'error');
                }
            });
    });

    // -------------------------------------------------------------------
    // === 8. EDIT DATA ===
    // -------------------------------------------------------------------
    $(document).on('click', '.edit-btn, [id^="btn-edit-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        const id = getDataId(this);
        if (!id) return;

        $.when(
            fetchData(`${CRUD.baseUrl}/crud/structure/${table}`),
            fetchData(`${CRUD.baseUrl}/crud/get/${table}/${id}`)
        )
        .done(function (structRes, dataRes) {
            const struct = structRes[0];
            const row = dataRes[0];

            if (struct.status === 'success' && row.status === 'success') {
                generateFormFields(struct.meta, row.data);
                $('#formModal .modal-title').text('Edit Data ' + table);
                $('#formModal').modal('show');
            } else {
                Swal.fire('Error', struct.message || row.message || 'Gagal memuat struktur atau data.', 'error');
            }
        });
    });

    // -------------------------------------------------------------------
    // === 9. HAPUS DATA & HAPUS SEMUA DATA ===
    // -------------------------------------------------------------------
    const handleDelete = function (isDeleteAll) {
        return function () {
            const table = getActiveTable(this);
            if (!table) return;

            const id = isDeleteAll ? null : getDataId(this);
            if (!isDeleteAll && !id) return;

            const url = isDeleteAll ? `${CRUD.baseUrl}/crud/deleteAll/${table}` : `${CRUD.baseUrl}/crud/delete/${table}/${id}`;
            const title = isDeleteAll ? 'Yakin hapus **semua** data?' : 'Yakin hapus data ini?';
            const text = isDeleteAll ? 'Semua data di tabel ini akan dihapus permanen!' : 'Data yang dihapus tidak bisa dikembalikan!';
            const confirmText = isDeleteAll ? 'Ya, hapus semua' : 'Ya, hapus';
            const successMsg = isDeleteAll ? 'Semua data berhasil dihapus.' : 'Data berhasil dihapus';
            const failMsg = isDeleteAll ? 'Gagal menghapus semua data.' : 'Gagal menghapus data.';

            Swal.fire({
                title: title,
                text: text,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: confirmText,
                cancelButtonText: 'Batal'
            }).then(result => {
                if (!result.isConfirmed) return;

                $.post(url, 'json')
                    .done(function (res) {
                        handleResponse(res, successMsg, failMsg, () => window.reloadTable(table));
                    })
                    .fail(() => {
                        Swal.fire('Error', 'Terjadi kesalahan pada server.', 'error');
                    });
            });
        };
    };

    $(document).on('click', '.delete-btn, [id^="btn-delete-"]', handleDelete(false));
    $(document).on('click', '.btn-delete-all, [id^="btn-deleteall-"]', handleDelete(true));

    // -------------------------------------------------------------------
    // === 10. EXPORT & IMPORT ===
    // -------------------------------------------------------------------
    $(document).on('click', '.btn-export, [id^="btn-export-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;
        window.location.href = `${CRUD.baseUrl}/crud/export/${table}`;
    });

    $(document).on('click', '.btn-import, [id^="btn-import-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        $('#importModal')
            .data('table', table)
            .find('.modal-title').text('Import Data ' + table);
        $('#importModal').modal('show');
    });

    $(document).off('submit', '#importForm').on('submit', '#importForm', function (e) {
        e.preventDefault();
        const table = getActiveTable($('#importModal').data('table'));
        if (!table) return;

        showLoadingSwal('Mengupload data...');

        $.ajax({
            url: `${CRUD.baseUrl}/crud/import/${table}`,
            type: 'POST',
            data: new FormData(this),
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function (res) {
                Swal.close();
                if (res.status === 'success') {
                    $('#importModal').modal('hide');
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil!',
                        html: `<b>${res.inserted || 0}</b> data baru<br><b>${res.updated || 0}</b> data diperbarui.`,
                        timer: 2000,
                        showConfirmButton: false
                    }).then(() => {
                        window.reloadTable(table);
                        // Highlight baris yang baru ditambahkan
                        res.inserted_ids?.forEach(id => {
                            const $row = $('#datatable tr[data-id="' + id + '"]');
                            $row.addClass('highlight');
                            setTimeout(() => $row.removeClass('highlight'), 3000);
                        });
                    });
                } else {
                    Swal.fire('Gagal', res.message || 'Terjadi kesalahan saat memproses file.', 'error');
                }
            },
            error: function () {
                Swal.close();
                Swal.fire('Error', 'Gagal mengunggah file.', 'error');
            }
        });
    });

    // -------------------------------------------------------------------
    // === 11. PRINT TABEL ===
    // -------------------------------------------------------------------
    $(document).on('click', '.btn-print, [id^="btn-print-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        const tableContent = document.querySelector('#crud-content table');
        if (!tableContent) {
            Swal.fire('Oops', 'Tabel data tidak ditemukan!', 'warning');
            return;
        }

        let titleText = document.querySelector('#crud-content h4')?.innerText.trim() || 'Data Tabel';
        if (!titleText.toLowerCase().includes(table.toLowerCase())) {
            titleText += ` (${table})`;
        }

        const clonedTable = tableContent.cloneNode(true);
        // Hapus kolom aksi
        clonedTable.querySelectorAll('tr').forEach(row => {
            let actionIndex = -1;
            row.querySelectorAll('th, td').forEach((cell, index) => {
                if (cell.querySelector('.btn') || /aksi|action/i.test(cell.innerText.trim())) {
                    actionIndex = index;
                }
            });
            if (actionIndex > -1 && row.cells[actionIndex]) {
                row.deleteCell(actionIndex);
            }
        });

        const printWindow = window.open('', '_blank', 'width=1000,height=700');
        printWindow.document.write(`
            <html>
            <head>
                <title>${titleText}</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
                <style>
                    body { padding: 20px; font-size: 14px; color: #000; }
                    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
                    th, td { border: 1px solid #999; padding: 8px; text-align: left; }
                    th { background-color: #f8f9fa; }
                    h4 { margin-bottom: 20px; text-align: center; }
                    @media print { @page { margin: 20mm; } }
                </style>
            </head>
            <body>
                <h4>${titleText}</h4>
                ${clonedTable.outerHTML}
                <script>window.onload = function(){ window.print(); }</script>
            </body>
            </html>
        `);
        printWindow.document.close();
    });

    // -------------------------------------------------------------------
    // === 12. TOGGLE STATUS ===
    // -------------------------------------------------------------------
    $(document).on('change', '.toggle-status, [id^="switch_"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        const column = $(this).data('column');
        const id = getDataId(this);
        if (!id || !column) {
            Swal.fire('Error', 'Data toggle tidak lengkap.', 'error');
            return;
        }

        const status = $(this).is(':checked') ? 'aktif' : 'nonaktif';

        $.post(`${CRUD.baseUrl}/crud/updateToggle`, { table, column, id, status }, 'json')
            .done(function (res) {
                handleResponse(res, `Status berhasil diubah menjadi ${status}.`, 'Gagal memperbarui status.');
            })
            .fail(() => {
                Swal.fire('Error!', 'Tidak dapat terhubung ke server.', 'error');
            });
    });

    // -------------------------------------------------------------------
    // === 13. GENERATE DATA ===
    // -------------------------------------------------------------------
    $(document).on('click', '.btn-generate, [id^="btn-generate-"]', function () {
        const table = getActiveTable(this);
        if (!table) return;

        Swal.fire({
            title: 'Generate Data?',
            text: 'Data otomatis akan dibuat untuk tabel: ' + table,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Ya, lanjutkan',
            cancelButtonText: 'Batal'
        }).then(result => {
            if (!result.isConfirmed) return;

            showLoadingSwal();

            $.get(`${CRUD.baseUrl}/crud/generate/${table}`, 'json')
                .done(function (res) {
                    Swal.close();
                    handleResponse(res, 'Generate selesai.', 'Terjadi kesalahan saat generate data.', () => window.reloadTable(table));
                })
                .fail(xhr => {
                    Swal.close();
                    Swal.fire('Error', `Tidak dapat menghubungi server (${xhr.status})`, 'error');
                });
        });
    });

   // -------------------------------------------------------------------
// === 14. ACTIVE VIEW TOGGLE ===
// -------------------------------------------------------------------
$(document).on('click', '.activeView, [id^="btn-activeview-"]', function (e) {
    e.preventDefault();
    const table = getActiveTable(this);
    if (!table) return;

    const $btn = $('.activeView[data-table="' + table + '"]');
    // Periksa status saat ini berdasarkan window.activeViewTable atau class CSS
    const isCurrentlyActive = (window.activeViewTable === table) || $btn.hasClass('btn-success');
    
    const actionTitle = isCurrentlyActive ? 'Nonaktifkan View?' : 'Aktifkan View?';
    const actionText = isCurrentlyActive ? `Mematikan tampilan aktif untuk tabel: ${table}` : `Mengatur tampilan aktif untuk tabel: ${table}`;
    const confirmText = isCurrentlyActive ? 'Ya, nonaktifkan!' : 'Ya, aktifkan!';

    Swal.fire({
        title: actionTitle,
        text: actionText,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: confirmText,
        cancelButtonText: 'Batal'
    }).then(result => {
        if (!result.isConfirmed) return;

        const originalHtml = $btn.html();
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Memproses...');
        // Pastikan fungsi showLoadingSwal() sudah didefinisikan
        showLoadingSwal(); 

        $.post(`${CRUD.baseUrl}/crud/activeView/${table}`, 'json')
            .done(function (response) {
                Swal.close(); // Tutup loading Swal
                
                if (response.success) {
                    const newActive = typeof response.active !== 'undefined' ? response.active : !isCurrentlyActive;
                    const successMsg = newActive ? 'Active view diaktifkan.' : 'Active view dinonaktifkan.';

                    // 1. Update global state
                    window.activeViewTable = newActive ? table : null;
                    
                    // 2. Update UI Tombol: Set semua tombol nonaktif, lalu aktifkan yang baru (jika ada)
                    $('.activeView')
                        .removeClass('btn-success').addClass('btn-secondary')
                        .prop('disabled', false)
                        .html('<i class="fa fa-eye"></i> Active View');

                    if (newActive) {
                        $btn.removeClass('btn-secondary').addClass('btn-success');
                    }

                    // 3. Simpan status ke session PHP & localStorage (Asinkron)
                    const finalTable = newActive ? table : (response.activeTable || localStorage.getItem('lastSidebarTable'));
                    localStorage.setItem('lastSidebarTable', finalTable);
                    $.post(`${CRUD.baseUrl}/crud/saveLastTable`, { table: finalTable });

                    // 4. Tampilkan Swal Sukses (Menggunakan icon: 'success' secara langsung)
                    Swal.fire({
                        icon: 'success', 
                        title: 'Berhasil!',
                        text: response.message || successMsg,
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        // 5. Reload (jika nonaktif) setelah Swal selesai
                        if (!newActive) {
                            // Beri jeda singkat agar user melihat Swal sebelum reload
                            setTimeout(() => location.reload(), 100); 
                        }
                    });

                } else {
                    // BLOK GAGAL DARI RESPON SERVER (response.success = false)
                    Swal.fire('Gagal!', response.message || 'Operasi gagal.', 'error');
                }
            })
            .fail(function () {
                // BLOK GAGAL DARI AJAX/NETWORK/JSON PARSE ERROR
                Swal.close();
                Swal.fire('Error!', 'Terjadi kesalahan pada server atau koneksi jaringan.', 'error');
            })
            .always(function () {
                // Reset tombol regardless of success/fail
                $btn.prop('disabled', false).html(originalHtml);
            });
    });
});
    // -------------------------------------------------------------------
    // === 15. RESET FORM SETELAH MODAL DITUTUP ===
    // -------------------------------------------------------------------
    $('#formModal').on('hidden.bs.modal', function () {
        $('#crudForm input, #crudForm select, #crudForm textarea')
            .prop('readonly', false).prop('disabled', false);
        $('#crudForm button[type=submit]').show();
        $('#crudForm input[type="hidden"]').remove(); // Hapus hidden PK field
    });

   // ===================================================================
// === AUTO KLIK SIDEBAR TERAKHIR DAN SMART RELOAD ===
// ===================================================================
(function () {

    // Fungsi reload tabel berdasarkan table-link
    function loadTable(table) {
        const $link = $('.table-link[data-table="' + table + '"]');
        if ($link.length) {
            setTimeout(() => $link.trigger('click'), 400);
        } else {
            console.warn('Table-link untuk', table, 'tidak ditemukan.');
        }
    }

    // 1️⃣ Auto klik sidebar terakhir
    $(document).ready(function () {
        const lastTable = localStorage.getItem('lastSidebarTable');
        if (lastTable) {
            // Tunggu sampai DOM dan event binding CRUD siap
            const interval = setInterval(() => {
                if ($('.table-link').length) {
                    loadTable(lastTable);
                    clearInterval(interval);
                }
            }, 200); // cek setiap 200ms
            setTimeout(() => clearInterval(interval), 5000); // stop setelah 5 detik
        }
    });

    // 2️⃣ Smart reload F5 / Ctrl+R
    function isActiveView() {
        return Boolean(window.activeViewTable);
    }

    function reloadActiveViewContent() {
        if (!isActiveView()) return;
        const table = window.activeViewTable;

        const interval = setInterval(() => {
            if ($('.table-link[data-table="' + table + '"]').length) {
                loadTable(table);
                clearInterval(interval);
            }
        }, 200);
        setTimeout(() => clearInterval(interval), 5000); // stop setelah 5 detik
    }

    $(document).on('keydown', function (e) {
        const isReload = (e.which || e.keyCode) === 116 || ((e.which || e.keyCode) === 82 && (e.ctrlKey || e.metaKey));
        if (isReload && isActiveView()) {
            e.preventDefault();
            reloadActiveViewContent();
        }
    });

})();

});