import PhotoSwipe from "photoswipe";
import PhotoSwipeLightbox from 'photoswipe/lightbox';
import 'photoswipe/style.css';
import { getLatestJobs } from "./data/getLatestJobs.js"
import emailjs from "@emailjs/browser";

const theme = document.querySelector("#change-theme");
const html = document.querySelector("html");
const containerGalleries = document.querySelector(".container-galleries");
const copyright = document.querySelector(".copyright");
const alert = document.getElementById("alert");

const serviceID = 'default_service';
const templateID = 'template_758pkwo';

copyright.innerHTML = `@ ${new Date().getFullYear()} - Todos los derechos reservados.`

document.addEventListener("DOMContentLoaded", () => {
    html.setAttribute("data-theme", window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" : "light")

    theme.addEventListener("change", () => {
        if (html.getAttribute("data-theme") === "dark") {
            html.setAttribute("data-theme", "light");
        } else {
            html.setAttribute("data-theme", "dark");
        }
    })

})

const configureEmailSendContact = () => {
    emailjs.init({
        publicKey: 'KjgzLqUvLg29kOMXi',
    });

    const form = document.querySelector("#contact-form");
    const btnSend = document.getElementById("button-send");

    form.addEventListener("submit", (event) => {
        event.preventDefault();
        btnSend.disabled = true;
        btnSend.value = "Enviando...";

        const formData = new FormData(event.target);
        const formObject = {};

        for (let [key, value] of formData.entries()) {
            formObject[key] = value;
        }

        if (!formObject.mensaje || !formObject.email) {
            alert.innerHTML = `Los campos <b>"Mensaje"</b> e <b>"Correo"</b> son obligatorios.`
            alert.classList.add("active");
            btnSend.disabled = false;
            btnSend.value = "Enviar";
            setTimeout(() => {
                alert.classList.remove("active");
            }, 5000);
        } else {
            emailjs.sendForm(serviceID, templateID, form)
                .then(() => {
                    btnSend.value = 'Enviar';
                    alert.innerHTML = `El correo ha sido enviado!`

                    alert.classList.add("active");
                    form.reset();
                    btnSend.disabled = false;
                })
                .catch((err) => {
                    btnSend.value = 'Enviar';
                    console.log(JSON.stringify(err));
                    btnSend.disabled = false;
                });

            setTimeout(() => {
                alert.classList.remove("active");
            }, 5000);
        }
    });
};

configureEmailSendContact()

// Trabajos previos
const setDataToGaleries = (client, id, info) => {
    const gallery = document.createElement("div");
    gallery.id = id;
    gallery.classList.add('pswp-gallery');

    const images = getLatestJobs(client).images;
    console.log(images);
    

    // Crea el primer elemento de imagen visible
    const firstImage = document.createElement("article");
    firstImage.style.maxHeight = "515px";
    firstImage.style.minHeight = "515px";
    firstImage.classList.add('flex', 'flex-col');
    const firstImageLink = document.createElement("a");
    firstImageLink.href = `/assets/img/jobs/${client}/${images[0]}.webp`;
    firstImageLink.dataset.pswpWidth = "3000";
    firstImageLink.dataset.pswpHeight = "2000";
    firstImageLink.dataset.cropped = "true";
    firstImageLink.ariaLabel = `Imagen correspondiente a cliente ${client}`
    const firstImageImg = document.createElement("img");
    firstImageImg.src = `/assets/img/jobs/${client}/${images[0]}.webp`;
    firstImageImg.width = 500;
    firstImageImg.height = 500;
    firstImageImg.alt = `${client.toLowerCase()}-0`; // Asignar el atributo alt aquí
    firstImageLink.append(firstImageImg);
    
    // Encabezado y footer de la tarjeta
    const header = document.createElement("header");
    header.textContent = client.toUpperCase();
    header.style.textAlign = "center";
    const footer = document.createElement("footer");
    footer.textContent = info.description;

    firstImage.append(firstImageLink);
    firstImage.insertAdjacentElement("afterbegin", header);
    firstImage.insertAdjacentElement("beforeend", footer);
    gallery.append(firstImage);

    // Crea un contenedor para ocultar las imágenes restantes inicialmente
    const hiddenImagesContainer = document.createElement('div');
    hiddenImagesContainer.classList.add('pswp-hidden-images'); // Agregar una clase personalizada para diseñar

    // Crear y ocultar elementos restantes
    images.slice(1).forEach((job, i) => {
        const hiddenImage = document.createElement("article");
        const hiddenImageLink = document.createElement("a");
        hiddenImageLink.href = `/assets/img/jobs/${client}/${job}.webp`;
        hiddenImageLink.dataset.pswpWidth = '1280';
        hiddenImageLink.dataset.pswpHeight = '720';
        hiddenImageLink.dataset.cropped = 'true';
        hiddenImageLink.ariaLabel = `Imagen correspondiente a cliente ${client}-${i}`
        const hiddenImageImg = document.createElement("img");
        hiddenImageImg.src = `/assets/img/jobs/${client}/${job}.webp`;
        hiddenImageImg.alt = `${client.toLowerCase()}-${i}`
        hiddenImageLink.append(hiddenImageImg);
        hiddenImage.append(hiddenImageLink);
        hiddenImagesContainer.append(hiddenImage);
    });

    gallery.append(hiddenImagesContainer);
    containerGalleries.appendChild(gallery);

    const lightbox = new PhotoSwipeLightbox({
        gallery: `#${id}`,
        children: 'a',
        pswpModule: PhotoSwipe,
        arrowKeys: true,
        initialZoomLevel: 'fit',
        secondaryZoomLevel: 1.5,
        maxZoomLevel: 1,
    });

    // Detector de eventos de clic a la primera imagen para activar PhotoSwipe
    firstImageLink.addEventListener('click', () => lightbox.init());

    lightbox.init();
};

const clients = ["zonis", "multipago", "vakoSRL"];
clients.forEach((job, i) => {
    const info = getLatestJobs(job);
    const index = i + 1;
    if (info) {
        const idGallery = `gallery-${job}-${index}`;
        setDataToGaleries(job, idGallery, info);
    }
});

const topTop = document.querySelector(".go-top");
window.addEventListener("scroll", () => {
    const scrollPos = window.scrollY;
    topTop.style.display = (scrollPos > 800)
        ? "block"
        : "none"
})
