let dtForms, dtCategories;
window.wardList = []; window.roomList = [];
const builderApi = '/rimax/application/dripend/systemSetup/ipd/processClinicalBuilder.php';

window.initDynamicFormBuilder = function() {
    
    function fetchDropdowns() {
        $.post(builderApi, { action: 'fetch_dropdowns' }, function(res) {
            if(res.status === 'success') {
                window.wardList = res.wards; window.roomList = res.rooms;
                
                let wOpts = '<option value="">-- Available to All Wards Globally --</option>';
                res.wards.forEach(w => wOpts += `<option value="${w.id}">${w.ward_name}</option>`);
                $('#f_ward_id').html(wOpts);

                let roOpts = '<option value="">-- Available to All Staff Roles --</option>';
                res.roles.forEach(r => roOpts += `<option value="${r.id}">${r.name}</option>`);
                $('#f_target_role_id').html(roOpts);

                let frmOpts = '<option value="">-- Choose Custom Form --</option>';
                res.forms_list.forEach(f => frmOpts += `<option value="${f.id}">${f.form_name}</option>`);
                $('#fld_embed_form').html(frmOpts);

                let cOpts = '';
                res.categories.forEach(c => cOpts += `<option value="${c.id}">${c.category_name}</option>`);
                $('#f_form_type').html(cOpts);

                // DYNAMIC DEPARTMENT BINDING - ZERO HARDCODING
                let modOpts = '<option value="Global Application">Global Application (All Modules)</option>';
                let deptMultiOpts = '';
                res.departments.forEach(d => {
                    modOpts += `<option value="${d.department_name}">${d.department_name}</option>`;
                    deptMultiOpts += `<option value="${d.id}">${d.department_name}</option>`;
                });
                $('#f_target_module').html(modOpts);
                $('#fld_service_depts').html(deptMultiOpts);

                let dOpts = '<option value="">-- Choose Target Database --</option>';
                let coreOpts = ''; let custOpts = '';
                res.dictionaries.forEach(d => {
                    if(d.type === 'Core Database') coreOpts += `<option value="${d.id}">${d.name}</option>`;
                    else custOpts += `<option value="${d.id}">${d.name}</option>`;
                });
                if(coreOpts) dOpts += `<optgroup label="System/Core Databases">${coreOpts}</optgroup>`;
                if(custOpts) dOpts += `<optgroup label="Custom Built Dictionaries">${custOpts}</optgroup>`;
                $('#fld_dict_ref').html(dOpts);
            }
        }, 'json');
    }
    fetchDropdowns();

    $('#f_ward_id').on('change', function() {
        let wId = $(this).val();
        if(wId) {
            $('#room_mapping_div').slideDown();
            let rOpts = '<option value="">-- Apply to Entire Ward --</option>';
            window.roomList.filter(r => r.ward_id == wId).forEach(r => rOpts += `<option value="${r.id}">${r.room_number_or_name}</option>`);
            $('#f_room_id').html(rOpts);
        } else {
            $('#room_mapping_div').slideUp();
            $('#f_room_id').html('<option value="">-- Apply to Entire Ward --</option>');
        }
    });

    dtCategories = $('#tblCategories').DataTable({
        ajax: { url: builderApi, type: 'POST', data: { action: 'fetch_categories' } },
        paging: false, info: false, searching: false,
        columns: [
            { data: 'category_name', render: d => `<b class="text-secondary ps-2">${d}</b>` },
            { data: null, className: 'text-end pe-3', orderable: false, render: (d,t,r) => `<button class="btn btn-sm btn-danger py-0 px-2" onclick="deleteNode('category', ${r.id})"><i class="fa fa-times"></i></button>` }
        ]
    });

    dtForms = $('#tblForms').DataTable({
        ajax: { url: builderApi, type: 'POST', data: { action: 'fetch_forms' } },
        pageLength: 8, lengthChange: false,
        columns: [
            { 
                data: null, 
                render: (d,t,r) => `
                    <div class="d-flex flex-column py-1" style="cursor:pointer;" onclick="loadCanvas(${r.id}, '${r.form_name.replace(/'/g, "\\'")}')">
                        <b class="text-primary mb-1" style="font-size:15px;">${r.form_name}</b>
                        <div class="d-flex gap-2 flex-wrap mb-1">
                            <span class="badge bg-dark"><i class="fa-solid fa-server"></i> Module: ${r.target_module || 'Global Application'}</span>
                            <span class="badge bg-secondary"><i class="fa-solid fa-layer-group"></i> Category: ${r.category_name}</span>
                        </div>
                        ${r.role_name ? `<span class="small text-danger fw-bold mt-1"><i class="fa-solid fa-user-doctor"></i> Role Restriction: ${r.role_name}</span>` : ''}
                        ${r.ward_name ? `<span class="small text-info fw-bold mt-1"><i class="fa-solid fa-hospital-user"></i> Mapped: ${r.ward_name} ${r.room_number_or_name ? '> '+r.room_number_or_name : ''}</span>` : '<span class="small text-success fw-bold mt-1"><i class="fa-solid fa-globe"></i> Global Application</span>'}
                    </div>`
            },
            { 
                data: null, 
                orderable: false, 
                className: 'text-end',
                render: (d,t,r) => `
                    <div class="dropdown">
                        <button class="btn btn-sm btn-light border" type="button" data-bs-toggle="dropdown"><i class="fa-solid fa-ellipsis-vertical px-2"></i></button>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                            <li><a class="dropdown-item fw-bold" href="#" onclick="editForm(${r.id}, '${r.form_name.replace(/'/g, "\\'")}', '${r.category_id}', '${r.target_module || 'Global Application'}', '${r.ward_id || ''}', '${r.room_id || ''}', '${r.target_role_id || ''}', ${r.requires_signature})"><i class="fa-solid fa-edit text-primary me-2"></i> Edit Mapping</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger fw-bold" href="#" onclick="deleteNode('form', ${r.id})"><i class="fa-solid fa-trash me-2"></i> Delete Form</a></li>
                        </ul>
                    </div>`
            }
        ]
    });

    window.loadCanvas = function(formId, formName) {
        $('#active_form_id').val(formId);
        $('#canvasTitle').html(`<i class="fa-solid fa-file-signature me-2"></i> Designing: <b class="text-dark">${formName}</b>`);
        $('#canvasActions').show();
        $('#formCanvas').html('<div class="text-center p-5"><div class="spinner-border text-primary"></div></div>');

        $.post(builderApi, { action: 'fetch_form_structure', form_id: formId }, function(res) {
            if(res.status === 'success') {
                let sections = res.data.sections;
                if(sections.length === 0) {
                    $('#formCanvas').html(`
                        <div class="empty-canvas text-center py-5">
                            <i class="fa-solid fa-folder-open fa-4x mb-3 text-muted" style="opacity:0.3;"></i>
                            <h5 class="fw-bold text-dark">This form has no sections.</h5>
                            <button class="btn btn-sm btn-success mt-3 px-4 py-2 fw-bold shadow-sm" onclick="openSectionModal()"><i class="fa-solid fa-plus me-1"></i> Create First Section</button>
                        </div>`);
                    return;
                }

                let html = '';
                sections.forEach(sec => {
                    html += `
                    <div class="section-card border rounded-3 mb-4 bg-white shadow-sm overflow-hidden">
                        <div class="section-header d-flex justify-content-between align-items-center p-3" style="background:#f8fafc; border-bottom:2px solid #e2e8f0;">
                            <span class="fw-bold text-dark text-uppercase small" style="letter-spacing:0.5px;"><i class="fa-solid fa-layer-group text-primary me-2"></i> ${sec.section_title}</span>
                            <div>
                                <button class="btn btn-sm btn-info py-1 px-3 me-1 shadow-sm fw-bold text-white" onclick="openFieldModal(${sec.id})" title="Inject New Field"><i class="fa-solid fa-plus me-1"></i> Add Block</button>
                                <button class="btn btn-sm btn-light py-1 px-2 border me-1" onclick="editSection(${sec.id}, '${sec.section_title.replace(/'/g, "\\'")}', ${sec.display_order})"><i class="fa-solid fa-pen text-primary"></i></button>
                                <button class="btn btn-sm btn-danger py-1 px-2 shadow-sm" onclick="deleteNode('section', ${sec.id})"><i class="fa-solid fa-trash text-white"></i></button>
                            </div>
                        </div>
                        <div class="section-body p-4 bg-white">`;

                    if(sec.fields.length === 0) {
                        html += `<div class="text-center py-4 text-muted small border border-dashed rounded" style="background:#f1f5f9;">No fields added to this section yet. Click "Add Block" to begin.</div>`;
                    } else {
                        sec.fields.forEach(fld => {
                            let mandBadge = fld.is_mandatory == 1 ? '<span class="badge bg-danger rounded-pill ms-2" style="font-size:9px;">Required</span>' : '';
                            
                            let mock = '';
                            if(fld.field_type === 'Dictionary Reference') {
                                mock = `<div class="p-3 bg-success bg-opacity-10 border border-success rounded mt-2"><h6 class="fw-bold text-success mb-1 small text-uppercase"><i class="fa-solid fa-book me-2"></i> Bound to Dictionary: ${fld.dictionary_name || 'Unknown'}</h6></div>`;
                            }
                            else if(fld.field_type === 'Embed Custom Form') {
                                mock = `<div class="p-3 bg-primary bg-opacity-10 border border-primary rounded mt-2 border-dashed"><h6 class="fw-bold text-primary mb-1 small text-uppercase"><i class="fa-solid fa-file-import me-2"></i> Embedded Sub-Form: ${fld.embedded_form_name || 'Unknown Form'}</h6></div>`;
                            }
                            else if(fld.field_type.startsWith('Native:')) {
                                let mapType = fld.field_type.split(':')[1].trim();
                                let icon = 'fa-laptop-medical'; let color = 'text-danger'; let bgClass = 'bg-danger border-danger';
                                
                                if(mapType === 'Pharmacy') { icon = 'fa-pills'; color = 'text-warning'; bgClass = 'bg-warning border-warning'; }
                                if(mapType === 'Service Order') { icon = 'fa-microscope'; color = 'text-success'; bgClass = 'bg-success border-success'; mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2 shadow-sm"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Injected Native Engine: Diagnostic / Service Order</h6><span class="small text-muted">Dynamically Bound to Department IDs: ${fld.options_csv}</span></div>`; }
                                if(mapType === 'Ward Service Order') { icon = 'fa-vial'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; }
                                if(mapType === 'Clinical Diagnosis') { 
                                    icon = 'fa-book-medical'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; 
                                    mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2 shadow-sm"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Injected Native Engine: Clinical Diagnosis (ICD-10 & G-DRG)</h6><span class="small text-muted">Dynamically fetches ICD-10 and G-DRG codes for automated clinical coding and billing maps.</span></div>`;
                                }
                                if(mapType === 'Clinical Outcome') { 
                                    icon = 'fa-bed-pulse'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; 
                                    mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2 shadow-sm"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Injected Native Engine: Clinical Outcome / Patient Disposition</h6><span class="small text-muted">Dynamically fetches outcomes from the DB and triggers system workflows (Discharge, Transfer, Remain).</span></div>`; 
                                }
                                if(mapType === 'Blood Transfusion Request') { icon = 'fa-truck-droplet'; color = 'text-danger'; bgClass = 'bg-danger border-danger'; }
                                if(mapType === 'Ambulance Request') { icon = 'fa-truck-medical'; color = 'text-danger'; bgClass = 'bg-danger border-danger'; }
                                if(mapType === 'Medication Chart') { icon = 'fa-list-check'; color = 'text-dark'; bgClass = 'bg-secondary border-secondary'; }
                                if(mapType === 'Fluid Chart') { icon = 'fa-droplet'; color = 'text-info'; bgClass = 'bg-info border-info'; }
                                if(mapType === 'Oxygen Chart') { icon = 'fa-lungs'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; }
                                if(mapType === 'Blood Transfusion Charting') { icon = 'fa-truck-droplet'; color = 'text-danger'; bgClass = 'bg-danger border-danger'; }

                                if(mapType !== 'Service Order' && mapType !== 'Clinical Outcome' && mapType !== 'Clinical Diagnosis') {
                                    mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2 shadow-sm"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Injected Native Engine: ${mapType}</h6><span class="small text-muted">This block will render complex interactive components dynamically.</span></div>`;
                                }
                            }
                            else if(fld.field_type.startsWith('Report:')) {
                                let mapType = fld.field_type.split(':')[1].trim();
                                let icon = 'fa-chart-line'; let color = 'text-info'; let bgClass = 'bg-info border-info';
                                mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2 shadow-sm"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Injected Report Engine: ${mapType}</h6><span class="small text-muted">This block will automatically generate and render real-time charts and data tables.</span></div>`;
                            }
                            else if(fld.field_type.startsWith('ConfigMap:')) {
                                let mapType = fld.field_type.split(':')[1].trim();
                                let icon = 'fa-link'; let color = 'text-dark'; let bgClass = 'bg-secondary border-secondary';
                                
                                if(mapType === 'Vitals') { icon = 'fa-heart-pulse'; color = 'text-danger'; bgClass = 'bg-danger border-danger'; }
                                if(mapType === 'Diets') { icon = 'fa-utensils'; color = 'text-success'; bgClass = 'bg-success border-success'; }
                                if(mapType === 'Fluids') { icon = 'fa-droplet'; color = 'text-info'; bgClass = 'bg-info border-info'; }
                                if(mapType.includes('Oxygen')) { icon = 'fa-lungs'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; }
                                if(mapType === 'Blood Products') { icon = 'fa-truck-droplet'; color = 'text-danger'; bgClass = 'bg-danger border-danger'; }
                                if(mapType === 'Ward Services') { icon = 'fa-vial'; color = 'text-primary'; bgClass = 'bg-primary border-primary'; }
                                if(mapType === 'Isolation & PPE') { icon = 'fa-shield-virus'; color = 'text-warning'; bgClass = 'bg-warning border-warning'; }
                                if(mapType === 'Ward Equipment') { icon = 'fa-wheelchair'; color = 'text-secondary'; bgClass = 'bg-secondary border-secondary'; }

                                mock = `<div class="p-3 ${bgClass} bg-opacity-10 border rounded mt-2"><h6 class="fw-bold ${color} mb-1 small text-uppercase"><i class="fa-solid ${icon} me-2"></i> Linked to Clinical Config: ${mapType}</h6></div>`;
                            }

                            html += `
                            <div class="field-row p-3 rounded mb-3 border bg-light shadow-sm">
                                <div class="w-100">
                                    <div class="d-flex justify-content-between align-items-center mb-1">
                                        <div>
                                            <i class="fa-solid fa-grip-vertical text-muted me-2" style="cursor:move;"></i> 
                                            <span class="fw-bold text-dark fs-6">${fld.field_label}</span> ${mandBadge}
                                        </div>
                                        <div>
                                            <button class="btn btn-sm btn-white py-1 px-2 border shadow-sm me-1" onclick="editField(${fld.id}, ${sec.id}, '${fld.field_label.replace(/'/g, "\\'")}', '${fld.field_type}', '${fld.dictionary_reference || ''}', '${fld.embedded_form_id || ''}', '${fld.options_csv ? fld.options_csv.replace(/'/g, "\\'") : ''}', ${fld.is_mandatory}, ${fld.display_order})"><i class="fa-solid fa-pen text-primary"></i></button>
                                            <button class="btn btn-sm btn-white py-1 px-2 border shadow-sm" onclick="deleteNode('field', ${fld.id})"><i class="fa-solid fa-trash text-danger"></i></button>
                                        </div>
                                    </div>
                                    <div class="small text-muted ms-4 mb-2"><span class="badge bg-secondary">${fld.field_type}</span> ${fld.options_csv && !fld.field_type.includes('Native: Service Order') ? ` [ ${fld.options_csv} ]` : ''}</div>
                                    <div class="ms-4">${mock}</div>
                                </div>
                            </div>`;
                        });
                    }
                    html += `</div></div>`;
                });
                $('#formCanvas').html(html);
            }
        }, 'json');
    };

    window.openCategoryModal = () => { $('#frmCategory')[0].reset(); $('#cat_id').val(''); $('#modalCategory').modal('show'); };
    window.openFormModal = () => { $('#frmMasterForm')[0].reset(); $('#form_id').val(''); $('#room_mapping_div').hide(); $('#modalForm').modal('show'); };
    window.openSectionModal = () => { let fid = $('#active_form_id').val(); if(!fid){alert("Select a form."); return;} $('#frmSection')[0].reset(); $('#sec_form_id').val(fid); $('#modalSection').modal('show'); };
    
    window.openFieldModal = (secId) => { 
        $('#frmField')[0].reset(); $('#fld_sec_id').val(secId); 
        $('#div_field_options, #div_dict_reference, #div_embed_form, #div_service_depts').hide();
        $('#fld_opts, #fld_dict_ref, #fld_embed_form').prop('required', false);
        $('#fld_service_depts').prop('required', false).val([]).trigger('change');
        $('#div_mand_switch').show();
        $('#modalField').modal('show'); 
    };

    window.editForm = (id, name, cat, module, ward, room, role, sig) => {
        $('#form_id').val(id); $('#f_form_name').val(name); $('#f_form_type').val(cat);
        $('#f_target_module').val(module);
        $('#f_target_role_id').val(role);
        $('#f_ward_id').val(ward).trigger('change');
        setTimeout(() => $('#f_room_id').val(room), 200);
        $('#f_req_sig').prop('checked', sig == 1);
        $('#modalForm').modal('show');
    };
    
    window.editSection = (id, title, order) => { $('#section_id').val(id); $('#sec_title').val(title); $('#sec_order').val(order); $('#sec_form_id').val($('#active_form_id').val()); $('#modalSection').modal('show'); };

    window.editField = (id, secId, label, type, dictRef, embFrm, opts, isMand, order) => {
        $('#field_id').val(id); $('#fld_sec_id').val(secId); $('#fld_label').val(label); $('#fld_type').val(type).trigger('change');
        if(type === 'Embed Custom Form') { $('#fld_embed_form').val(embFrm); } 
        else { $('#fld_dict_ref').val(dictRef); }
        
        if(type === 'Native: Service Order') {
            let depts = opts ? opts.split(',') : [];
            $('#fld_service_depts').val(depts).trigger('change');
            $('#fld_opts').val('');
        } else {
            $('#fld_opts').val(opts);
            $('#fld_service_depts').val([]).trigger('change');
        }

        $('#fld_order').val(order);
        $('#fld_mand').prop('checked', isMand == 1);
        $('#modalField').modal('show');
    };

    $('#fld_type').on('change', function() {
        let v = $(this).val();
        
        if(['Select Dropdown', 'Radio (Single)', 'Checkbox (Multiple)'].includes(v)) {
            $('#div_field_options').slideDown(); $('#fld_opts').prop('required', true);
        } else {
            $('#div_field_options').slideUp(); $('#fld_opts').prop('required', false).val('');
        }

        if(v === 'Dictionary Reference') {
            $('#div_dict_reference').slideDown(); $('#fld_dict_ref').prop('required', true);
        } else {
            $('#div_dict_reference').slideUp(); $('#fld_dict_ref').prop('required', false).val('');
        }

        if(v === 'Embed Custom Form') {
            $('#div_embed_form').slideDown(); $('#fld_embed_form').prop('required', true);
        } else {
            $('#div_embed_form').slideUp(); $('#fld_embed_form').prop('required', false).val('');
        }

        if(v === 'Native: Service Order') {
            $('#div_service_depts').slideDown(); $('#fld_service_depts').prop('required', true);
        } else {
            $('#div_service_depts').slideUp(); $('#fld_service_depts').prop('required', false).val([]).trigger('change');
        }

        if(v.includes('ConfigMap:') || v.startsWith('Native:') || v.startsWith('Report:') || v === 'Embed Custom Form') {
            $('#div_mand_switch').hide(); $('#fld_mand').prop('checked', false);
        } else {
            $('#div_mand_switch').show();
        }
    });

    $('#frmCategory').on('submit', function(e) { 
        e.preventDefault(); 
        $.post(builderApi, $(this).serialize(), res => { dtCategories.ajax.reload(null, false); fetchDropdowns(); $('#f_cat_name').val(''); }); 
    });
    
    $('#frmMasterForm, #frmSection, #frmField').on('submit', function(e) {
        e.preventDefault();
        let frm = $(this);
        let btn = frm.find('button[type="submit"]');
        let orig = btn.html();
        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-1"></i> Saving...');

        $.post(builderApi, frm.serialize(), function(res) {
            btn.prop('disabled', false).html(orig);
            if(res.status === 'success') {
                $('.modal').modal('hide');
                if(frm.attr('id') === 'frmMasterForm') dtForms.ajax.reload(null, false);
                if($('#active_form_id').val()) loadCanvas($('#active_form_id').val(), $('#canvasTitle b').text());
            } else { alert('Error: ' + (res.message || 'Database error occurred.')); }
        }, 'json').fail(function() {
            btn.prop('disabled', false).html(orig);
            alert('Server error occurred during save.');
        });
    });

    window.deleteNode = (type, id) => {
        if(confirm('Delete this item permanently?')) {
            $.post(builderApi, { action: 'delete_node', node_type: type, id: id }, res => {
                if(type === 'form') { dtForms.ajax.reload(null,false); $('#formCanvas').html('<div class="empty-canvas text-center py-5"><h5 class="text-danger fw-bold">Form Deleted</h5></div>'); $('#active_form_id').val(''); $('#canvasActions').hide(); $('#canvasTitle').html('Form Canvas'); fetchDropdowns(); }
                else if(type === 'category') { dtCategories.ajax.reload(null,false); fetchDropdowns(); }
                else { if($('#active_form_id').val()) loadCanvas($('#active_form_id').val(), $('#canvasTitle b').text()); }
            });
        }
    };
};