import './bootstrap';
import Alpine from 'alpinejs';

if (!window.Alpine) {
    window.Alpine = Alpine;
    Alpine.start();
}

const prefersReducedMotion = () => window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function initGsap() {
    if (typeof window.gsap === 'undefined') return null;
    const { gsap } = window;
    if (typeof window.ScrollTrigger !== 'undefined') {
        gsap.registerPlugin(window.ScrollTrigger);
    }
    return gsap;
}

function revealHomepage() {
    const gsap = initGsap();
    const root = document.querySelector('[data-tx-home]');
    if (!root || !gsap || prefersReducedMotion()) return;
    if (root.dataset.txAnimated === 'true') return;
    root.dataset.txAnimated = 'true';

    gsap.set('.tx-split-line', { yPercent: 110, opacity: 0, rotate: 1.5 });
    gsap.set('.tx-reveal-fade', { y: 28, opacity: 0 });

    const heroTl = gsap.timeline({ defaults: { ease: 'expo.out' } });
    heroTl
        .to('.tx-split-line', {
            yPercent: 0,
            opacity: 1,
            rotate: 0,
            duration: 1.25,
            stagger: 0.08,
            delay: 0.1,
        })
        .to('.tx-reveal-fade', {
            y: 0,
            opacity: 1,
            duration: 0.85,
            stagger: 0.09,
        }, '-=0.65')
        .fromTo('.tx-hero-card', {
            y: 52,
            opacity: 0,
            rotate: -2,
        }, {
            y: 0,
            opacity: 1,
            rotate: 0,
            duration: 1.05,
            stagger: 0.08,
        }, '-=0.7');

    if (window.ScrollTrigger) {
        gsap.utils.toArray('[data-tx-section]').forEach((section) => {
            const cards = section.querySelectorAll('.tx-reveal-card, .tx-index__row');
            if (!cards.length) return;

            gsap.fromTo(cards, {
                y: 42,
                opacity: 0,
            }, {
                y: 0,
                opacity: 1,
                duration: 0.8,
                ease: 'power3.out',
                stagger: 0.08,
                scrollTrigger: {
                    trigger: section,
                    start: 'top 72%',
                    once: true,
                },
            });
        });

        gsap.to('.tx-hero__visual', {
            yPercent: -10,
            ease: 'none',
            scrollTrigger: {
                trigger: '.tx-hero',
                start: 'top top',
                end: 'bottom top',
                scrub: 0.7,
            },
        });

        const bridge = document.getElementById('bridge-svg-cms');
        if (bridge) {
            const len = bridge.getTotalLength ? bridge.getTotalLength() : 300;
            gsap.set(bridge, { strokeDasharray: len, strokeDashoffset: len });
            gsap.to(bridge, {
                strokeDashoffset: 0,
                ease: 'none',
                scrollTrigger: {
                    trigger: '.tx-global',
                    start: 'top 68%',
                    end: 'bottom 38%',
                    scrub: 1,
                },
            });
        }
    }
}

window.texoraRefreshScroll = () => {
    if (window.ScrollTrigger) window.ScrollTrigger.refresh();
};

document.addEventListener('DOMContentLoaded', revealHomepage);
window.addEventListener('texora:homepage-mounted', revealHomepage, { once: true });

function initTanujaTexoraHome() {
    const root = document.querySelector('[data-tj-home]');
    const gsap = initGsap();
    if (!root || !gsap || prefersReducedMotion()) return;
    if (root.dataset.tjAnimated === 'true') return;
    root.dataset.tjAnimated = 'true';

    gsap.set('.tj-hero-copy h1 span', { yPercent: 18, opacity: 0, filter: 'blur(8px)' });
    gsap.set('.tj-nav-shell, .tj-topline, .tj-floating-cta, .tj-mini-menu', { y: -18, opacity: 0 });

    gsap.timeline({ defaults: { ease: 'expo.out' } })
        .to('.tj-topline', { y: 0, opacity: 1, duration: 0.8 })
        .to('.tj-nav-shell', { y: 0, opacity: 1, duration: 0.9 }, '-=0.55')
        .to('.tj-hero-copy h1 span', {
            yPercent: 0,
            opacity: 1,
            filter: 'blur(0px)',
            duration: 1.15,
            stagger: 0.12,
        }, '-=0.3')
        .fromTo('.tj-hero-copy p', { y: 24, opacity: 0 }, { y: 0, opacity: 1, duration: 0.8 }, '-=0.55')
        .to('.tj-floating-cta, .tj-mini-menu', { y: 0, opacity: 1, duration: 0.75, stagger: 0.08 }, '-=0.45');

    if (!window.ScrollTrigger) return;

    gsap.utils.toArray('[data-tj-section]:not([data-sticky-services])').forEach((section) => {
        const targets = section.querySelectorAll('h2, .tj-blue-copy > p, .tj-blue-copy > span, .tj-blue-cards article, .tj-quotes article, .tj-spec-table div, .tj-blue-button, .tj-international-card, .tj-intro p, .tj-blog-card');
        gsap.fromTo(targets, {
            y: 54,
            opacity: 0,
            filter: 'blur(6px)',
        }, {
            y: 0,
            opacity: 1,
            filter: 'blur(0px)',
            duration: 0.85,
            ease: 'power3.out',
            stagger: 0.075,
            scrollTrigger: {
                trigger: section,
                start: 'top 72%',
                once: true,
            },
        });
    });

    initStickyServices(gsap);

    gsap.fromTo('.tj-blue-panel', {
        scale: 0.96,
        borderRadius: '18px',
    }, {
        scale: 1,
        borderRadius: '0px',
        ease: 'none',
        scrollTrigger: {
            trigger: '.tj-blue-panel',
            start: 'top bottom',
            end: 'top 18%',
            scrub: true,
        },
    });

    gsap.to('.tj-floating-cta, .tj-mini-menu', {
        y: 120,
        opacity: 0,
        ease: 'power2.out',
        scrollTrigger: {
            trigger: '.tj-blue-panel',
            start: 'top 82%',
            end: 'top 45%',
            scrub: true,
        },
    });
}

document.addEventListener('DOMContentLoaded', initTanujaTexoraHome);

function initStickyServices(gsap) {
    const section = document.querySelector('[data-sticky-services]');
    if (!section || !window.ScrollTrigger) return;
    if (window.matchMedia('(max-width: 980px)').matches) return;

    const slides = Array.from(section.querySelectorAll('[data-service-slide]'));
    const demos = Array.from(section.querySelectorAll('[data-service-demo]'));
    const tabs = Array.from(section.querySelectorAll('[data-service-tab]'));
    const fills = Array.from(section.querySelectorAll('.tj-demo-progress i'));
    const total = slides.length;
    let active = 0;

    if (!total) return;

    const setActive = (index, animate = true) => {
        const next = Math.max(0, Math.min(index, total - 1));
        if (next === active && animate) return;

        const previous = active;
        active = next;
        gsap.killTweensOf(slides);
        gsap.killTweensOf(demos);
        gsap.killTweensOf(fills);
        slides.forEach((slide, i) => {
            slide.classList.toggle('is-active', i === next);
            if (i === next) {
                gsap.set(slide, { zIndex: 2, pointerEvents: 'auto' });
                gsap.fromTo(slide, {
                    xPercent: next >= previous ? 14 : -14,
                    y: 14,
                    opacity: 0,
                    filter: 'blur(8px)',
                }, {
                    xPercent: 0,
                    y: 0,
                    opacity: 1,
                    filter: 'blur(0px)',
                    duration: animate ? 0.58 : 0,
                    ease: 'expo.out',
                });
            } else {
                gsap.set(slide, { xPercent: i < next ? -12 : 12, y: 10, opacity: 0, filter: 'blur(6px)', zIndex: 0, pointerEvents: 'none' });
            }
        });

        demos.forEach((demo, i) => {
            demo.classList.toggle('is-active', i === next);
            if (i === next) {
                gsap.set(demo, { zIndex: 2, pointerEvents: 'auto' });
                gsap.fromTo(demo, {
                    xPercent: next >= previous ? 8 : -8,
                    y: 28,
                    scale: 0.965,
                    opacity: 0,
                    filter: 'blur(8px)',
                }, {
                    xPercent: 0,
                    y: 0,
                    scale: 1,
                    opacity: 1,
                    filter: 'blur(0px)',
                    duration: animate ? 0.65 : 0,
                    ease: 'expo.out',
                });
                const bar = demo.querySelector('.tj-demo-window strong');
                if (bar) {
                    gsap.fromTo(bar, { scaleX: 0.18 }, { scaleX: 1, duration: animate ? 0.8 : 0, ease: 'power3.out' });
                }
            } else {
                gsap.set(demo, { xPercent: i < next ? -8 : 8, y: 18, scale: 0.985, opacity: 0, filter: 'blur(8px)', zIndex: 0, pointerEvents: 'none' });
            }
        });

        tabs.forEach((tab, i) => tab.classList.toggle('is-active', i === next));
    };

    setActive(0, false);

    const trigger = window.ScrollTrigger.create({
        trigger: section.querySelector('.tj-services-track'),
        start: 'top top',
        end: 'bottom bottom',
        scrub: true,
        onUpdate: (self) => {
            const progress = Math.min(self.progress, 0.9999);
            const index = Math.min(Math.floor(progress * total), total - 1);
            setActive(index);

            const localStart = index / total;
            const localEnd = (index + 1) / total;
            const localProgress = (progress - localStart) / (localEnd - localStart);
            fills.forEach((fill, i) => {
                gsap.set(fill, { scaleX: i < index ? 1 : i === index ? Math.max(0.08, localProgress) : 0.08 });
            });
        },
    });

    tabs.forEach((tab, i) => {
        tab.addEventListener('click', () => {
            const track = section.querySelector('.tj-services-track');
            if (!track) return;
            const maxScroll = track.offsetHeight - window.innerHeight;
            const y = track.offsetTop + (maxScroll * (i / Math.max(total - 1, 1)));
            window.scrollTo({ top: y, behavior: 'smooth' });
        });
    });

    [...slides, ...demos].forEach((item) => {
        item.addEventListener('click', (event) => {
            if (event.target.closest('a, button')) return;
            const href = item.dataset.href;
            if (href) window.location.href = href;
        });
        item.addEventListener('keydown', (event) => {
            if (event.key !== 'Enter') return;
            const href = item.dataset.href;
            if (href) window.location.href = href;
        });
    });

    window.addEventListener('beforeunload', () => trigger.kill(), { once: true });
}

function initPremiumPages() {
    const gsap = initGsap();
    const roots = document.querySelectorAll('[data-txp-page]');
    if (!roots.length || !gsap || prefersReducedMotion()) return;
    if (!window.ScrollTrigger) return;

    roots.forEach((root) => {
        if (root.dataset.txpAnimated === 'true') return;
        root.dataset.txpAnimated = 'true';

        gsap.fromTo(root.querySelectorAll('[data-txp-hero] .txp-reveal'), {
            y: 34,
            opacity: 0,
            filter: 'blur(8px)',
        }, {
            y: 0,
            opacity: 1,
            filter: 'blur(0px)',
            duration: 0.9,
            ease: 'expo.out',
            stagger: 0.08,
        });

        root.querySelectorAll('[data-txp-section]').forEach((section) => {
            const targets = section.querySelectorAll('.txp-card, .txp-row, .txp-reveal, .txp-visual');
            if (!targets.length) return;

            gsap.fromTo(targets, {
                y: 44,
                opacity: 0,
                filter: 'blur(6px)',
            }, {
                y: 0,
                opacity: 1,
                filter: 'blur(0px)',
                duration: 0.75,
                ease: 'power3.out',
                stagger: 0.06,
                scrollTrigger: {
                    trigger: section,
                    start: 'top 78%',
                    once: true,
                },
            });
        });
    });
}

document.addEventListener('DOMContentLoaded', initPremiumPages);

function initClickableCards() {
    document.querySelectorAll('[data-href]').forEach((card) => {
        if (card.dataset.clickableReady === 'true') return;
        card.dataset.clickableReady = 'true';

        card.addEventListener('click', (event) => {
            if (event.target.closest('a, button, input, select, textarea, label')) return;
            window.location.href = card.dataset.href;
        });

        card.addEventListener('keydown', (event) => {
            if (event.key !== 'Enter') return;
            window.location.href = card.dataset.href;
        });
    });
}

document.addEventListener('DOMContentLoaded', initClickableCards);
