<style>
  .fake {
    background-image: url(img/bg05.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
  }

  .hr-style {
    opacity: 1;
    width: 50%;
  }

  .button-prev,
  .button-next {
    cursor: pointer;
    width: 40px;
    z-index: 50;
    transition: opacity 0.3s;
  }

  .bg-custom {
    background: #f0f4f2;
  }

  .bg-custom-transparent {
    background: rgba(240, 244, 242, 0.6);
  }

  .drop-card {
    border: 3px dashed var(--bs-primary);
    width: 50px;
    height: 50px;
  }

  .content-enfermedad img {
    height: 200px;
  }

  .card-drag {
    cursor: grab;
    width: 50px;
    height: 50px;
  }

  .card-drag img {
    width: 100%;
  }

  .card-drag.ui-draggable-dragging {
    cursor: grabbing;
  }

  .img-retro {
    top: -75px;
    left: 0;
    right: 0;
    margin: 0 auto;
    max-width: 40%;
  }


  .card-sort {
    min-height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    user-select: none;
    transition: transform 0.2s ease;
  }

  .card-sort:hover {
    transform: scale(1.05);
  }

  .ui-sortable-helper {
    transform: rotate(5deg);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  }

  .swiper-container {
    overflow: hidden;
  }

  #activity1 img {
    max-height: 250px;
  }
</style>


<div class='page-sco py-2 py-md-4 h-100'>
  <div class='container h-100'>
    <div class='row justify-content-center align-items-center h-100'>
      <div class='col-12'>
        <div class='row justify-content-center'>
          <div class="col-11 mb-2">
            <h2 class="text-center fw-bold text-primary">¿Cómo funciona la diálisis peritoneal?</h2>
            <hr class="border border-3 border-verde-oscuro hr-style mx-auto my-0">
            <h3 class="text-verde-oscuro fw-bold"><span class="text-gris">></span> Glucosa</h3>
          </div>
          <div class="col-12">
            <div class="row justify-content-center align-content-center">
              <div class="col-1 d-flex  justify-content-center align-items-center" style="z-index: 50;">
                <img src="img/left.png" class="img-fluid button-prev" style="display: none;" alt="Left">
              </div>
              <div class="col-10">
                <div class="swiper-container">
                  <div class="swiper-wrapper">
                    <div class="swiper-slide">
                      <div class="card bg-transparent text-white border-0">
                        <div class="card-body text-center d-flex flex-column justify-content-center align-items-center">
                          <div class="col-12">
                            <div class="card border-0 my-2 rounded bg-secondary shadow p-3 text-center">
                              <div class="d-flex justify-content-center align-items-center flex-row">
                                <img src="img/2.1.png" class="img-fluid mx-3">
                                <p class="mb-0"><strong>Instrucciones:</strong> Observa los tapones, cada uno tiene un
                                  color
                                  que indica la concentración de su solución. Tu tarea es arrastrarlos hacia la solución
                                  que
                                  les corresponde.​</p>
                              </div>
                            </div>
                          </div>
                          <div id="drag-drop-activity" class="col-12">
                            <div class="row justify-content-center">
                              <div class="col-12">
                                <div id="content-drags" class="d-flex flex-row justify-content-center gap-3"></div>
                              </div>
                              <div class="col-12 mt-3">
                                <div class="card bg-transparent border-0 rounded-0 shadow-none p-0">
                                  <div class="d-flex flex-row justify-content-center gap-3">
                                    <div class="content-enfermedad text-center">
                                      <div class="card rounded bg-custom-transparent border-0 shadow px-3 py-2 mt-2">
                                        <img src="img/5.1a.png" class="img-fluid">
                                      </div>
                                    </div>
                                    <div class="content-enfermedad text-center">
                                      <div class="card rounded bg-custom-transparent border-0 shadow px-3 py-2 mt-2">
                                        <img src="img/5.2a.png" class="img-fluid">
                                      </div>
                                    </div>
                                    <div class="content-enfermedad text-center">
                                      <div class="card rounded bg-custom-transparent border-0 shadow px-3 py-2 mt-2">
                                        <img src="img/5.3a.png" class="img-fluid">
                                      </div>
                                    </div>
                                    <div class="content-enfermedad text-center">
                                      <div class="card rounded bg-custom-transparent border-0 shadow px-3 py-2 mt-2">
                                        <img src="img/5.4a.png" class="img-fluid">
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="swiper-slide">
                      <div class="card border-0 bg-transparent">
                        <div class="card-body d-flex flex-column justify-content-center align-items-center">
                          <div class="col-9">
                            <div class="card border-0 my-2 rounded bg-secondary shadow p-3 text-center">
                              <div class="d-flex justify-content-center align-items-center flex-row">
                                <img src="img/2.1.png" class="img-fluid mx-3">
                                <p class="mb-0"><strong>Instrucciones:</strong> Arrastre los pasos del recambio para
                                  colocarlos en el orden correcto.</p>
                              </div>
                            </div>
                          </div>

                          <div id="activity1" class="my-4">
                            <div id="sortable-cards" class="d-flex flex-row gap-3 justify-content-center flex-wrap">
                              <!-- Las tarjetas se generarán dinámicamente -->
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-1 d-flex  justify-content-center align-items-center" style="z-index: 50;">
                <img src="img/right.png" class="img-fluid button-next" alt="Left">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div class="d-none">
  <div id="pop0">
    <div class="container-fluid">
      <div class=" w-100 text-center">
        <img src="img/3.5.png" class="img-fluid">
      </div>
      <div class="row justify-content-center">
        <div class="col-12 text-center mb-2">
          <h3 class="text-secondary-dark fw-bold">¡Bien hecho!</h3>
        </div>
        <div class="col-12 text-center">
          <p class="mb-0">Has concluido la actividad.</p>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
  $(function () {
    'use strict';
    $('body').addClass('fake');
    let questions;
    let currentQuestionIndex = 0;
    let currentQuestion;
    let correctQuestions = 0;
    const bad = CourseNav.createSound('audio/feedback-incorrect.mpeg');
    const good = CourseNav.createSound('audio/feedback-correct.mpeg');

    const urlExcelFile = 'Drag_Drop3.xlsx';

    function readExcelFile(url, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'arraybuffer';
      xhr.onload = function (e) {
        var arrayBuffer = xhr.response;
        var data = new Uint8Array(arrayBuffer);
        var workbook = XLSX.read(data, { type: "array" });
        var result = {};
        workbook.SheetNames.forEach(sheetName => {
          var sheet = workbook.Sheets[sheetName];
          result[sheetName] = XLSX.utils.sheet_to_json(sheet);
        });
        callback(result);
      };
      xhr.send();
    }

    function procesarPreguntas(data) {
      const preguntas = data.map(fila => {
        const opciones = [];
        Object.keys(fila).forEach(key => {
          if (key.startsWith('opcion')) {
            opciones.push({
              text: fila[key].trim(),
              correct: key === 'opcion_c'
            });
          }
        });
        return {
          pregunta: fila.pregunta.trim(),
          opciones: opciones,
          retroalimentacion_correcta: fila.retroalimentacion_correcta.trim(),
          retroalimentacion_incorrecta: fila.retroalimentacion_incorrecta.trim()
        };
      });
      return preguntas;
    }

    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    }

    function CreateDragAndDrop() {
      $('.content-enfermedad').each(function (index) {
        if (questions && questions[index]) {
          const dropDiv = `<div class="position-relative card bg-transparent drop-card shadow-none rounded-0 p-0 mx-auto" data-drop="${index}"></div>`;
          $(dropDiv).insertAfter($(this).find('.card'));
        }
      });

      // Crear todas las respuestas en #content-drags
      let allOptions = [];
      questions.forEach((question, index) => {
        question.opciones.forEach(opcion => {
          allOptions.push({ text: opcion.text, index: index });
        });
      });

      allOptions = shuffleArray(allOptions);
      allOptions.forEach(option => {
        const dragDiv = `<div class="card card-drag bg-transparent border border-2 border-secondary rounded-0 shadow-none text-white text-center" data-drag="${option.index}">${option.text}</div>`;
        $('#content-drags').append(dragDiv);
      });
    }

    function initializeDragAndDrop() {
      $('.card-drag').draggable({
        revert: 'invalid',
        revertDuration: 300,
        containment: "#drag-drop-activity",
        cursor: "grabbing",
        start: function (event, ui) {
          $(this).css('z-index', 1000);
          ui.position.left = 0;
          ui.position.top = 0;
        },
        drag: function (event, ui) {
          var changeLeft = ui.position.left - ui.originalPosition.left;
          var newLeft = ui.originalPosition.left + changeLeft;
          var changeTop = ui.position.top - ui.originalPosition.top;
          var newTop = ui.originalPosition.top + changeTop;
          ui.position.left = newLeft;
          ui.position.top = newTop;
        },
        stop: function (event, ui) {
          $(this).css('z-index', 1);
        }
      });

      $('.drop-card').droppable({
        accept: '.card-drag',
        tolerance: 'pointer',
        drop: function (event, ui) {
          const dragData = ui.helper.data('drag');
          const dropData = $(this).data('drop');

          if (dragData == dropData) {
            good.play();
            ui.helper.css({ position: 'static', top: 'auto', left: 'auto' }).appendTo(this);
            ui.helper.draggable('disable');
            $(this).droppable('disable');

            // Verificar si todos están completados
            if ($('.drop-card:not(.ui-droppable-disabled)').length === 0) {
              Completed();
            }
          } else {
            bad.play();
            ui.helper.draggable('option', 'revert', true);
          }
        }
      });
    }

    function Completed() {
      const html = $("#pop0").html();
      Swal.fire({
        html: html,
        target: "body",
        customClass: {
          popup: 'pop_html_style border border-3 border-primary rounded-4',
          confirmButton: 'btn text-white bg-primary amor fw-semibold animate__animated animate__pulse animate__infinite'
        },
        confirmButtonText: "Cerrar",
        showConfirmButton: true,
        allowOutsideClick: false,
        allowEscapeKey: false,
        focusConfirm: false,
        backdrop: "rgba(65, 60, 60, .95)",
        width: "35em",
        didOpen: () => {
        },
        didClose: () => {
          CourseNav.audioController.stopAudio();
          //CourseNav.soundClick();
          CourseNav.setSlideVisited();
          /* setTimeout(() => {
            Swal.close();
            CourseNav.nextSlide();
          }, 100); */
        },
      });
    }

    readExcelFile(urlExcelFile, function (data) {
      const hojaDatos = data["DragAndDrop"];
      questions = procesarPreguntas(hojaDatos);
      CreateDragAndDrop();
      initializeDragAndDrop();
      igualarAlturaBgCustomTransparent();
    });

    // Ajustar altura de todos los elementos .bg-custom-transparent al más alto
    function igualarAlturaBgCustomTransparent() {
      var maxHeight = 0;
      $('.bg-custom-transparent').each(function () {
        $(this).css('height', 'auto'); // Resetear altura para medir correctamente
        var h = $(this).outerHeight();
        if (h > maxHeight) maxHeight = h;
      });
      $('.bg-custom-transparent').css('height', maxHeight + 'px');
    }
    $(window).on('resize', igualarAlturaBgCustomTransparent);
    igualarAlturaBgCustomTransparent();




    // Función para mezclar array (algoritmo Fisher-Yates)
    function shuffleArray(array) {
      const shuffled = [...array];
      for (let i = shuffled.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
      }
      return shuffled;
    }

    // Crear y mezclar las tarjetas
    function createShuffledCards() {
      const cards = [1, 2, 3];
      const shuffledCards = shuffleArray(cards);
      const container = $('#sortable-cards');

      // Limpiar contenedor
      container.empty();

      // Crear tarjetas mezcladas
      shuffledCards.forEach(number => {
        const cardHtml = `
                        <div class="card border-0 card-sort bg-verde-claro text-white fw-bold text-center" 
                             data-order="${number}" 
                             style="cursor:grab;">
                          <div class="card-body px-0 py-0">
                            <img src="img/5.${number}b.png" class="img-fluid">
                            </div>
                        </div>
                    `;
        container.append(cardHtml);
      });
    }

    // Verificar si las tarjetas están en orden correcto
    function checkOrder() {
      let correct = true;
      $('#sortable-cards .card-sort').each(function (index) {
        if ($(this).data('order') === index + 1) {
          $(this).removeClass('bg-verde-claro').addClass('bg-success');
        } else {
          $(this).css('background', ''); // reset
          correct = false;
        }
      });
      return correct;
    }

    // Inicializar Swiper
    var mySwiper = new Swiper('.swiper-container', {
      loop: false,
      allowTouchMove: false,
      simulateTouch: false,
      navigation: {
        nextEl: '.button-next',
        prevEl: '.button-prev',
      },
    });

    // Función para actualizar botones de navegación
    function updateNavButtons(swiper) {
      var prevBtn = document.querySelector('.button-prev');
      var nextBtn = document.querySelector('.button-next');
      var totalSlides = swiper.slides ? swiper.slides.length : 0;

      if (totalSlides <= 1) {
        $(prevBtn).hide();
        return;
      }

      if (swiper.activeIndex === 0) {
        $(prevBtn).hide();
        $(nextBtn).show();
      } else if (swiper.activeIndex === totalSlides - 1) {
        $(nextBtn).hide();
        $(prevBtn).show();
      } else {
        $(prevBtn).show();
        $(nextBtn).show();
      }
    }

    // Eventos de Swiper
    mySwiper.on('slideChange', function () {
      updateNavButtons(mySwiper);
    });

    // Inicializar estado de los botones
    updateNavButtons(mySwiper);

    // Crear tarjetas mezcladas al cargar
    createShuffledCards();

    // Configurar sortable
    $('#sortable-cards').sortable({
      axis: 'x',
      containment: '#activity1',
      cursor: 'grabbing',
      tolerance: 'pointer',
      update: function (event, ui) {
        if (checkOrder()) {
          const html = $("#pop0").html();
          Swal.fire({
            html: html,
            target: "body",
            customClass: {
              popup: 'pop_html_style border border-3 border-primary rounded-4',
              confirmButton: 'btn text-white bg-primary amor fw-semibold animate__animated animate__pulse animate__infinite'
            },
            confirmButtonText: "Cerrar",
            showConfirmButton: true,
            allowOutsideClick: false,
            allowEscapeKey: false,
            focusConfirm: false,
            backdrop: "rgba(65, 60, 60, .95)",
            width: "35em",
            didOpen: () => {
            },
            didClose: () => {
              CourseNav.audioController.stopAudio();
              //CourseNav.soundClick();
              CourseNav.setSlideVisited();
              /* setTimeout(() => {
                Swal.close();
                CourseNav.nextSlide();
              }, 100); */
            },
          });
        }
      },
      start: function (event, ui) {
        ui.item.addClass('ui-sortable-helper');
      },
      stop: function (event, ui) {
        ui.item.removeClass('ui-sortable-helper');
      }
    });

    // Hacer las tarjetas arrastrables
    $('#sortable-cards').on('mousedown touchstart', '.card-sort', function () {
      $(this).css('cursor', 'grabbing');
    });

    $(document).on('mouseup touchend', function () {
      $('.card-sort').css('cursor', 'grab');
    });

    // Botón para reiniciar el juego (opcional)
    $('.button-prev').on('click', function () {
      setTimeout(createShuffledCards, 300); // Crear nuevas tarjetas mezcladas
    });
  });
</script>