3d Model not deattaching/removing when radio button unselect

The problem is that I am rendering a 3d boat model which has different sections in which there are options with multiple select and single select which are dealt with radio and checkboxes. Now issue is when I select a radio option the model accessory is attached to boat model but as I unselect that option the price of that option is deducted but the model is not removed and frequent clicks on the radio option the calculation also starts to become wrong.

The following is the way I tried. My Laravel blade code where the radio and the checkbox structure is set is:

                                            <input class="form-check-input cat-item-check"
                                            name="{{ $value->multi_select == 2 ? 'option[' . $value->type . ']' : 'option[' . $value1->type . ']' }}"
                                            type="{{ $value->multi_select == 1 ? 'checkbox' : 'radio' }}"
                                            value="{{ $option->id }}" data-typename="{{ $value1->ltitle }}"
                                            data-type="{{ $value->multi_select == 2 ? $value->type : $value1->type }}"
                                            data-parent="{{ $option->parent_id }}"
                                            data-waschecked="{{ $option->is_standard_option == 1 ? 'true' : 'false' }}"
                                            data-model="{{ asset('storage/' . $option->file) }}"
                                            data-price="{{ $option->price }}"
                                            id="collapse-{{ $option->id }}"
                                            {{ $option->is_standard_option == 1 ? 'checked' : '' }}>

The script which I am using is:

 document.addEventListener('DOMContentLoaded', function() {
        const modelPath = '{{ asset('storage/' . $modelPath) }}';
        const container = document.getElementById('3d-model');

        const scene = new THREE.Scene();
        const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1,
            1000);
        camera.position.set(0, 0, 6);
        camera.lookAt(scene.position);

        const renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.gammaOutput = true;
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 2;

        renderer.setSize(container.clientWidth, container.clientHeight);
        renderer.setClearColor(0xffffff);
        container.appendChild(renderer.domElement);

        const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
        directionalLight.position.set(5, 5, 5).normalize();
        scene.add(directionalLight);

        const directionalLight2 = new THREE.DirectionalLight(0xffffff, 2);
        directionalLight2.position.set(-5, -5, -5).normalize();
        scene.add(directionalLight2);

        const ambientLight = new THREE.AmbientLight(0xffffff, 1.5);
        scene.add(ambientLight);

        const dracoLoader = new THREE.DRACOLoader();
        dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.4.1/");

        const loader = new THREE.GLTFLoader();
        loader.setDRACOLoader(dracoLoader);

        let baseModel, additionalModels = [];

        function loadModel(path, targetSize = 8, callback) {
            loader.load(path, function(gltf) {
                const model = gltf.scene;
                model.userData.path = path;
                const bbox = new THREE.Box3().setFromObject(model);
                const size = new THREE.Vector3();
                bbox.getSize(size);
                const maxDimension = Math.max(size.x, size.y, size.z);
                const scaleFactor = targetSize / maxDimension;
                model.scale.set(scaleFactor, scaleFactor, scaleFactor);
                bbox.setFromObject(model);
                const center = new THREE.Vector3();
                bbox.getCenter(center);

                model.position.x -= center.x;
                model.position.y -= center.y;
                model.position.z -= center.z;

                callback(model);
            }, undefined, function(error) {
                console.error('Error loading model:', path, error);
            });
        }

        loadModel(modelPath, 8, function(model) {
            baseModel = model;
            scene.add(baseModel);


            function handleCheckboxClick(input) {
                const modelPath = input.dataset.model;
                const isChecked = input.checked;
                toggleAdditionalModel(modelPath, isChecked);
            }

            let previousSelectedRadio = {};

function handleRadioClick(input) {
    const modelPath = input.dataset.model;
    const radioGroupName = input.name;
    document.querySelectorAll(`input[name="${radioGroupName}"]`).forEach(radio => {
        const otherModelPath = radio.dataset.model;
        const modelIndex = additionalModels.findIndex(m => m.userData.path === otherModelPath);
        if (modelIndex !== -1) {
            scene.remove(additionalModels[modelIndex]);
            additionalModels.splice(modelIndex, 1);
        }
    });

    if (input.checked) {
        toggleAdditionalModel(modelPath, true);
        previousSelectedRadio[radioGroupName] = input;
    }
}

            document.querySelectorAll('.cat-item-check').forEach(input => {
                if (input.type === 'checkbox') {
                    handleCheckboxClick(input);
                } else if (input.type === 'radio') {
                    handleRadioClick(input);
                }
                input.addEventListener('click', function() {
                    if (this.type === 'checkbox') {
                        handleCheckboxClick(this);
                    } else if (this.type === 'radio') {
                        handleRadioClick(this);
                    }
                });
            });
        });

        function toggleAdditionalModel(path, add) {
            if (add) {
                loadModel(path, 4, function(model) {
                    additionalModels.push(model);
                    if (baseModel) {
                        model.position.copy(baseModel.position);
                        model.scale.copy(baseModel.scale);
                    }
                    scene.add(model);
                });
            } else {
                const modelIndex = additionalModels.findIndex(m => m.userData.path === path);
                if (modelIndex !== -1) {
                    scene.remove(additionalModels[modelIndex]);
                    additionalModels.splice(modelIndex, 1);
                }
            }
        }

        const controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.enableDamping = false;
        controls.minDistance = 3;
        controls.maxDistance = 13;

        function animate() {
            requestAnimationFrame(animate);
            renderer.render(scene, camera);
            controls.update();
        }

        animate();

        // Color picker setup
        const colorPickers = document.querySelectorAll('[data-color-picker="true"]');

        colorPickers.forEach(pickerElement => {
            const pickr = Pickr.create({
                el: pickerElement,
                theme: 'classic',
                swatches: [
                    'rgba(244, 67, 54, 1)',
                    'rgba(233, 30, 99, 0.95)',
                    'rgba(156, 39, 176, 0.9)',
                    'rgba(103, 58, 183, 0.85)',
                    'rgba(63, 81, 181, 0.8)',
                    'rgba(33, 150, 243, 0.75)',
                    'rgba(3, 169, 244, 0.7)',
                    'rgba(0, 188, 212, 0.7)',
                    'rgba(0, 150, 136, 0.75)',
                    'rgba(76, 175, 80, 0.8)',
                    'rgba(139, 195, 74, 0.85)',
                    'rgba(205, 220, 57, 0.9)',
                    'rgba(255, 235, 59, 0.95)',
                    'rgba(255, 193, 7, 1)'
                ],
                components: {
                    preview: true,
                    opacity: true,
                    hue: true,
                    interaction: {
                        hex: true,
                        rgba: true,
                        input: true,
                        clear: true,
                        save: true
                    }
                }
            });

            pickr.on('save', (color, instance) => {
                const colorOptionId = pickerElement.getAttribute('data-color-option-id');
                const colorType = pickerElement.getAttribute('data-color-option-type');
                const colorPrice = parseFloat(pickerElement.getAttribute('data-color-price'));

                if (colorOptionId && colorType) {
                    const colorSelected = color.toHEXA().toString();
                    const inputName = `option[${colorType}]`;
                    const inputElement = document.querySelector(`input[name="${inputName}"]`);

                    if (inputElement) {
                        inputElement.value = `${colorOptionId}-${colorSelected}`;
                        updateTotalPrice(colorPrice); // Update total price function

                        const firstWord = colorType.split('-')[
                        0]; // Extract "top" from "top-color"

                        let colorApplied = false;

                        additionalModels.forEach(model => {
                            const modelLabel = model.userData.path.toLowerCase();
                            if (modelLabel.includes(firstWord)) {
                                console.log(`Applying color ${colorSelected} to model at path: ${model.userData.path}`);
                                // Apply color to model's material or texture
                                // Example assuming model has a material with a 'color' property
                                model.traverse(child => {
                                    if (child.isMesh) {
                                        child.material.color.set(colorSelected);
                                    }
                                });
                                colorApplied = true;
                            }
                        });

                        if (!colorApplied && baseModel) {
                            let basePartFound = false;
                            baseModel.traverse(child => {
                                if (child.name) {
                                    console.log(
                                        `Checking base model part: '${child.name}' for match with '${firstWord}'`
                                        );


                                    const childName = child.name.trim().toLowerCase();
                                    const checkName = firstWord.trim().toLowerCase();

                                    if (childName === checkName) {
                                        console.log(
                                            `Applying color ${colorSelected} to base model part: ${child.name}`
                                            );
                                        child.traverse(child => {
                                            if (child.isMesh) {
                                                if (child.material) {
                                                    child.material.color.set(
                                                        colorSelected);
                                                }
                                            }
                                        });

                                        basePartFound = true;
                                    }
                                }
                            });



                            if (!basePartFound) {
                                console.log(
                                    `No matching part found in additional models or base model for: ${firstWord}`
                                    );
                            }
                        }

                    } else {
                        console.error(`Input element with name ${inputName} not found.`);
                    }
                } else {
                    console.error('Color option ID or type not found.');
                }
            });

        });

        function updateTotalPrice(colorPrice) {
            let totalPrice = parseFloat($('input[name="total_price"]').val());
            totalPrice += parseFloat(colorPrice);

            const currency = "<?php echo get_application_currency()['symbol']; ?>";
            const vatPrice = (totalPrice * 5) / 100;
            const vatTotal = totalPrice + vatPrice;

            $('.sub-total').text(totalPrice.toLocaleString('en-US') + currency);
            $('.vat-price').text(vatPrice.toLocaleString('en-US') + currency);
            $('.vat-total').text(vatTotal.toLocaleString('en-US') + currency);
            $('input[name="total_price"]').val(totalPrice);
        }
    });

So how to fix the issue?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật