window.initTheatreManagerForms = function() {
    let dtConfig;
    let currentActiveTab = 'stages';
    const apiForms = '/rimax/application/dripend/systemSetup/ipd/processTheatreManagerForms.php';
    let pendingDeleteId = null;

    // Fetch Dependencies
    function loadDependencies() {
        $.post(apiForms, { action: 'fetch_dependencies' }, function(res) {
            if(res.status === 'success') {
                let stOpts = '<option value="">-- Select Stage --</option>';
                if(res.stages) res.stages.forEach(s => stOpts += `<option value="${s.id}">${s.name}</option>`);
                $('#cfg_stage_id').html(stOpts);

                let scOpts = '<option value="">-- Select Section --</option>';
                if(res.sections) res.sections.forEach(s => scOpts += `<option value="${s.id}">${s.name}</option>`);
                $('#cfg_section_id, #cfg_embedded_section').html(scOpts);

                let dOpts = '';
                if(res.departments) res.departments.forEach(d => dOpts += `<option value="${d.id}">${d.name}</option>`);
                $('#cfg_target_depts').html(dOpts);

                let pOpts = '';
                if(res.procedures) res.procedures.forEach(p => pOpts += `<option value="${p.id}">${p.name}</option>`);
                $('#cfg_target_procs').html(pOpts);

                let mapOpts = '<option value="">-- Select Data Dictionary --</option>';
                if(res.dictionaries) res.dictionaries.forEach(d => mapOpts += `<option value="${d.id}">${d.name}</option>`);
                $('#cfg_dictionary').html(mapOpts);

                $('.select2-modal').select2({ dropdownParent: $('#configModal'), width: '100%' });
            }
        }, 'json');
    }

    loadDependencies();

    function showAppResponse(title, msg, type = 'success') {
        if(type === 'success') {
            $('#appResIcon').attr('class', 'fa-solid fa-circle-check text-success fa-4x mb-3');
            $('#appResBtn').attr('class', 'btn btn-success fw-bold px-4 mt-2');
        } else {
            $('#appResIcon').attr('class', 'fa-solid fa-circle-xmark text-danger fa-4x mb-3');
            $('#appResBtn').attr('class', 'btn btn-dark fw-bold px-4 mt-2');
        }
        $('#appResTitle').text(title);
        $('#appResMsg').text(msg);
        $('#appResponseModal').modal('show');
    }

    // Advanced Dynamic UI Toggles based on field type
    $('#cfg_field_type').on('change', function() {
        let t = $(this).val();
        
        // Hide all specifics first
        $('#grp_options, #grp_dictionary, #grp_embedded_section, #grp_richtext_options').slideUp();
        $('#cfg_options, #cfg_dictionary, #cfg_embedded_section, #cfg_richtext_options').prop('required', false);

        // 1. Array Options
        if(['select', 'radio', 'checkbox'].includes(t)) {
            $('#grp_options').slideDown();
            $('#cfg_options').prop('required', true);
        } 
        // 2. Dictionary Maps
        else if(t === 'config_map') {
            $('#grp_dictionary').slideDown();
            $('#cfg_dictionary').prop('required', true);
        } 
        // 3. Embedded Forms
        else if(t === 'embedded_form') {
            $('#grp_embedded_section').slideDown();
            $('#cfg_embedded_section').prop('required', true);
        }
        // 4. Rich Text Format Settings
        else if(t === 'richtext') {
            $('#grp_richtext_options').slideDown();
            $('#cfg_richtext_options').prop('required', true);
        }
    });

    window.loadConfigTab = function(tabName) {
        currentActiveTab = tabName;
        $('.config-tab-btn').removeClass('active');
        $(`button[onclick="loadConfigTab('${tabName}')"]`).addClass('active');

        let titles = {
            'stages': 'Clinical Stages Configuration',
            'sections': 'UI Section Groups',
            'fields': 'Dynamic Form Fields Builder'
        };
        $('#current_tab_title').text(titles[tabName]);
        
        initDataTable();
    };

    function initDataTable() {
        if ($.fn.DataTable.isDataTable('#tblConfig')) {
            $('#tblConfig').DataTable().destroy();
            $('#tblConfig').empty();
        }

        let columns = [];
        if (['stages', 'sections'].includes(currentActiveTab)) {
            columns = [
                { data: 'id', title: 'ID', className: 'fw-bold text-muted', width: '10%' },
                { data: 'name', title: 'Name', className: 'fw-bold text-dark' },
                { data: 'status_badge', title: 'Status', width: '15%' }
            ];
        } else if (currentActiveTab === 'fields') {
            columns = [
                { data: 'field_label', title: 'Field Question/Label', className: 'fw-bold text-danger' },
                { 
                    data: 'field_type', title: 'Input Engine Type', 
                    render: function(d) {
                        let icon = 'fa-code';
                        if(d.includes('native')) icon = 'fa-bolt';
                        if(d === 'richtext') icon = 'fa-font';
                        if(d === 'embedded_form') icon = 'fa-plug';
                        return `<span class="type-badge"><i class="fa ${icon} me-1"></i> ${d.toUpperCase()}</span>`;
                    }
                },
                { data: null, title: 'Scope & Targets', render: r => `<span class="small text-muted"><i class="fa fa-hospital"></i> Depts:</span> ${r.dept_targets}<br><span class="small text-muted"><i class="fa fa-scalpel"></i> Procs:</span> ${r.proc_targets}` },
                { data: 'stage_name', title: 'Clinical Stage', className: 'fw-bold text-dark' },
                { data: 'section_name', title: 'UI Section', className: 'text-muted' },
                { data: 'req_badge', title: 'Required' },
                { data: 'display_order', title: 'Order' },
                { data: 'status_badge', title: 'Status', width: '10%' }
            ];
        }

        columns.push({
            data: null, title: 'Action', className: 'text-end', width: '15%', orderable: false,
            render: function(data, type, row) {
                let toggleClass = row.is_active == 1 ? 'text-warning' : 'text-success';
                let toggleIcon = row.is_active == 1 ? 'fa-ban' : 'fa-check';
                let toggleAction = row.is_active == 1 ? 0 : 1;
                let payload = btoa(unescape(encodeURIComponent(JSON.stringify(row))));

                return `
                <button class="btn btn-sm btn-light border text-primary shadow-sm" onclick="editConfig('${payload}')" title="Edit"><i class="fa-solid fa-pen"></i></button>
                <button class="btn btn-sm btn-light border ${toggleClass} shadow-sm ms-1" onclick="toggleStatus(${row.id}, ${toggleAction})" title="Toggle Status"><i class="fa-solid ${toggleIcon}"></i></button>
                <button class="btn btn-sm btn-light border text-danger shadow-sm ms-1" onclick="deleteConfig(${row.id})" title="Delete"><i class="fa-solid fa-trash"></i></button>`;
            }
        });

        dtConfig = $('#tblConfig').DataTable({
            ajax: {
                url: apiForms,
                type: 'POST',
                data: function(d) { d.action = 'fetch_config'; d.config_type = currentActiveTab; },
                dataSrc: function (json) {
                    if (json.status === 'error') { showAppResponse("System Error", json.message, 'error'); return []; }
                    return json.data || [];
                }
            },
            pageLength: 15,
            autoWidth: false,
            columns: columns
        });
    }

    window.openConfigModal = function() {
        $('#frmConfig')[0].reset();
        $('#cfg_id').val('');
        $('#cfg_type').val(currentActiveTab);
        $('.select2-modal').val('').trigger('change');
        $('#cfg_field_type').trigger('change');
        setupModalUI();
        $('#configModal').modal('show');
    };

    window.editConfig = function(payloadBase64) {
        let row = JSON.parse(decodeURIComponent(escape(atob(payloadBase64))));
        $('#frmConfig')[0].reset();
        $('#cfg_id').val(row.id);
        $('#cfg_type').val(currentActiveTab);
        
        setupModalUI();

        if (['stages', 'sections'].includes(currentActiveTab)) {
            $('#cfg_name').val(row.name);
        } else if (currentActiveTab === 'fields') {
            
            // Map Multiple Selects safely
            if(row.target_departments) {
                $('#cfg_target_depts').val(row.target_departments.split(',')).trigger('change');
            } else {
                $('#cfg_target_depts').val('').trigger('change');
            }

            if(row.target_procedures) {
                $('#cfg_target_procs').val(row.target_procedures.split(',')).trigger('change');
            } else {
                $('#cfg_target_procs').val('').trigger('change');
            }

            $('#cfg_stage_id').val(row.stage_id).trigger('change');
            $('#cfg_section_id').val(row.section_id).trigger('change');
            $('#cfg_field_label').val(row.field_label);
            
            // This triggers the view logic automatically
            $('#cfg_field_type').val(row.field_type).trigger('change');
            
            $('#cfg_dictionary').val(row.dictionary_reference).trigger('change');
            $('#cfg_embedded_section').val(row.embedded_section_id).trigger('change');
            
            if(row.field_type === 'richtext') $('#cfg_richtext_options').val(row.field_options);
            else $('#cfg_options').val(row.field_options);
            
            $('#cfg_order').val(row.display_order);
            $('#cfg_required').prop('checked', row.is_required == 1);
        }
        
        $('#configModal').modal('show');
    };

    function setupModalUI() {
        // Hide standard inputs
        $('#grp_name, .builder-fld, #grp_options, #grp_dictionary, #grp_embedded_section, #grp_richtext_options').hide();
        $('#cfg_name, #cfg_stage_id, #cfg_section_id, #cfg_field_label, #cfg_field_type').prop('required', false);

        if (['stages', 'sections'].includes(currentActiveTab)) {
            $('#grp_name').show();
            $('#lbl_name').html(currentActiveTab === 'stages' ? `Clinical Stage Name <span class="text-danger">*</span>` : `UI Section Name <span class="text-danger">*</span>`);
            $('#cfg_name').prop('required', true);
        } else if (currentActiveTab === 'fields') {
            $('.builder-fld').show();
            $('#cfg_stage_id, #cfg_section_id, #cfg_field_label, #cfg_field_type').prop('required', true);
            $('#cfg_field_type').trigger('change'); // Ensure specific inputs show based on current selection
        }
    }

    $('#frmConfig').off('submit').on('submit', function(e) {
        e.preventDefault();
        let btn = $('#btnSaveConfig'); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Saving...');

        $.post(apiForms, $(this).serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if(res.status === 'success') {
                $('#configModal').modal('hide');
                showAppResponse("Saved", res.message, 'success');
                loadDependencies(); // Refresh dependencies in case a new stage/section was added
                if(dtConfig) dtConfig.ajax.reload(null, false);
            } else {
                showAppResponse("Save Error", res.message, 'error');
            }
        }, 'json').fail(function() {
            btn.prop('disabled', false).html(orig);
            showAppResponse("Server Error", "A fatal server error occurred while saving configuration.", 'error');
        });
    });

    window.toggleStatus = function(id, newStatus) {
        $.post(apiForms, { action: 'toggle_status', config_type: currentActiveTab, id: id, new_status: newStatus }, function(res) {
            if(res.status === 'success') dtConfig.ajax.reload(null, false);
            else showAppResponse("Toggle Error", res.message, 'error');
        }, 'json');
    };

    window.deleteConfig = function(id) {
        pendingDeleteId = id;
        $('#deleteModal').modal('show');
    };

    $('#btnConfirmDelete').off('click').on('click', function() {
        if(!pendingDeleteId) return;
        let btn = $(this); let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        $.post(apiForms, { action: 'delete_config', config_type: currentActiveTab, id: pendingDeleteId }, function(res) {
            $('#deleteModal').modal('hide');
            btn.prop('disabled', false).html(orig);

            if(res.status === 'success') {
                showAppResponse("Deleted", res.message, 'success');
                loadDependencies();
                if(dtConfig) dtConfig.ajax.reload(null, false);
            } else {
                showAppResponse("Cannot Delete", res.message, 'error');
            }
            pendingDeleteId = null;
        }, 'json');
    });

    // Initialize with default tab
    loadConfigTab('stages');
};