<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
        const ruteLainnyaDiv = document.getElementById("ruteLainnya");
        const lantaiLainnyaDiv = document.getElementById("lantaiLainnya");



        // Create new div for additional items
        function createNewDiv(container, inputName) {
            const newDiv = document.createElement("div");
            newDiv.className = "flex items-baseline flex-wrap lg:flex-nowrap gap-2.5 mb-5";

            const index = container.querySelectorAll(".flex.items-baseline")
                .length; // Get index for dynamic IDs

            newDiv.innerHTML = `
             <div class="flex items-baseline w-full flex-wrap lg:flex-nowrap gap-2.5 mb-5" id="photoContainer">
        <label class="flex flex-col form-label max-w-56">
            Masukkan nama ${inputName}
        </label>
        <div class="flex flex-wrap items-baseline w-full gap-4">
            <img id="foto_${inputName}-preview-${index}"
                         src="{{ isset($formFoto['gerbang']) ? asset('storage/' . $formFoto['gerbang']) : '' }}"
                         alt="Foto Gerbong" class="mt-2 max-w-full h-auto"
                         style="{{ isset($formFoto['gerbang']) ? '' : 'display: none;' }} width: 30rem;">

            <div class="flex flex-col lg:flex-row gap-2 w-full">
                <div class="flex flex-wrap items-baseline px-2">
                    <input class="input" type="text" name="name_${inputName}[]">
                </div>
                <div class="input-group w-full flex flex-col gap-2">
                    <div class="input-group w-full flex gap-2">
                        <input id="inputLainnya-${index}" type="file" name="foto_${inputName}[]"
                               class="file-input file-input-bordered w-full" accept="image/*"
                               capture="camera" onchange="previewImage(this, 'foto_${inputName}-preview-${index}')">
                        <button type="button" id="btnCamera-${index}" class="btn btn-light"
                                data-modal-toggle="#cameraModal">
                            <i class="ki-outline ki-abstract-33"></i> Camera
                        </button>
                    </div>
                </div>
                <button type="button" class="btn btn-danger btn-sm delete-btn">
                    <i class="ki-filled ki-trash"></i>
                </button>
            </div>
        </div>
        </div>
    `;

            container.appendChild(newDiv);
            addDeleteListeners(container); // Re-add listeners for delete buttons in the new div
        }

        // Event listener for adding more items



        function setupInputHandlers(containerId, buttonId, labelText, inputDataClass, buttonDeleteClass) {
            const addButton = document.getElementById(buttonId);
            const inputContainer = document.getElementById(containerId);

            if (!addButton || !inputContainer) {
                console.error(`Element with ID ${containerId} or ${buttonId} not found.`);
                return;
            }

            function updateLabels() {
                const labels = inputContainer.querySelectorAll('.form-label span');
                labels.forEach((label, index) => {
                    label.textContent = `${labelText} ${index + 1}`;
                });
            }

            function handleDeleteButtons() {
                const deleteBtns = inputContainer.querySelectorAll(`.${buttonDeleteClass}`);
                deleteBtns.forEach(btn => {
                    btn.style.display = inputContainer.children.length > 1 ? 'block' : 'none';
                });
            }

            function createNewInput() {
                const newDiv = inputContainer.children[0].cloneNode(true);

                // Reset semua input dalam elemen baru
                const inputFile = newDiv.querySelector(`.${inputDataClass}`);
                const previewContainer = newDiv.querySelector('.preview-container');
                const imgPreview = previewContainer.querySelector('img');
                if (inputFile) {
                    // Generate unique ID untuk input dan preview
                    const uniqueId = `${containerId}-${Date.now()}`;
                    inputFile.id = `input-${uniqueId}`;
                    imgPreview.id = `preview-${uniqueId}`;

                    // Reset input file
                    inputFile.value = '';

                    // Tambahkan event listener untuk preview
                    inputFile.addEventListener('change', function() {
                        const file = this.files[0];
                        if (file) {
                            const reader = new FileReader();
                            reader.onload = function(e) {
                                imgPreview.src = e.target.result;
                                imgPreview.style.display = 'block';
                            };
                            reader.readAsDataURL(file);
                        }
                    });
                }

                // Reset preview
                imgPreview.src = '';
                imgPreview.style.display = 'none';

                const deleteBtn = newDiv.querySelector(`.${buttonDeleteClass}`);
                if (deleteBtn) {
                    deleteBtn.addEventListener('click', function() {
                        inputContainer.removeChild(newDiv);
                        handleDeleteButtons();
                        updateLabels();
                    });
                }

                newDiv.style.marginTop = '10px';
                inputContainer.appendChild(newDiv);
                updateLabels();
                handleDeleteButtons();
            }

            // Event listener untuk tombol tambah
            addButton.addEventListener('click', createNewInput);

            // Inisialisasi preview untuk input yang sudah ada
            const existingInputs = inputContainer.querySelectorAll(`.${inputDataClass}`);
            existingInputs.forEach((input, index) => {
                const previewContainer = input.closest('.flex').querySelector('.preview-container');
                const imgPreview = previewContainer.querySelector('img');

                input.addEventListener('change', function() {
                    const file = this.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            imgPreview.src = e.target.result;
                            imgPreview.style.display = 'block';
                        };
                        reader.readAsDataURL(file);
                    }
                });

                // Tambahkan event listener untuk tombol hapus
                document.querySelectorAll('.delete-btn').forEach(deleteBtn => {
                    deleteBtn.addEventListener('click', function() {
                        // Temukan container terdekat yang akan dihapus
                        const containerToRemove = this.closest('.flex');
                        const inputContainer = this.closest('#inputContainerRute');

                        if (inputContainer.querySelectorAll('.flex').length > 1) {
                            containerToRemove.remove();

                            // Update nomor label setelah penghapusan
                            updateLabels(inputContainer);
                        } else {
                            // Jika hanya satu input, reset input tersebut
                            resetInput(containerToRemove);
                        }
                    });
                });
            });

            updateLabels();
            handleDeleteButtons();
        }


        // setupInputHandlers('inputContainerRute', 'btnRute', 'Foto Rute Menuju Lokasi', 'file-input',
        // 'delete-btn');
        // setupInputHandlers('inputContainerLantai', 'btnLantai', 'Foto Lantai', 'file-input',
        //     'delete-btn');
        // setupInputHandlers('inputContainerLingkungan', 'btnLingkungan', 'Lingkungan', 'file-input',
        // 'delete-btn');


    });
</script>
