document.addEventListener('DOMContentLoaded', function () {
    let circleCoordinatesContainer = document.getElementById('pin-coordinates-container');
    let addCircleCoordinateButton = document.getElementById('add-pin-item');
	let placeholderImg = ServerData.pluginUrl + 'assets/img/placeholder.png';

    addCircleCoordinateButton.addEventListener('click', function () {
        //cuenta numero de pines creados
        let index = circleCoordinatesContainer.children.length;
        //random values beetween 100 and 700 to pin positions by default
        if (index >= 2) return;
        let posX = Math.floor(Math.random() * 600) + 100;
        let posY =  Math.floor(Math.random() * 600) + 100;
        //crea un nuevo contenedor (div). el cual se usara para almacenar los controles de datos del pin correspondiente
        let newItem = document.createElement('div');
        newItem.classList.add('pin-item');
        //agrega un nuevo pin y el control para agregar tarjetas. la variable index se usa para identificar el pin actual en el repetidor
        //por ahora en la seccion de card solo existe el control de person_name y person_position
        newItem.innerHTML = `
                
                <button type="button" class="accordion"><span class="dashicons dashicons-arrow-right-alt2"></span>Pin ${index+1}</button>
                <div class="pin-accordion">
                <p>
                <label for="circle_coordinates[${index}][cx]"> Horizontal Position </label>
                <input type="number" name="circle_coordinates[${index}][cx]" value="${posX}" />
                </p>
                <p>
                <label for="circle_coordinates[${index}][cy]"> Vertical Position </label>
                <input type="number" name="circle_coordinates[${index}][cy]" value="${posY}" />
                </p>
                <p>
                <label for="circle_coordinates[${index}][circle_name]"> Pin Name </label>
                <input type="text" name="circle_coordinates[${index}][circle_name]" value="${index+1}" />
                </p>
                <!-- jo 11-07-24 image-form-control -->
                <div class="image-form-control">
                    <label for="circle_coordinates[${index}][circle_image][url]"> 
                        Pin Image 
                        <div class="nahiro-control-desc">
                            Click the box to select an image
                        </div>
                    </label>
                        
                        <div class="nahiro-img-control pin${index}-image">
                            <input type="hidden" name="circle_coordinates[${index}][circle_image][url]"
                            value="" 
                            class="pin${index}-image-upload-field" />
                           
                         
                                <div class="nahiro-img-preview pin${index}-image-preview">
                                <!-- Display image preview here -->
                                    <img src="${placeholderImg}" />
                                </div>
                                <a href="#" class="nahiro-img-delete pin${index}-delete-img hidden"><span class="dashicons dashicons-trash"></span></a>


                        </div>
                        
                </div>
                <!-- jo 04 julio inicio -->
                    <!-- circle hide -->
                    <p>
                    <label for="circle_coordinates[${index}][circle_hide]"> Hide Circle </label>
                    <select name="circle_coordinates[${index}][circle_hide]">
                        <option value="yes"> Yes </option>
                        <option value="no"> No </option>
                    </select>
                    </p>
                    <!-- circle color -->
                    <p>
                    <label for="circle_coordinates[${index}][circle_color]"> Circle Color </label>
                    <input class="icolor" type="color" name="circle_coordinates[${index}][circle_color]"  value="#fff" />
                    </p>
                    <!-- circle ratio -->
                    <p>
                    <label for="circle_coordinates[${index}][circle_ratio]"> Circle Size </label>
                    <input type="number" name="circle_coordinates[${index}][circle_ratio]" value="3" />
                    </p>
                    <!-- left (circle left) -->
                    <p>
                    <label for="circle_coordinates[${index}][left]"> Position Left Name </label>
                    <input type="number" name="circle_coordinates[${index}][left]" value="0" />
                    </p>
                    <!-- top  (circle top) -->
                    <p>
                    <label for="circle_coordinates[${index}][top]"> Position Top Name </label>
                    <input type="number" name="circle_coordinates[${index}][top]" value="70" />
                    </p>
                <!-- jo fin 04 julio -->    
                
                <!--card items-->
                <h4> Cards </h4>
                <div class="card-repeater">
                    
                    <div class="card-container">
                        <div class="card-item">
                        <p>
                            <label for="circle_coordinates[${index}][people][0][person_name]"> Name </label>
                            <input type="text" name="circle_coordinates[${index}][people][0][person_name]" value="Your Title Here"
                                maxlength="23" />
                        </p>
                        <p>
                            <label for="circle_coordinates[${index}][people][0][person_position]"> Information </label>
                            <input type="text" name="circle_coordinates[${index}][people][0][person_position]" value="Your Subtitle Here"
                                maxlength="53" />
                        </p>
                            <!-- person_phone -->
                        <p>
                            <label for="circle_coordinates[${index}][people][0][person_phone]"> Phone </label>
                            <input type="text" name="circle_coordinates[${index}][people][0][person_phone]" value="+49 XX XXX XXXX"
                                maxlength="30" />
                        </p>
                            <!-- person_email -->
                        <p>
                            <label for="circle_coordinates[${index}][people][0][person_email]"> Email </label>
                            <input type="email" name="circle_coordinates[${index}][people][0][person_email]"  value="mail@mail.com" />
                        </p>
                            <!-- person_image -->
                         <!-- jo 11-07-24  image form control-->
                        <div class="image-form-control">
                                  
                            <label for="circle_coordinates[${index}][people][0][person_image][url]"> Image </label>
                            
                                
                            <div class="nahiro-img-control card${index}0-image">

                                <input type="hidden"
                                name="circle_coordinates[${index}][people][0][person_image][url]"
                                value=""
                                class="card${index}0-image-upload-field" />

                                <div class="nahiro-img-preview card${index}0-image-preview">
                                    <!-- Display image preview here -->
                                </div>
                                <a href="#" class="nahiro-img-delete card${index}0-delete-img hidden"><span class="dashicons dashicons-trash"></span></a>

                            </div>
                                
                        </div>
                            <!-- remove card btn-->
                        
                            <button type="button" class="remove-card"> Remove Card </button>
                        
                        </div>
                    </div>
                        <button type="button" class="add-card"> Add Card </button>
                </div>
                </div>


                <button type="button" class="remove-circle-coordinate"><span class="dashicons dashicons-trash"></span></button>
            `;
        //agrega el nuevo elemento a la pagina
        circleCoordinatesContainer.appendChild(newItem);
        // jo 11-07-24 setupImage
        setupImageUpload('pin'+index);
        setupImageUpload('card'+index+'0');//always is added only the first card in this event

        //jo 3 julio 2024 nuevo
        /**
         * añade un event listener al recientemente creado boton de .add-card que al ser pulsado crea una nueva tarjeta
         */
        newItem.querySelector('.add-card').addEventListener('click', function () {
            addCard(newItem, index);
        });

        //la unica solucion que encontre para que se pueda eliminar la tarjeta por defecto del pin (solo al crearlo, no ocurre luego de guardar los datos). 
        //si esto se comenta, se puede crear una tarjeta 
        //por defecto que no se pueda eliminar similar al widget de elementor
        newItem.querySelectorAll('.remove-card').forEach(function (button) {
            button.addEventListener('click', function () {
                button.parentElement.remove();
            });
        });
        //fin jo 3 julio

        newItem.querySelector('.remove-circle-coordinate').addEventListener('click', function () {
            newItem.remove();
        });
        
        //accordion event
        newItem.querySelector(".accordion").addEventListener('click', function (){
            accordionClick(this);
        });//end accordion event
});


    //jo 3 julio


    //==================================
    //DOM Content Loaded EventListeners
    //=================================
    circleCoordinatesContainer.querySelectorAll('.add-card').forEach(function (button, pinIndex) {
        button.addEventListener('click', function () {
           //console.log(pinIndex);
            addCard(button.parentElement, pinIndex);
        });
    });

    //fin 3 julio

    //==================================
    //remove pin
    circleCoordinatesContainer.querySelectorAll('.remove-circle-coordinate').forEach(function (button) {
        button.addEventListener('click', function () {
            button.parentElement.remove();
        });
    });
    //=================================
    //remove card(person)
    circleCoordinatesContainer.querySelectorAll('.remove-card').forEach(function (button) {
        button.addEventListener('click', function () {
            button.parentElement.remove();
        });
    });

    //=================================
    //accordion initialization
    document.querySelectorAll('.accordion').forEach(function(button) {
        button.addEventListener('click', function(event) {
            accordionClick(this);
        });
    });

    //=================================
    //images fields (pins and cards) initialization
    var pinContainer = document.getElementById('pin-coordinates-container'); 
    var pinQuantity = pinContainer.children.length;

    //run the function for each pin
    //initialize the main function for each pin
    for(let i=0; i<pinQuantity; i++){
        setupImageUpload('pin'+i);
    }
    //add the function to any newly created pin
    // let addCircleCoordinateButton = document.getElementById('add-pin-item');
    addCircleCoordinateButton.addEventListener('click', function(){
        let npinQuantity = document.getElementById('pin-coordinates-container').children.length;
        setupImageUpload('pin'+npinQuantity);
    })

    //por cada .card-container, cuenta children.length y corre la funcion como se realizo anteriormente
    var cardsContainers = pinContainer.querySelectorAll('.card-container');
    for(let i =0; i<cardsContainers.length;i++){
        let cardItems = cardsContainers[i].querySelectorAll('.card-item');
        for(let j=0; j<cardItems.length;j++){
            setupImageUpload('card'+i+''+j);
        }
    }

    //==================================
    //Main Functions
    //=================================
    /**
     * function to select image in images fields an display a preview of that image applying the url of the image to an inner img element
     * 
     * @param {HTMLElement} element
     */
    function setupImageUpload(prefix) {
        var customUploader;
        var uploadBtn = jQuery('.' + prefix + '-image');
        var imgUrlInput = jQuery('.' + prefix + '-image-upload-field');
        var imgIdInput = jQuery('.' + prefix + '-img-id');
        var imgPreview = jQuery('.' + prefix + '-image-preview');
        var delImgLink = jQuery('.' + prefix + '-delete-img');

        // Ensure event handlers are only attached once
        uploadBtn.off('click').on('click', function (e) {
            e.preventDefault();
            if (customUploader) {
                customUploader.open();
                return;
            }
            customUploader = wp.media.frames.file_frame = wp.media({
                title: 'Choose Image',
                button: {
                    text: 'Choose Image'
                },
                multiple: false
            });

            customUploader.on('select', function () {
                // Get media attachment details from the frame state
                var attachment = customUploader.state().get('selection').first().toJSON();
                // Send the attachment URL to our custom image input field    
                imgUrlInput.val(attachment.url);
                // Send the attachment id to our hidden input
                imgIdInput.val(attachment.id);
                // Show on preview
                imgPreview.html('<img src="' + attachment.url + '" alt="Custom Image" style="max-width:254px;"/>');
                // Unhide the remove image link
                delImgLink.removeClass('hidden');
            });

            customUploader.open();

            
            
        });

        // DELETE IMAGE LINK
        delImgLink.off('click').on('click', function (event) {
            event.preventDefault();
            //avoids the triggering of the uploadBtn event
            event.stopPropagation();
            // Clear the URL input
            imgUrlInput.val('');
            // Clear out the preview image
            imgPreview.html('');
            // Hide the delete image link
            delImgLink.addClass('hidden');
            // Delete the image id from the hidden input
            imgIdInput.val('');
        });

        //remove class if item already has and image
        if(imgUrlInput.val() === ''){

        }else{
            delImgLink.removeClass('hidden');
        }
    
    }
    
    /**
     * Creates a new card element and attach its events and function associated with its fields
     *
     * @param {HTMLElement} element
     * @param {int} index 
     */
    function addCard(element, index){
        let cardContainer = element.querySelector('.card-container');
        //cardIndex permite reconocer los elementos hijos dentro del pin actual, cuenta el numero de cards creados para ir incrementandolo y permitir su guardado
        let cardIndex = cardContainer.children.length;
        if (cardIndex >= 2) return;
        let newCard = document.createElement('div');
        newCard.classList.add('card-item');
        newCard.innerHTML = `
                <p>
                <label for="circle_coordinates[${index}][people][${cardIndex}][person_name]"> Name </label>
                <input type="text" name="circle_coordinates[${index}][people][${cardIndex}][person_name]" value="Your Title Here"
                    maxlength="23" />
                </p>
                <p>
                <label for="circle_coordinates[${index}][people][${cardIndex}][position]"> Information </label>
                <input type="text" name="circle_coordinates[${index}][people][${cardIndex}][person_position]" value="Your Subtitle Here"
                    maxlength="53"/>
                </p>
                        <!-- person_phone -->
                        <p>
                        <label for="circle_coordinates[${index}][people][${cardIndex}][person_phone]"> Phone </label>
                        <input type="text" name="circle_coordinates[${index}][people][${cardIndex}][person_phone]" value="+49 XX XXX XXXX"
                            maxlength="30" />
                        </p>
                        <!-- person_email -->
                        <p>
                        <label for="circle_coordinates[${index}][people][${cardIndex}][person_email]"> Email </label>
                        <input type="email" name="circle_coordinates[${index}][people][${cardIndex}][person_email]" value="mail@mail.com"
                            maxlength="30" />
                        </p>
                        <!-- person_image -->
                        <!-- jo 11-07-24  image form control-->
                        <div class="image-form-control">
                                
                            <label for="circle_coordinates[${index}][people][${cardIndex}][person_image][url]"> Image </label>
                                
                            <div class="nahiro-img-control card${index}${cardIndex}-image">

                                <input type="hidden"
                                name="circle_coordinates[${index}][people][${cardIndex}][person_image][url]"
                                value=""
                                class="card${index}${cardIndex}-image-upload-field" />

                                <div class="nahiro-img-preview card${index}${cardIndex}-image-preview">
                                    <!-- Display image preview here -->
                                </div>
                                <a href="#" class="nahiro-img-delete card${index}${cardIndex}-delete-img hidden"><span class="dashicons dashicons-trash"></span></a>

                            </div>
                        </div>
                        

                <!-- remove card btn-->
                <button type="button" class="remove-card">Remove Card</button>
            `;
        //crea el elemento
        cardContainer.appendChild(newCard);
        // jo 11-07-24 setupImage
        //adjunta el evento de setupImage al elemento imagen recientemente agregado
        setupImageUpload('card'+index+''+cardIndex);//add the event to the newly created image element of the new card

        //crea un event listener para el boton .remove-card creado en la linea de codigo anterior. Al pulsarse el boton se elimina al elemento padre (la tarjeta)
        newCard.querySelector('.remove-card').addEventListener('click', function () {
            newCard.remove();
        });
    }
    
    /**
     * Opens an closes the accordion while changing the button icon
     *
     * @param {HTMLElement} element
     */
    function accordionClick(element){
        var panel = element.nextElementSibling;
        var arrowIcon = element.querySelector(".dashicons");
        // Toggle active class on accordion button
        // this class changes the max-height of the pin-accordion container by css showing its content
        element.classList.toggle('active_1');
        // Toggle arrow icon
        arrowIcon.classList.toggle('dashicons-arrow-down-alt2');//down arrow
        arrowIcon.classList.toggle('dashicons-arrow-right-alt2');//right arrow
    }

});