/**
 * ============================================================
 * YAIDEL HOME — HERO INTERACTIONS (IMAGE VERSION)
 * ============================================================
 * - Soft entrance reveal
 * - Background radial pointer response
 * - Gentle image tilt on desktop
 * - Professional typewriter effect for hero title span
 * - Reduced-motion compliant
 * ============================================================
 */

(function () {
    'use strict';
    
    
    
    
    if (window.lucide && typeof window.lucide.createIcons === 'function') {
    window.lucide.createIcons({
        attrs: {
            width: 18,
            height: 18,
            stroke: 0.9
        }
    });
}
    
    

    const section = document.querySelector('.yaidel-hero-section');
    if (!section) return;

    const media = section.querySelector('.yaidel-hero-media');
    const titleSpan = section.querySelector('.yaidel-hero-title span');
    const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // ---------------------------------------------------------
    // Typewriter effect for hero title span
    // ---------------------------------------------------------
    function typeHeroSpan() {
        if (!titleSpan) return;

        const finalText = (titleSpan.dataset.text || titleSpan.textContent || '').trim();
        if (!finalText) return;

        // Keep full text for SEO/accessibility while animating visually
        titleSpan.setAttribute('aria-label', finalText);

        // Reduced motion: show full text instantly
        if (reducedMotion) {
            titleSpan.textContent = finalText;
            return;
        }

        // Reset and animate
        titleSpan.textContent = '';

        const chars = Array.from(finalText);
        let i = 0;

        // Professional speed: balanced and readable
        const baseDelay = 42; // typing speed
        const punctuationDelay = 130; // longer pause at punctuation

        function tick() {
            if (i >= chars.length) {
                titleSpan.classList.add('yaidel-typed-done');
                return;
            }

            const ch = chars[i];
            titleSpan.textContent += ch;
            i += 1;

            let nextDelay = baseDelay;

            // Slightly slower around punctuation for natural rhythm
            if (/[.,!?]/.test(ch)) {
                nextDelay = punctuationDelay;
            } else if (ch === ' ') {
                nextDelay = 24;
            }

            window.setTimeout(tick, nextDelay);
        }

        // Start shortly after reveal begins
        window.setTimeout(tick, 280);
    }

    // ---------------------------------------------------------
    // Entrance reveal
    // ---------------------------------------------------------
    const targets = section.querySelectorAll(
        '.yaidel-hero-eyebrow, .yaidel-hero-title, .yaidel-hero-description, .yaidel-hero-feature-grid, .yaidel-hero-actions, .yaidel-hero-trust, .yaidel-hero-media'
    );

    targets.forEach(function (el, i) {
        el.style.opacity = '0';
        el.style.transform = 'translateY(10px)';
        el.style.transition = 'opacity 460ms ease, transform 460ms ease';

        window.setTimeout(function () {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, 50 + (i * 65));
    });

    // Start typing effect
    typeHeroSpan();

    if (reducedMotion) return;

    // ---------------------------------------------------------
    // Section radial follow
    // ---------------------------------------------------------
    let spotRaf = null;
    let targetX = 72;
    let targetY = 24;
    let currentX = 72;
    let currentY = 24;

    function animateSpot() {
        currentX += (targetX - currentX) * 0.1;
        currentY += (targetY - currentY) * 0.1;

        section.style.setProperty('--hero-spot-x', currentX.toFixed(2) + '%');
        section.style.setProperty('--hero-spot-y', currentY.toFixed(2) + '%');

        if (Math.abs(targetX - currentX) > 0.05 || Math.abs(targetY - currentY) > 0.05) {
            spotRaf = requestAnimationFrame(animateSpot);
        } else {
            spotRaf = null;
        }
    }

    function queueSpot() {
        if (spotRaf !== null) return;
        spotRaf = requestAnimationFrame(animateSpot);
    }

    section.addEventListener('pointermove', function (event) {
        const rect = section.getBoundingClientRect();
        if (!rect.width || !rect.height) return;

        targetX = ((event.clientX - rect.left) / rect.width) * 100;
        targetY = ((event.clientY - rect.top) / rect.height) * 100;
        queueSpot();
    });

    section.addEventListener('pointerleave', function () {
        targetX = 72;
        targetY = 24;
        queueSpot();
    });

    // ---------------------------------------------------------
    // Media tilt (desktop only)
    // ---------------------------------------------------------
    if (!media) return;
    if (window.innerWidth <= 1200) return;

    let tiltRaf = null;
    let tx = -6;
    let ty = 1.5;
    let cx = -6;
    let cy = 1.5;

    function animateTilt() {
        cx += (tx - cx) * 0.12;
        cy += (ty - cy) * 0.12;

        media.style.transform =
            'perspective(1400px) rotateY(' + cx.toFixed(2) + 'deg) rotateX(' + cy.toFixed(2) + 'deg)';

        if (Math.abs(tx - cx) > 0.03 || Math.abs(ty - cy) > 0.03) {
            tiltRaf = requestAnimationFrame(animateTilt);
        } else {
            tiltRaf = null;
        }
    }

    function queueTilt() {
        if (tiltRaf !== null) return;
        tiltRaf = requestAnimationFrame(animateTilt);
    }

    media.addEventListener('pointermove', function (event) {
        const rect = media.getBoundingClientRect();
        const px = (event.clientX - rect.left) / rect.width;
        const py = (event.clientY - rect.top) / rect.height;

        tx = (px - 0.5) * 7;
        ty = (0.5 - py) * 4;
        queueTilt();
    });

    media.addEventListener('pointerleave', function () {
        tx = -6;
        ty = 1.5;
        queueTilt();
    });
})();


/**
 * ============================================================
 * YAIDEL HOME — FEATURES INTERACTIONS (REFINED)
 * ============================================================
 */

(function () {
    'use strict';

    // Lucide init
    function initLucide() {
        if (window.lucide && typeof window.lucide.createIcons === 'function') {
            window.lucide.createIcons({
                attrs: { width: 34, height: 34, stroke: 1.55 }
            });
            return true;
        }
        return false;
    }

    if (!initLucide()) {
        window.setTimeout(initLucide, 80);
    }

    const section = document.querySelector('.yaidel-features-section');
    if (!section) return;

    const cards = Array.from(section.querySelectorAll('.yaidel-feature-card'));
    if (!cards.length) return;

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

    // Reveal
    function revealAll() {
        cards.forEach((card) => card.classList.add('yaidel-feature-visible'));
    }

    if (prefersReducedMotion || !('IntersectionObserver' in window)) {
        revealAll();
    } else {
        const io = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (!entry.isIntersecting) return;

                const card = entry.target;
                const idx = cards.indexOf(card);

                window.setTimeout(() => {
                    card.classList.add('yaidel-feature-visible');
                }, idx * 50);

                io.unobserve(card);
            });
        }, {
            threshold: 0.14,
            rootMargin: '0px 0px -38px 0px'
        });

        cards.forEach((card) => io.observe(card));
    }

    if (prefersReducedMotion) return;

    // Spotlight follow
    let rafId = null;
    let targetX = 52;
    let targetY = 24;
    let currentX = 52;
    let currentY = 24;

    function animateSpot() {
        currentX += (targetX - currentX) * 0.10;
        currentY += (targetY - currentY) * 0.10;

        section.style.setProperty('--spot-x', currentX.toFixed(2) + '%');
        section.style.setProperty('--spot-y', currentY.toFixed(2) + '%');

        if (Math.abs(targetX - currentX) > 0.05 || Math.abs(targetY - currentY) > 0.05) {
            rafId = window.requestAnimationFrame(animateSpot);
        } else {
            rafId = null;
        }
    }

    function queueSpot() {
        if (rafId !== null) return;
        rafId = window.requestAnimationFrame(animateSpot);
    }

    section.addEventListener('pointermove', (event) => {
        const rect = section.getBoundingClientRect();
        if (!rect.width || !rect.height) return;

        const x = ((event.clientX - rect.left) / rect.width) * 100;
        const y = ((event.clientY - rect.top) / rect.height) * 100;

        targetX = Math.max(0, Math.min(100, x));
        targetY = Math.max(0, Math.min(100, y));
        queueSpot();
    });

    section.addEventListener('pointerleave', () => {
        targetX = 52;
        targetY = 24;
        queueSpot();
    });
})();







/**
 * ============================================================
 * YAIDEL WEBSITE PORTFOLIO
 * ============================================================
 */

document.addEventListener('DOMContentLoaded', () => {

    const filterButtons = document.querySelectorAll('.portfolio-filter-btn');
    const portfolioCards = document.querySelectorAll('.portfolio-card');

    if (!filterButtons.length || !portfolioCards.length) {
        return;
    }

    /**
     * --------------------------------------------
     * Filter Portfolio
     * --------------------------------------------
     */
    function filterPortfolio(category) {

        portfolioCards.forEach(card => {

            const cardCategory = card.dataset.category;

            if (category === 'all' || cardCategory === category) {

                card.style.display = '';

                requestAnimationFrame(() => {
                    card.classList.remove('hidden');
                });

            } else {

                card.classList.add('hidden');

                setTimeout(() => {
                    if (card.classList.contains('hidden')) {
                        card.style.display = 'none';
                    }
                }, 300);

            }

        });

    }

    /**
     * --------------------------------------------
     * Update Active Button
     * --------------------------------------------
     */
    function setActiveButton(button) {

        filterButtons.forEach(btn => {
            btn.classList.remove('active');
            btn.setAttribute('aria-pressed', 'false');
        });

        button.classList.add('active');
        button.setAttribute('aria-pressed', 'true');

    }

    /**
     * --------------------------------------------
     * Click Events
     * --------------------------------------------
     */
    filterButtons.forEach(button => {

        button.addEventListener('click', () => {

            const category = button.dataset.filter;

            setActiveButton(button);
            filterPortfolio(category);

            history.replaceState(
                null,
                '',
                '#' + category
            );

        });

    });

    /**
     * --------------------------------------------
     * Keyboard Navigation
     * --------------------------------------------
     */
    filterButtons.forEach(button => {

        button.addEventListener('keydown', e => {

            if (e.key === 'Enter' || e.key === ' ') {

                e.preventDefault();
                button.click();

            }

        });

    });

    /**
     * --------------------------------------------
     * Initial Filter From URL Hash
     * --------------------------------------------
     */
    const hash = window.location.hash.replace('#', '');

    if (hash) {

        const matchingButton = document.querySelector(
            `.portfolio-filter-btn[data-filter="${hash}"]`
        );

        if (matchingButton) {

            matchingButton.click();
            return;

        }

    }

    /**
     * --------------------------------------------
     * Default
     * --------------------------------------------
     */
    filterButtons[0].click();

});







/**
 * ============================================================
 * Website Development Process Animation
 * ============================================================
 */

document.addEventListener("DOMContentLoaded", () => {

    const timeline = document.querySelector(".process-timeline");

    if (!timeline) return;

    const cards = [...timeline.querySelectorAll(".process-card")];
    const progressBar = timeline.querySelector(".process-line-progress");

    /* ========================================================
       Reveal Cards
    ======================================================== */

    const observer = new IntersectionObserver((entries) => {

        entries.forEach(entry => {

            if (entry.isIntersecting) {

                entry.target.classList.add("active");

            }

        });

    }, {

        threshold: 0.35

    });

    cards.forEach(card => observer.observe(card));

    /* ========================================================
       Timeline Progress
    ======================================================== */

    function updateTimelineProgress() {

        const rect = timeline.getBoundingClientRect();

        const viewportHeight = window.innerHeight;

        /*
            0% when timeline reaches lower part of screen.
            100% when timeline has completely passed.
        */

        const start = viewportHeight * 0.15;
        const end = rect.height + viewportHeight * 0.25;

        let progress = (start - rect.top) / end;

        progress = Math.max(0, Math.min(progress, 1));

        progressBar.style.height = `${progress * 100}%`;

    }

    updateTimelineProgress();

    window.addEventListener("scroll", updateTimelineProgress, {
        passive: true
    });

    window.addEventListener("resize", updateTimelineProgress);

});




/**
 * ============================================================
 * YAIDEL WEBSITE ANIMATIONS
 * ============================================================
 */

document.addEventListener("DOMContentLoaded", () => {

    /* ========================================================
       PROCESS TIMELINE
    ======================================================== */

    (() => {

        const timeline = document.querySelector(".process-timeline");

        if (!timeline) return;

        const cards = timeline.querySelectorAll(".process-card");
        const progress = timeline.querySelector(".process-line-progress");

        const observer = new IntersectionObserver((entries) => {

            entries.forEach(entry => {

                if (!entry.isIntersecting) return;

                const card = entry.target;

                card.classList.add("active");

                const step = card.closest(".process-step");

                step?.querySelector(".process-node")
                    ?.classList.add("active");

            });

        }, {
            threshold: .35
        });

        cards.forEach(card => observer.observe(card));

        function updateTimeline() {

            const rect = timeline.getBoundingClientRect();

            const viewport = window.innerHeight;

            const total = rect.height + viewport;

            let percent = (viewport - rect.top) / total;

            percent = Math.max(0, Math.min(percent, 1));

            progress.style.height = `${percent * 100}%`;

        }

        updateTimeline();

        window.addEventListener("scroll", updateTimeline, {
            passive: true
        });

        window.addEventListener("resize", updateTimeline);

    })();


    /* ========================================================
       TECHNOLOGY GRID
    ======================================================== */

    (() => {

        const cards = document.querySelectorAll(".technology-grid article");

        if (!cards.length) return;

        const observer = new IntersectionObserver((entries) => {

            entries.forEach(entry => {

                if (!entry.isIntersecting) return;

                cards.forEach((card, index) => {

                    setTimeout(() => {

                        card.classList.add("show");

                    }, index * 90);

                });

                observer.disconnect();

            });

        }, {
            threshold: .2
        });

        observer.observe(cards[0]);

    })();


    /* ========================================================
       PERFORMANCE COUNTERS
    ======================================================== */

    (() => {

        const metrics = document.querySelectorAll(".performance-metrics strong");

        if (!metrics.length) return;

        let started = false;

        const observer = new IntersectionObserver((entries) => {

            entries.forEach(entry => {

                if (!entry.isIntersecting || started) return;

                started = true;

                metrics.forEach(counter => {

                    const text = counter.textContent.trim();

                    if (text.includes("95")) {

                        animate(counter, 95, "", "+");

                    }

                    else if (text.includes("2")) {

                        animateDecimal(counter, 5, 2, "<", "s");

                    }

                    else if (text.includes("A")) {

                        animateGrade(counter);

                    }

                });

            });

        }, {
            threshold: .35
        });

        observer.observe(document.querySelector(".website-performance"));

    })();


    /* ========================================================
       PERFORMANCE PARALLAX
    ======================================================== */

    (() => {

        const card = document.querySelector(".performance-card");

        if (!card) return;

        window.addEventListener("mousemove", e => {

            const rect = card.getBoundingClientRect();

            const x = (e.clientX - rect.left) / rect.width;

            const y = (e.clientY - rect.top) / rect.height;

            card.style.backgroundPosition =
                `${50 + x * 5}% ${50 + y * 5}%`;

        });

    })();


    /* ========================================================
       HELPERS
    ======================================================== */

    function animate(el, target, prefix = "", suffix = "") {

        let start = 0;

        const duration = 1400;

        const startTime = performance.now();

        function frame(now) {

            const progress = Math.min((now - startTime) / duration, 1);

            const value = Math.floor(progress * target);

            el.textContent = prefix + value + suffix;

            if (progress < 1) {

                requestAnimationFrame(frame);

            }

        }

        requestAnimationFrame(frame);

    }

    function animateDecimal(el, from, to, prefix = "", suffix = "") {

        const duration = 1400;

        const startTime = performance.now();

        function frame(now) {

            const progress = Math.min((now - startTime) / duration, 1);

            const value = from + ((to - from) * progress);

            el.textContent =
                prefix +
                value.toFixed(1).replace(".0", "") +
                suffix;

            if (progress < 1) {

                requestAnimationFrame(frame);

            }

        }

        requestAnimationFrame(frame);

    }

    function animateGrade(el) {

        const grades = [

            "F",
            "D",
            "C",
            "B",
            "A",
            "A+"

        ];

        let i = 0;

        const timer = setInterval(() => {

            el.textContent = grades[i];

            i++;

            if (i >= grades.length) {

                clearInterval(timer);

            }

        }, 160);

    }

});







/* ==========================================================
   ADD-ONS REVEAL
========================================================== */

(() => {

    const cards = document.querySelectorAll(".addons-grid article");

    if (!cards.length) return;

    const observer = new IntersectionObserver((entries) => {

        entries.forEach(entry => {

            if (!entry.isIntersecting) return;

            cards.forEach((card, index) => {

                setTimeout(() => {

                    card.classList.add("show");

                }, index * 80);

            });

            observer.disconnect();

        });

    }, {

        threshold:0.2

    });

    observer.observe(cards[0]);

})();











/* ==========================================================
   COMPARISON REVEAL
========================================================== */

(() => {

    const table = document.querySelector(".comparison-card");

    if(!table) return;

    const observer = new IntersectionObserver(entries=>{

        entries.forEach(entry=>{

            if(entry.isIntersecting){

                table.classList.add("show");

            }

        });

    },{

        threshold:.06

    });

    observer.observe(table);

})();











/* ==========================================================
   TESTIMONIAL REVEAL
========================================================== */

(() => {

    const cards = document.querySelectorAll(".testimonial-card");

    if (!cards.length) return;

    const observer = new IntersectionObserver(entries => {

        entries.forEach(entry => {

            if (!entry.isIntersecting) return;

            cards.forEach((card,index)=>{

                setTimeout(()=>{

                    card.classList.add("show");

                },index*180);

            });

            observer.disconnect();

        });

    },{

        threshold:.25

    });

    observer.observe(cards[0]);

})();






/* ==========================================================
   FAQ ACCORDION
========================================================== */

(() => {

    const items = document.querySelectorAll(".faq-item");

    items.forEach(item=>{

        const button = item.querySelector(".faq-question");

        button.addEventListener("click",()=>{

            const active = item.classList.contains("active");

            items.forEach(i=>i.classList.remove("active"));

            if(!active){

                item.classList.add("active");

            }

        });

    });

})();




/* ==========================================================
   FAQ REVEAL
========================================================== */

(() => {

    const items = document.querySelectorAll(".faq-item");

    if(!items.length) return;

    const observer = new IntersectionObserver(entries=>{

        entries.forEach(entry=>{

            if(!entry.isIntersecting) return;

            items.forEach((item,index)=>{

                setTimeout(()=>{

                    item.classList.add("show");

                },index*120);

            });

            observer.disconnect();

        });

    },{

        threshold:.2

    });

    observer.observe(items[0]);

})();