import './variables';
import cardValidator from "card-validator";
window.cardValidator = cardValidator;
import { loadCountries, loadStates, loadCities } from './location';
window.loadCountries = loadCountries;
window.loadStates = loadStates;
window.loadCities = loadCities;
import $ from 'jquery';
window.$ = window.jQuery = $;
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import "keen-slider/keen-slider.min.css";
import KeenSlider from "keen-slider";

gsap.registerPlugin(ScrollTrigger);


export function textReveal({ container, 
    selector = ".sgs_txt", 
    scroll = false, 
    duration = 0.6, 
    stagger = 0.05, 
    ease = "power3.out", }) { 
        if (!container) return; 
        const items = container.querySelectorAll(selector); 
        if (!items.length) return; 
    return gsap.from(items, { opacity: 0, y: 16, duration, stagger, ease, clearProps: "transform,opacity", scrollTrigger: scroll ? { trigger: container, start: "top 80%", once: true, } : undefined, }); }
    
    const items = document.querySelectorAll(".sgs_txt");
    
    gsap.from(items, { 
            opacity: 0, 
            y: 16, 
            duration: 0.6, 
            stagger: 0.05, 
            ease: "power3.out", });

 requestAnimationFrame(() => {
  requestAnimationFrame(() => {
    const wraps = document.querySelectorAll(".sxs-rtxt .sgs_txtwrp");

    if (!wraps.length) {
      console.log("No se encontraron textos");
      return;
    }

    wraps.forEach((wrap, i) => {
      const letters = wrap.querySelectorAll(".sgs_txt");

      gsap.set(letters, {
        opacity: 0,
        y: 14,
      });

      gsap.to(letters, {
        opacity: 1,
        y: 0,
        duration: 3,
        stagger: 0.75,
        ease: "power3.out",
        delay: i * 0.45, 
        clearProps: "transform,opacity",
        scrollTrigger: {
        trigger: wrap,
        start: "top 85%",
        toggleActions: "play none none none",
        },
      });
    });
  });
}); 

document.addEventListener("DOMContentLoaded", () => {
  gsap.registerPlugin(ScrollTrigger);

  const section = document.querySelector(".sxs-pxsec");
  if (!section) return;

  const header = document.querySelector(".sxs-header");
  const hH = header ? header.clientHeight : 0;

  const trackLeft = section.querySelector(
    ".sxs-pxsec__col--left .sxs-pxsec__track"
  );
  const trackCenter = section.querySelector(
    ".sxs-pxsec__col--center .sxs-pxsec__track"
  );
  const trackRight = section.querySelector(
    ".sxs-pxsec__col--right .sxs-pxsec__track"
  );

  if (!trackLeft || !trackCenter || !trackRight) return;

  const cH = section.clientHeight;
  const tLH = trackLeft.clientHeight;
  const tCH = trackCenter.clientHeight;
  const tRH = trackRight.clientHeight;

  // 🔽 START desplazamiento (ambos bajan)
  const startOffset = -(Math.max(tLH, tRH) - cH);
  const scrollLen = Math.max(tLH, tCH, tRH);

  const mm = gsap.matchMedia();

  mm.add("(min-width: 768px)", () => {
    // posiciones iniciales
    gsap.set([trackLeft, trackRight], { y: startOffset });

    // 📌 pin
    ScrollTrigger.create({
      trigger: section,
      start: `top +=${hH}`,
      end: `+=${scrollLen}`,
      pin: true,
      pinSpacing: true,
    });

    // ⬇️ LEFT + RIGHT bajan juntos
    gsap.to([trackLeft, trackRight], {
      y: 0,
      ease: "none",
      scrollTrigger: {
        trigger: section,
        start: `top +=${hH}`,
        end: `+=${scrollLen}`,
        scrub: 1,
      },
    });

    return () => {
      ScrollTrigger.getAll().forEach(t => t.kill());
    };
  });
});


function formatCardExpirationDate(v) {
    let cV = v.replace(/\D/g, "").slice(0, 4);

    let month = cV.slice(0, 2);

    if (month.length === 1 && parseInt(month, 10) > 1) {
        month = "0" + month;
        cV = month + cV.slice(1);
    }

    if (month.length === 2) {
        let m = parseInt(month, 10);
        if (m === 0) month = "01";
        else if (m > 12) month = "12";
    }

    let year = cV.slice(2, 4);

    let result = month;
    if (cV.length > 2) result += " / " + year;

    return result;
}

function formatCardNumberWithGaps(v) {
    var vv = luhnCheck(v);
    var c = vv.card;

    if (!c) {
        return v
            .replace(/\D/g, "")
            .replace(/(.{4})/g, "$1 ")
            .trim();
    }

    var gtt = c.gaps || [4, 8, 12, 16];
    var clF = v.replace(/\D/g, "");
    var pArr = [];
    var ltIdx = 0;

    for (var i = 0; i < gtt.length; i++) {
        var g = gtt[i];
        if (clF.length > g) {
            pArr.push(clF.substring(ltIdx, g));
            ltIdx = g;
        } else {
            break;
        }
    }

    pArr.push(clF.substring(ltIdx));

    return $.grep(pArr, function (n) {
        return n;
    }).join(" ");
}

function validateCardNumber(v) {
    var clean = v.replace(/\D/g, "");
    if (clean.length <= 8) return true;
    return luhnCheck(clean) ? true : "Número de tarjeta inválido";
}

function luhnCheck(num) {
    var sum = 0, shouldDouble = false;
    for (var i = num.length - 1; i >= 0; i--) {
        var digit = parseInt(num.charAt(i), 10);
        if (shouldDouble) {
            digit *= 2;
            if (digit > 9) digit -= 9;
        }
        sum += digit;
        shouldDouble = !shouldDouble;
    }
    return sum % 10 === 0;
}


function getImgByTitle(type = null) {
    const cardsArr = [
        { title: "Visa", type: "visa", img: "svg/card-icon-visa.svg", def: true },
        { title: "MasterCard", type: "mastercard", img: "svg/card-icon-mastercard.svg", def: true },
        { title: "American Express", type: "american-express", img: "svg/card-icon-amex.svg", def: true },
        { title: "Diners", type: "diners-club", img: "svg/card-icon-diners.svg", def: true },
        { title: "Discover", type: "discover", img: "images/card-icon-discover.svg" },
        { title: "JCB", type: "jcb", img: "images/card-icon-jcb.svg" },
        { title: "UnionPay", type: "unionpay", img: "images/card-icon-unionpay.svg" }
    ];

    const buildImg = card => `<img alt="${card.title}" loading="lazy" class="active" src="${card.img}">`;
    const defCards = cardsArr.filter(card => card.def === true);
    if (!type) {
        return defCards.map(buildImg).join("");
    }
    const card = defCards.find(card => card.type === type);
    return card ? buildImg(card) : "";
}

function getCardType(a) {
    const clean = a.replace(/\D/g, "");
    const result = cardValidator.number(clean);
    return result.card ? result.card.type : null;
}

$(document).on("input", 'input[required],textarea[required]', function () {

    const billingActive = $("#f-billing").is(":checked");
    const $input = $(this);
    const id = $input.attr("id") || "";
    if (id.startsWith("f-facturacion") && billingActive) {
        return;
    }
    let value = $.trim($input.val());
    let hasValue = value !== "";
    let isValid = hasValue;
    const mode = $input.attr("inputmode");
    if (mode === "numeric" || mode === "tel") {
        value = value.replace(/\D/g, "");
        $input.val(value);
        hasValue = value !== "";
        isValid = hasValue;
    }
    if ($input.attr("type") === "email") {
        const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
        isValid = hasValue && ok;
    }
    if ($input.is("input") && $input.attr("type") !== "email") {
        isValid = value.length >= 2;
    }
    if ($input.is("textarea")) {
        isValid = value.length >= 10;
    }
    const $frame = $("#frame-" + id.replace(/^f-/, ""));

    $frame
        .removeClass("sxs-fcon--has-errors sxs-fcon--is-filled")
        .addClass(
            isValid
                ? "sxs-fcon--is-filled sxs-fcon--has-label"
                : "sxs-fcon--has-errors sxs-fcon--has-label"
        );
});


$(document).on("input", "#f-expiration_date", function () {
    this.value = formatCardExpirationDate(this.value);
    const $el = $("#frame-expiration_date");
    $el.removeClass("sxs-fcon--has-errors sxs-fcon--is-filled");
    if (this.value === "") {
        $el.addClass("sxs-fcon--has-errors sxs-fcon--has-label");
    } else {
        $el.addClass("sxs-fcon--is-filled sxs-fcon--has-label");
    }
});


$(document).on("input", "#f-cvv2", function () {
    this.value = this.value.replace(/\D/g, "").slice(0, 4);
    const $el = $("#frame-cvv2");
    $el.removeClass("sxs-fcon--has-errors sxs-fcon--is-filled");
    if (this.value === "") {
        $el.addClass("sxs-fcon--has-errors sxs-fcon--has-label");
    } else {
        $el.addClass("sxs-fcon--is-filled sxs-fcon--has-label");
    }
});

$(document).on("input", "#f-card_number", function (e) {

    var cardType = getCardType(this.value);
    var imgVisa = getImgByTitle(cardType);
    $("#f-card_fbox__med").html(imgVisa);

    var input = this;
    var cleanValue = input.value.replace(/\D/g, "");
    input.value = formatCardNumberWithGaps(cleanValue);
    var result = validateCardNumber(cleanValue);

    if (this.value === "") {
        $("#frame-card_number").addClass("sxs-fcon--has-errors sxs-fcon--is-filled").addClass("sxs-fcon--has-label");
        $("#f-card_fbox__med").html(CardIconError());
    } else {
        $("#frame-card_number").removeClass("sxs-fcon--has-errors sxs-fcon--is-filled").addClass("sxs-fcon--has-label");
    }

    if (result !== true) {
        $("#frame-card_number").addClass("sxs-fcon--has-errors sxs-fcon--is-filled").addClass("sxs-fcon--has-label");
        $("#f-card_fbox__med").html(CardIconError());
    }

});

$("#entrega_pais, #entrega_estado, #entrega_ciudad,#entrega_envio_metodo").on("change", function () {
    const $input = $(this);
    const id = $input.attr("id") || "";
    const $frame = $("#frame-" + id.replace(/^f-/, ""));
    $frame.removeClass("sxs-fcon--has-errors sxs-fcon--is-filled");
    if ($input.val() === "0") {
        $frame.addClass("sxs-fcon--has-errors sxs-fcon--has-label");
    } else {
        $frame.addClass("sxs-fcon--is-filled sxs-fcon--has-label");
    }
});

$("#facturacion_pais, #facturacion_estado, #facturacion_ciudad").on("change", function () {
    const $input = $(this);
    const id = $input.attr("id") || "";
    const $frame = $("#frame-" + id.replace(/^f-/, ""));
    $frame.removeClass("sxs-fcon--has-errors sxs-fcon--is-filled");
    if ($input.val() === "0") {
        $frame.addClass("sxs-fcon--has-errors sxs-fcon--has-label");
    } else {
        $frame.addClass("sxs-fcon--is-filled sxs-fcon--has-label");
    }
});

function useInViewJS({
    element,          // Elemento DOM a observar
    triggerOnce = true,
    root = null,
    threshold = 0,
    shouldWatch = true,
    onChange = () => { }
} = {}) {

    if (!shouldWatch || !element) return () => { };

    let inView = false;

    const observer = new IntersectionObserver(entries => {
        const entry = entries[0];
        const isIntersecting = entry.isIntersecting;

        if (!triggerOnce || (triggerOnce && !inView)) {
            inView = isIntersecting;
            onChange(inView, entry);
        }

        if (triggerOnce && isIntersecting) {
            observer.unobserve(element);
            observer.disconnect();
        }
    }, { threshold, root });

    observer.observe(element);
    return () => observer.disconnect();
}


document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".sxs-fdin.anmt").forEach((el, index) => {
        el.style.setProperty("--_idx", index);
        useInViewJS({
            element: el,
            threshold: 0.25,
            triggerOnce: true,
            onChange: (inView) => {
                el.classList.toggle("is-visible", inView);
            }
        });
    });
});


 document.addEventListener("DOMContentLoaded", function () {
    const combos = document.querySelectorAll(".sxs-fcdrp");
    combos.forEach(combo => {

        const btn = combo.querySelector(".sxs-fcdrp__btn");
        const drop = combo.querySelector(".sxs-fcdrp__drp");
        const options = combo.querySelectorAll(".sxs-fcdrp__op");
        const title = combo.querySelector(".sxs-fcdrp__tit");

        let isOpen = false;

        // preparar altura animable
        drop.style.height = "0px";
        drop.style.overflow = "hidden";

        function open() {
            combo.classList.add("is-open");
            combo.setAttribute("aria-hidden", "false");

            const fullHeight = drop.scrollHeight;
            drop.style.height = fullHeight + "px";

            isOpen = true;
        }

        function close() {
            drop.style.height = "0px";

            combo.classList.remove("is-open");
            combo.setAttribute("aria-hidden", "true");

            isOpen = false;
        }

        function toggle() {
            isOpen ? close() : open();
        }

        // botón principal
        btn.addEventListener("click", function (e) {
            e.stopPropagation();
            toggle();
        });

        // opciones
        options.forEach(op => {
            op.addEventListener("click", function () {
                options.forEach(o => o.classList.remove("active"));
                this.classList.add("active");
                title.textContent = this.textContent;                
                listado(this.value)
                close();
            });
        });

        // click fuera
        document.addEventListener("click", function (e) {
            if (!combo.contains(e.target)) {
                close();
            }
        });

        // recalcular altura si está abierto
        window.addEventListener("resize", function () {
            if (isOpen) {
                drop.style.height = drop.scrollHeight + "px";
            }
        });

    });

});

function listado(ord) {
    const path = window.location.pathname;
    const url = path.split('/').pop();
    $("#sec-main-category").empty().html('Cargando...');
        $.get("../categorylist/"+url+"/"+ord, function(data) {
        $("#sec-main-category").fadeIn(1000).html(data);
    }); 
}


   document.addEventListener("DOMContentLoaded", function () {

    const tabsContainer = document.querySelector(".sxs-tabs");
    const tabs = document.querySelectorAll(".sxs-tabs__tab");
    const buttons = document.querySelectorAll(".sxs-tabs__btn");
    const panels = document.querySelectorAll(".o_panel");

    const defaultTab = "que-es-la-zona";

    function moverIndicador(tab) {
        const btn = tab.querySelector(".sxs-tabs__btn");

        const rect = btn.getBoundingClientRect();
        const parentRect = tabsContainer.getBoundingClientRect();

        tabsContainer.style.setProperty("--_i-top", "5px");
        tabsContainer.style.setProperty("--_i-left", (rect.left - parentRect.left) + "px");
        tabsContainer.style.setProperty("--_i-width", rect.width + "px");
        tabsContainer.style.setProperty("--_i-height", "60px");
    }

    function activarTab(slug, updateURL = true) {

        let tabActivo = null;

        // tabs
        tabs.forEach(tab => {
            const btn = tab.querySelector(".sxs-tabs__btn");

            if (btn.dataset.tab === slug) {
                tab.classList.add("active");
                tabActivo = tab;
            } else {
                tab.classList.remove("active");
            }
        });
        
        panels.forEach(panel => {
            panel.classList.toggle("active", panel.dataset.tab === slug);
        });
        
        if (tabActivo) {
            moverIndicador(tabActivo);

            if (updateURL) {
                history.pushState(null, null, "#" + slug);
            }
        }
    }

    buttons.forEach(btn => {
        btn.addEventListener("click", function () {
            const slug = btn.dataset.tab;
            activarTab(slug);
        });
    });

    let hash = window.location.hash.replace("#", "");

    if (!hash || !document.querySelector(`.o_panel[data-tab="${hash}"]`)) {
        hash = defaultTab;
        if (window.location.pathname.includes("ciencia")) {
        history.replaceState(null, null, "#" + hash);        
        }
    }

    activarTab(hash, false);

    window.addEventListener("popstate", function () {
        let hash = window.location.hash.replace("#", "");
        if (hash) activarTab(hash, false);
    });
    
    window.addEventListener("resize", function () {
        const activeTab = document.querySelector(".sxs-tabs__tab.active");
        if (activeTab) moverIndicador(activeTab);
    });

});


 document.addEventListener("DOMContentLoaded", function () {
    const accordions = document.querySelectorAll(".sxs-acc");
    accordions.forEach(acc => {
        const header = acc.querySelector(".sxs-acc__hdr");
        const body = acc.querySelector(".sxs-acc__bod");

        header.addEventListener("click", function () {

            const group = acc.getAttribute("data-sub");
            const isOpen = acc.classList.contains("is-open");
            
            if (isOpen) {
                acc.classList.remove("is-open");
                acc.classList.add("is-closed");

                header.classList.remove("is-open");
                header.classList.add("is-closed");
                header.setAttribute("aria-label", "Abrir menú");

                body.classList.remove("is-open");
                body.classList.add("is-closed");
                if (!body.querySelector(".sec-des")) {
                body.style.maxHeight = "0px";
                body.style.overflow = "hidden";    
                }        
                return; 
            }

            const sameGroup = document.querySelectorAll(`.sxs-acc[data-sub="${group}"]`);

            sameGroup.forEach(item => {
                item.classList.remove("is-open");
                item.classList.add("is-closed");

                const h = item.querySelector(".sxs-acc__hdr");
                const b = item.querySelector(".sxs-acc__bod");

                h.classList.remove("is-open");
                h.classList.add("is-closed");
                h.setAttribute("aria-label", "Abrir menú");

                b.classList.remove("is-open");
                b.classList.add("is-closed");
                if (!body.querySelector(".sec-des")) {
                    b.style.maxHeight = "0px";
                    b.style.overflow = "hidden";
                }
            });
            
            acc.classList.add("is-open");
            acc.classList.remove("is-closed");
            header.classList.add("is-open");
            header.classList.remove("is-closed");
            header.setAttribute("aria-label", "Cerrar menú");
            body.classList.add("is-open");
            body.classList.remove("is-closed");
            if (!body.querySelector(".sec-des")) {
                body.style.overflow = "hidden";
                body.style.maxHeight = body.scrollHeight + "px";             
            }
        });
    });

}); 

document.addEventListener("DOMContentLoaded", () => {
  const tabs = document.querySelectorAll(".sxs-stabs__tab");
  const buttons = document.querySelectorAll(".sxs-stabs__btn");
  const sampItems = document.querySelectorAll(".sec-steps__samp-ite");
  const textItems = document.querySelectorAll(".sec-steps__text-ite");
  if (!tabs.length || !buttons.length) return;
  const activateTab = (index) => {    
    tabs.forEach(tab => tab.classList.remove("active"));
    sampItems.forEach(item => item.classList.remove("in-view"));
    textItems.forEach(item => item.classList.remove("in-view"));    
    tabs[index].classList.add("active");    
    if (sampItems[index]) sampItems[index].classList.add("in-view");
    if (textItems[index]) textItems[index].classList.add("in-view");
  };
  buttons.forEach((btn, i) => {
    btn.addEventListener("click", () => activateTab(i));
  });
  
});
 

document.addEventListener("DOMContentLoaded", () => {
  const sliders = document.querySelectorAll(".sxs-cardscar__lis");
  sliders.forEach((container) => {
    const slider = new KeenSlider(container, {
      loop: true,
      mode: "snap",
      slides: { perView: 4, spacing: 20 },
      breakpoints: {
        "(max-width: 1024px)": { slides: { perView: 2, spacing: 15 } },
        "(max-width: 600px)": { slides: { perView: 1, spacing: 10 } }
      }
    });
    
    const wrapper = container.closest(".sxs-car");
    const prev = wrapper?.querySelector(".sxs-car__arws-arw--prev");
    const next = wrapper?.querySelector(".sxs-car__arws-arw--next");
    prev?.addEventListener("click", () => slider.prev());
    next?.addEventListener("click", () => slider.next());
  });
});


document.addEventListener("DOMContentLoaded", function () {
    const btnSearch = document.querySelector(".sxs-header__menu-col--search .sxs-sbtn");
    const searchBar = document.querySelector(".sxs-sbar");
    btnSearch.addEventListener("click", function () {        
        searchBar.classList.toggle("visible");
        if (searchBar.classList.contains("visible")) {
            btnSearch.setAttribute("aria-label", "Cerrar barra de búsqueda");
        } else {
            btnSearch.setAttribute("aria-label", "Abrir barra de búsqueda");
        }
    });
});

let ejecutado = false;
$(document).on("keydown", "#search", function (e) {
    let search = $(this).val();     
    let btn = $("#sxs-sbar-buscar");
    if (search.length >= 3) {
        btn.removeClass("disabled").attr("aria-disabled", "false");        
    } else {        
        btn.addClass("disabled").attr("aria-disabled", "true");
    }
    if (e.key === "Enter") {
        e.preventDefault();     
        if (search.length >= 3 && !ejecutado) {
            ejecutado = true;
            $.ajax({
                url: "/productos",
                method: "GET",
                data: { search: search },
                success: function (res) {                    
                    window.location.href = "/productos?search=" + encodeURIComponent(search);
                }
            });
        } 
    }
});