try {
    // Object to hold DataTables to prevent multi-initialization memory leaks
    window.workflowDataTables = {};

    $.fn.dataTable.ext.errMode = 'none';

    window.initWorkflowEngineConfig = function() {
        const apiUrl = '/rimax/application/dripend/systemSetup/ipd/processWorkflowEngine.php';

        const renderIndex = (data, type, row, meta) => `<strong>${meta.row + 1}</strong>`;
        const renderStatus = (data) => data == 1 ? '<span class="badge bg-success bg-opacity-10 text-success border border-success">Active</span>' : '<span class="badge bg-secondary bg-opacity-10 text-secondary border border-secondary">Inactive</span>';
        
        const renderActions = (type, id, isActive) => {
            let toggleClass = isActive == 1 ? 'btn-outline-warning' : 'btn-outline-success';
            let toggleText = isActive == 1 ? '<i class="fa fa-pause"></i>' : '<i class="fa fa-play"></i>';
            return `
                <div class="btn-group shadow-sm">
                    <button class="btn btn-sm btn-primary" onclick="editWorkflowRecord('${type}', ${id})" title="Edit"><i class="fa fa-edit"></i></button>
                    <button class="btn btn-sm ${toggleClass}" onclick="toggleWorkflowData('${type}', ${id}, ${isActive == 1 ? 0 : 1})" title="Toggle Status">${toggleText}</button>
                    <button class="btn btn-sm btn-danger" onclick="deleteWorkflowData('${type}', ${id})" title="Delete"><i class="fa fa-trash"></i></button>
                </div>
            `;
        };

        // LAZY-LOAD INIT FUNCTION
        function loadTableData(type) {
            if (window.workflowDataTables[type]) {
                // If it exists, just do a silent real-time refresh
                window.workflowDataTables[type].ajax.reload(null, false);
                return;
            }

            // Map columns based on special types
            let columns = [
                { data: null, render: renderIndex }, 
                { data: 'name', render: d => `<b>${d}</b>` }
            ];

            if (type === 'adm_priority') {
                columns.push({ data: 'color_code', render: d => `<span class="badge text-white" style="background-color: ${d}; border:1px solid #333; min-width:60px;">${d}</span>` });
            }
            if (type === 'round_outcome') {
                columns.push({ data: 'triggers_action', render: d => d ? `<code class="small text-danger">${d}</code>` : '<span class="text-muted small">None</span>' });
            }

            columns.push({ data: 'is_active', render: renderStatus });
            columns.push({ data: null, orderable: false, render: (d,t,r) => renderActions(type, r.id, r.is_active) });

            // Initialize DataTable
            window.workflowDataTables[type] = $('#tbl_' + type).DataTable({
                ajax: { url: apiUrl, type: 'POST', data: { action: 'fetch_dictionaries', dict_type: type } },
                pageLength: 10,
                columns: columns
            });
        }

        // Initialize the first active tab on page load
        let initialType = $('#v-pills-tab .nav-link.active').data('type');
        if(initialType) loadTableData(initialType);

        // Listen for Tab Clicks to Lazy Load Tables
        $('button[data-bs-toggle="pill"]').on('shown.bs.tab', function (e) {
            let type = $(e.target).data('type');
            if (type) loadTableData(type);
        });

        // MODAL OPEN FUNCTION
        window.openWorkflowModal = function(type, title) {
            $('#frmWorkflowDict')[0].reset(); 
            $('#wf_id').val(''); 
            $('#wf_dict_type').val(type); 
            $('#wfModalTitle').text('Add ' + title);
            
            let html = '';
            if (type === 'adm_priority') {
                html = `<div class="mb-3"><label class="form-label fw-bold">Priority Level <span class="text-danger">*</span></label><input type="text" name="dict_name" id="wf_name" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label fw-bold text-primary">UI Color Code</label><input type="color" name="color_code" id="wf_color" class="form-control form-control-color w-100" value="#0d6efd" title="Choose your color"></div>`;
            } else if (type === 'round_outcome') {
                html = `<div class="mb-3"><label class="form-label fw-bold">Outcome Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="wf_name" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label fw-bold text-danger">System Trigger Action <small class="text-muted">(Optional)</small></label><select name="triggers_action" id="wf_trigger" class="form-select border-danger"><option value="">- No Action -</option><option value="discharge_workflow">Initiate Discharge Workflow</option><option value="transfer_workflow">Initiate Transfer Request</option><option value="icu_transfer">Emergency ICU Transfer</option></select></div>`;
            } else {
                html = `<div class="mb-3"><label class="form-label fw-bold">${title} Name <span class="text-danger">*</span></label><input type="text" name="dict_name" id="wf_name" class="form-control" required></div>`;
            }
            
            $('#wf_body_content').html(html); 
            $('#modalWorkflowDict').modal('show');
        };

        // EDIT FUNCTION
        window.editWorkflowRecord = function(type, id) {
            $.post(apiUrl, { action: 'get_record', dict_type: type, id: id }, function(res) {
                if(res && res.status === 'success') {
                    let d = res.data;
                    // Find the title from the active tab
                    let title = $(`button[data-type='${type}']`).data('title') || 'Entry';
                    
                    openWorkflowModal(type, title);
                    
                    setTimeout(()=> { 
                        $('#wf_id').val(id); 
                        $('#wf_name').val(d[res.mapped_col]); 
                        if(type === 'adm_priority') $('#wf_color').val(d.color_code);
                        if(type === 'round_outcome') $('#wf_trigger').val(d.triggers_action);
                    }, 100);
                }
            }, 'json');
        };

        // SUBMIT FORM
        $('#frmWorkflowDict').on('submit', function(e) { 
            e.preventDefault(); 
            let btn = $(this).find('button[type="submit"]');
            btn.prop('disabled', true).text('Saving...');
            
            $.post(apiUrl, $(this).serialize(), function(res) { 
                btn.prop('disabled', false).text('Save Configuration');
                if(res && res.status === 'success') { 
                    $('#modalWorkflowDict').modal('hide'); 
                    let updatedType = $('#wf_dict_type').val();
                    if(window.workflowDataTables[updatedType]) {
                        window.workflowDataTables[updatedType].ajax.reload(null, false); // Real-time silent refresh
                    }
                } else {
                    alert("Error saving data.");
                }
            }, 'json').fail(function() {
                btn.prop('disabled', false).text('Save Configuration');
                alert("Network error.");
            }); 
        });

        // DELETE FUNCTION
        window.deleteWorkflowData = function(type, id) {
            if(confirm('Are you sure you want to delete this configuration?')) {
                $.post(apiUrl, {action: 'delete_record', dict_type: type, id: id}, function(res) {
                    if(res.status === 'success' && window.workflowDataTables[type]) {
                        window.workflowDataTables[type].ajax.reload(null, false); // Real-time silent refresh
                    }
                }, 'json');
            }
        };
        
        // TOGGLE STATUS FUNCTION
        window.toggleWorkflowData = function(type, id, status) {
            $.post(apiUrl, {action: 'toggle_status', dict_type: type, id: id, status: status}, function(res) {
                if(res.status === 'success' && window.workflowDataTables[type]) {
                    window.workflowDataTables[type].ajax.reload(null, false); // Real-time silent refresh
                }
            }, 'json');
        };
    };
} catch (error) {
    console.error("Critical Runtime Error in Workflow JS", error);
}