$(document).ready(function () {

    AOS.init({
        duration: 400,
        easing: 'ease-in-out',
        once: true,
        offset: 60,
        disable: window.matchMedia('(prefers-reduced-motion: reduce)').matches
    });

    $lang = $('html').attr('lang');

    $('.related-services-carousel').owlCarousel({
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        dots: true,
        nav: false,
        responsive: {
            0: { items: 1 },
            992: { items: 2 },
            1100: { items: 3 }
        }
    });

    $('.related-services-carousel-en').owlCarousel({
        margin: 12,
        dots: true,
        nav: false,
        responsive: {
            0: { items: 1 },
            992: { items: 2 },
            1100: { items: 3 }
        }
    });

    $('.all-sectors__cards, .eservices-items').owlCarousel({
        autoplay: true,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        center: true,
        dots: false,
        nav: true,
        responsive: {
            0: {
                items: 1
            },
            992: {
                items: 2
            },
            1100: {
                items: 3
            }
        }
    });

    $('.sector-inner-slider').owlCarousel({
        autoplay: true,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        center: true,
        dots: true,
        nav: false,
        responsive: {
            0: {
                items: 1
            },
            992: {
                items: 2
            },
            1100: {
                items: 3
            }
        }
    });

    $('.eservices-items').owlCarousel({
        center: true,
        autoplay: true,
        items: 4,
        slideBy: 1,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        dots: false,
        nav: true,
        responsive: {
            0: {
                items: 1
            },
            992: {
                items: 2
            },
            1100: {
                items: 3
            }
        }

    });


    $('.all-sectors-carousel, .sector-inner-other-sectors').owlCarousel({
        autoplay: false,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        dots: false,
        nav: true,
        responsive: {
            0: {
                items: 1,
                nav: true,
                stagePadding: 50
            },
            768: {
                items: 2,
                nav: true,
                stagePadding: 50
            },
            1000: {
                items: 4,
                nav: true,
                loop: false
            }
        }

    });

    $('.e-services-carousel').owlCarousel({
        autoplay: false,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        dots: false,
        loop: true,
        nav: true,
        responsive: {
            0: {
                items: 1,
                nav: true,
                stagePadding: 50
            },
            768: {
                items: 2,
                nav: true,
                stagePadding: 50
            },
            1000: {
                items: 4,
                nav: true,
                loop: false
            }
        }
    });


    $('.hcis-logos-carousel').owlCarousel({
        autoplay: true,
        loop: true,
        dots: false,
        rtl: $lang == 'ar' ? true : false,
        margin: 12,
        nav: true,
        // nav: true,
        responsiveClass: true,
        responsive: {
            0: {
                items: 2,
            },
            768: {
                items: 4,
            },
            1300: {
                items: 10,
            }
        }

    });

    $('.news-cards').owlCarousel({
        // autoplaySpeed: 1000,
        // slideBy: 1,
        // center: true,
        margin: 12,
        rtl: $lang == 'ar' ? true : false,
        dots: true,
        nav: false,
        // loop: true,
        responsive: {
            0: {
                items: 1,
            },
            768: {
                items: 2,
            },
            1100: {
                items: 3,
            }
        }
    });

    owl = $('.home-banners-carousel').owlCarousel({
        autoplay: true,
        loop: true,
        rtl: $lang == 'ar' ? true : false,
        margin: 0,
        dots: false,
        nav: false,
        responsive: {
            0: { items: 1 },
            600: { items: 1 },
            1200: { items: 1 }
        }
    });
});


// Init AOS after setting attributes
//   AOS.init({
//     once: true,
//     duration: 600
//   });

// 1. Elements
const darkmodeBtn = document.getElementById('darkmode');

// 2. Load saved theme on page load
if (localStorage.getItem('theme') === 'dark') {
    document.body.classList.add('darkmode');
}

// 3. Toggle on click
darkmodeBtn.addEventListener('click', () => {
    document.body.classList.toggle('darkmode');

    // Save the state
    if (document.body.classList.contains('darkmode')) {
        localStorage.setItem('theme', 'dark');
    } else {
        localStorage.setItem('theme', 'light');
    }
});


const increaseBtn = document.getElementById('increase-fs');
const decreaseBtn = document.getElementById('decrease-fs');

let counter = 0;        // Current zoom steps
const max = 2;          // Max increase (was 6, now 2)
const min = -3;         // Max decrease

// Update root scale variable
function updateScale() {
    const scale = 1 + counter * 0.1;
    document.documentElement.style.setProperty('--scale', scale);
    // localStorage.setItem('fontScale', counter); // Save preference
}

// On page load - restore saved preference
// const savedCounter = localStorage.getItem('fontScale');
// if (savedCounter) {
//     counter = parseInt(savedCounter);
//     updateScale();
// }

increaseBtn.addEventListener('click', (e) => {
    e.preventDefault();
    if (counter < max) {
        counter++;
        updateScale();
    }
});

decreaseBtn.addEventListener('click', (e) => {
    e.preventDefault();
    if (counter > min) {
        counter--;
        updateScale();
    }
});


// Animate a single counter to its final value

const updateCounter = (element, current, target, step) => {
    current += step;
    if (current >= target) current = target;
    element.textContent = current.toLocaleString();

    if (current < target) {
        requestAnimationFrame(() => updateCounter(element, current, target, step));
    }
};

// Start the counter animation
const animateCounter = (element) => {
    const target = parseInt(element.textContent.replace(/,/g, ''), 10);
    const step = Math.ceil(target / 60);
    const current = 0;

    element.textContent = '0'; // Reset to 0 before animating
    requestAnimationFrame(() => updateCounter(element, current, target, step));
};

// Intersection observer callback
const handleIntersection = (entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            animateCounter(entry.target); // Animate on every view
        }
    });
};

// Setup observer for counters
const observeCounters = () => {
    const counters = document.querySelectorAll(".home-statistics__number");
    if (!counters.length) return;

    const options = { threshold: 0.3 };
    const observer = new IntersectionObserver(handleIntersection, options);

    counters.forEach(counter => observer.observe(counter));
};

// Run on DOM ready
document.addEventListener("DOMContentLoaded", observeCounters);

//map country click
document.querySelectorAll('.hcis-map path.hcis-branch').forEach(el => {
    el.addEventListener('click', function () {
        const targetId = this.dataset.city;
        const targetCity = document.getElementById(targetId);

        document.querySelectorAll('.hcis-map path.hcis-branch').forEach(e => {
            e.classList.remove('active-city');
        });

        document.querySelectorAll('.city-content').forEach(city => {
            city.classList.remove('active');
        });

        this.classList.toggle('active-city');

        if (targetCity) {
            document.querySelectorAll('.city-content').forEach(city => {
                city.classList.remove('active');
            });



            document.querySelectorAll(`[data-city="${targetId}"]`).forEach(cityMap => {

                cityMap.classList.add('active-city');
            });

            targetCity.classList.add('active');
        }
    });
});






// Home Banner Changing the color
$('.home-banners-carousel').on('changed.owl.carousel', function (event) {
    $('.owl-item').each(function () {

        // if $('.owl-item') 

    });
});


//   owl.on('changed.owl.carousel', function (e) {

//   });

$(document).ready(function () {


    $('.btn-digital-stamp-card').on('click', function () {
        $(this).parent().toggleClass("open");
        $(this).parent().next().slideToggle("fast");
    });

    // Set correct state on load
    $('.home-banners-carousel .owl-item').each(function () {

        $(this).find('.banner-default-img').css('opacity', '1');
        $(this).find('.banner-hover-img').css('opacity', '0');
    });

    // Handle after slide changes
    $('.home-banners-carousel').on('changed.owl.carousel refreshed.owl.carousel translated.owl.carousel', function (event) {
        setTimeout(function () {
            $(this).find('.banner-default-img').css('opacity', '1');
            $(this).find('.banner-hover-img').css('opacity', '0');
            $('.home-banners-carousel .owl-item').each(function () {
                const isActive = $(this).hasClass('active');
                $(this).find('.banner-default-img').css('opacity', isActive ? '0' : '1');
                $(this).find('.banner-hover-img').css('opacity', isActive ? '1' : '0');
            });
        }, 1500); // adjust if needed
    });
});



document.getElementById("year").innerHTML = new Date().getFullYear();



//coloring the current nav link

document.addEventListener('DOMContentLoaded', () => {
    const currentSlug = location.href.split('/').pop() || '/';

    // Clear any hardcoded active classes first — JS will re-apply the correct one
    document.querySelectorAll('.hcis-main-header-wrapper .nav-item.active').forEach(item => {
        item.classList.remove('active');
    });

    // Loop through all nav links
    document.querySelectorAll('.nav-item a, .dropdown-menu a').forEach(a => {
        const href = a.getAttribute('href') || '';

        // Skip external links — they are never the current page
        if (/^https?:\/\//i.test(href)) return;

        // Skip language-switcher links — same filename but opposite /ar/ or /en/ folder
        const currentLang = /\/en\//.test(location.pathname) ? 'en' : 'ar';
        const otherLang   = currentLang === 'en' ? 'ar' : 'en';
        if (href.includes('/' + otherLang + '/')) return;

        const linkSlug = href.split('/').pop() || '/';

        if (linkSlug === currentSlug) {
            // If inside offcanvas sub-menu, mark that specific sub-item
            const subItem = a.closest('.offcanvas-menu-list li');
            if (subItem) {
                subItem.classList.add('active');
            }
            // Always mark the parent nav-item too (section highlight)
            const navItem = a.closest('.nav-item');
            if (navItem) {
                navItem.classList.add('active');
                // Mark as current-page so it is never stripped by dropdown toggles
                navItem.classList.add('current-page');
            }
        }
    });
});



// Add this script  to JS file
document.addEventListener('DOMContentLoaded', function () {


    // const desktopMenuCol = document.querySelector('.desktop-menu-wrapper');
    // if (desktopMenuCol) {
    //     desktopMenuCol.classList.remove('col-7');
    //     desktopMenuCol.classList.add('col-8');
    // }

    const navBarSide = document.querySelector('.hcis-navbrand-side');
    // if (navBarSide) {
    //     navBarSide.classList.remove('col-2');
    //     navBarSide.classList.add('col-lg-2');
    // }

    // const headerSearchSide = document.querySelector('.header-search-lang-side');
    // if (headerSearchSide) {
    //     headerSearchSide.classList.remove('col-3');
    //     headerSearchSide.classList.add('col-lg-2');
    // }

    // const englishLink = document.querySelector('.header-search-lang-side a[href="../en/index_en.html"]');

    // if (englishLink) {
    //     englishLink.setAttribute('href', '../../pages/en/index-en.html');
    // }

    // document.querySelector('a[href="https://eservices.sais.gov.sa"]').parentElement.classList.add("d-none");
    // document.querySelector('li.nav-item.border-bottom-gray a[href="https://eservices.sais.gov.sa"]').parentElement.classList.add("d-none");
    // document.querySelector('a[href="https://eservices.sais.gov.sa/"]').parentElement.classList.add("d-none");

    document.querySelectorAll('.dga-contact-num #dga-certificate-h6 > a').forEach(link => {
        link.href = 'https://raqmi.dga.gov.sa/platforms/platforms/857b3ee7-be65-47f1-c735-08dddf0f5043/platform-license';
        link.textContent = '20250831889';
    });


    // document.querySelectorAll('.header-search-lang-side > a').forEach(search_lang => {
    //     if (search_lang) {
    //         search_lang.classList.add('d-none', 'd-xl-flex');
    //     }
    // });

    console.log('Navbar classes updated successfully');
});


$(document).ready(function () {

    const feedbackNoElements = document.querySelectorAll('.feedback-no');
    const feedbackYesElements = document.querySelectorAll('.feedback-yes');
    const closeButtons = document.querySelectorAll('.close-button'); // or '#close-button'
    const submitButtons = document.querySelectorAll('.feedback-submit-btn');
    const ratingsubmitButton = document.querySelector('.rating-submit-button');


    feedbackYesElements.forEach(feedbackYes => {
        feedbackYes.addEventListener('click', function (e) {
            e.preventDefault();
            feedbackYesElements.forEach(btn => btn.classList.add('active'));
            // Add active to all no buttons
            feedbackNoElements.forEach(btn => btn.classList.remove('active'));

            document.querySelectorAll('.page-question-default').forEach(el => {
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-no').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-yes').forEach(el => {
                el.classList.remove('d-none');
                el.classList.add('d-block');
            });
        });
    });

    feedbackNoElements.forEach(feedbackNo => {
        feedbackNo.addEventListener('click', function (e) {
            e.preventDefault();
            feedbackYesElements.forEach(btn => btn.classList.remove('active'));
            feedbackNoElements.forEach(btn => btn.classList.add('active'));
            document.querySelectorAll('.page-question-default').forEach(el => {
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-yes').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-no').forEach(el => {
                el.classList.remove('d-none');
                el.classList.add('d-block');
            });
        });
    });

    closeButtons.forEach(closeButton => {
        closeButton.addEventListener('click', function (e) {
            e.preventDefault();
            feedbackYesElements.forEach(btn => btn.classList.remove('active'));
            feedbackNoElements.forEach(btn => btn.classList.remove('active'));

            document.querySelectorAll('.page-question-default').forEach(el => {
                el.classList.remove('d-none');
                el.classList.add('d-block');
            });

            document.querySelectorAll('.page-question-yes').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-no').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });


        });
    });

    submitButtons.forEach(submitButton => {
        submitButton.addEventListener('click', function (e) {
            e.preventDefault();
            feedbackYesElements.forEach(btn => btn.classList.remove('active'));
            feedbackNoElements.forEach(btn => btn.classList.remove('active'));

            document.querySelectorAll('.page-question-default').forEach(el => {
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-yes').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-no').forEach(el => {
                el.classList.remove('d-block');
                el.classList.add('d-none');
            });

            document.querySelectorAll('.page-question-successfull').forEach(el => {
                el.classList.remove('d-none');
                el.classList.add('d-block');
            });


        });
    });
    if (ratingsubmitButton) {
        ratingsubmitButton.addEventListener('click', function (e) {
            e.preventDefault();

            const starsWrapper = document.querySelector('.stars-rating-wrapper');
            const successBox = document.querySelector('.rating-successfull');

            if (starsWrapper) {
                starsWrapper.classList.add('d-none');
            }

            if (successBox) {
                successBox.classList.remove('d-none');
                successBox.classList.add('d-block');
            }
        });
    }
});

document.querySelectorAll('a[href="#"]').forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
    });
});

// ── Back to Top ──────────────────────────────────────────────────────────────
const backToTopBtn = document.getElementById('backToTop');
if (backToTopBtn) {
    window.addEventListener('scroll', () => {
        backToTopBtn.classList.toggle('is-visible', window.scrollY > 400);
    });
    backToTopBtn.addEventListener('click', () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
}

// ── Sticky Header Shrink ─────────────────────────────────────────────────────
const mainHeader = document.querySelector('.hcis-main-header-wrapper');
if (mainHeader) {
    window.addEventListener('scroll', () => {
        mainHeader.classList.toggle('header-scrolled', window.scrollY > 80);
    });
}

// ── DGA Count-Up Animation (data-count attribute) ────────────────────────────
function dgaCountUp() {
    const counters = document.querySelectorAll('[data-count]');
    if (!counters.length) return;

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting && !entry.target.dataset.counted) {
                entry.target.dataset.counted = 'true';
                const target = parseInt(entry.target.dataset.count.replace(/,/g, ''));
                const duration = 1800;
                const step = target / (duration / 16);
                let current = 0;
                const timer = setInterval(() => {
                    current += step;
                    if (current >= target) {
                        current = target;
                        clearInterval(timer);
                    }
                    entry.target.textContent = Math.floor(current).toLocaleString('en-US');
                }, 16);
            }
        });
    }, { threshold: 0.5 });

    counters.forEach(el => observer.observe(el));
}
document.addEventListener('DOMContentLoaded', dgaCountUp);


//////Stars Rating Js //////
const stars = Array.from(document.querySelectorAll('.star'));
const rating = document.getElementById('rating');
if (rating) {
    let locked = 4.5;

    // Detect direction (LTR or RTL)
    const getDirection = () => {
        return window.getComputedStyle(rating).direction === 'rtl' ? 'rtl' : 'ltr';
    };

    const getValue = (star, e) => {
        const rect = star.querySelector('button').getBoundingClientRect();
        const x = e.clientX - rect.left;
        const starValue = +star.dataset.value;
        const isRTL = getDirection() === 'rtl';
        const isLeftHalf = x < rect.width / 2;

        // For RTL: right half = 0.5, left half = full
        // For LTR: left half = 0.5, right half = full
        if (isRTL) {
            return isLeftHalf ? starValue : starValue - 0.5;
        } else {
            return isLeftHalf ? starValue - 0.5 : starValue;
        }
    };

    const updateClipPath = () => {
        const isRTL = getDirection() === 'rtl';
        stars.forEach((star, index) => {
            const halfPath = star.querySelector('.half');
            const clipId = isRTL ? `clip-right-${index + 1}` : `clip-left-${index + 1}`;
            halfPath.setAttribute('clip-path', `url(#${clipId})`);
        });
    };

    const paint = (value) => {
        stars.forEach(star => {
            const val = +star.dataset.value;
            star.classList.remove('hover', 'half-hover', 'locked', 'half-locked');

            // Apply locked state (green)

            if (locked > 0) {
                if (val <= Math.floor(locked)) {
                    star.classList.add('locked');
                } else if (val - 0.5 === locked) {
                    star.classList.add('half-locked');
                }
            }

            // Apply hover state (gray with shadow) - show all stars up to hover value
            if (value > 0 && value !== locked) {
                const isLocked = locked > 0 && (val <= Math.floor(locked) || val - 0.5 === locked);

                if (!isLocked) {
                    // Show full stars before the hover value
                    if (val < value) {
                        star.classList.add('hover');
                    }
                    // Show half star at the hover value
                    else if (val - 0.5 === value) {
                        star.classList.add('half-hover');
                    }
                    // Show full star at the hover value (when value is whole number)
                    else if (val === value && Number.isInteger(value)) {
                        star.classList.add('hover');
                    }
                }
            }
        });
    };

    stars.forEach(star => {
        const btn = star.querySelector('button');

        btn.addEventListener('mousemove', (e) => {
            const value = getValue(star, e);
            paint(value);
        });

        btn.addEventListener('mouseleave', () => {
            paint(locked);
        });

        btn.addEventListener('click', (e) => {
            locked = getValue(star, e);
            paint(locked);
        });
    });

    if (rating) {
        rating.addEventListener('mouseleave', () => {
            paint(locked);
        });
    }


    // Update clip-path on direction change
    updateClipPath();

    // Watch for direction changes
    const observer = new MutationObserver(() => {
        updateClipPath();
        paint(locked);
    });
    observer.observe(rating, { attributes: true, attributeFilter: ['dir', 'style'] });
    observer.observe(document.documentElement, { attributes: true, attributeFilter: ['dir'] });

    paint(locked);

};


const emailLink = document.querySelector(
  'a[href="mailto:info@hcis.gov.sa"]'
);

if (emailLink) {
  emailLink.href = 'mailto:info@hcis.gov.sa';
  emailLink.textContent = 'info@hcis.gov.sa';
}


// ── DGA: Feedback Section — Full Layout (design.dga.gov.sa/templates/feedback) ──
// Matches DGA platformscode-react Feedback component exactly:
//
//  ┌────────────────────────────────────────────────────────────────────────┐
//  │ هل كانت هذه الصفحة مفيدة؟  [نعم] [لا]             [إغلاق ✕]         │
//  ├────────────────────────────────────────────────────────────────────────┤
//  │ [Heading + Checkboxes]          │  [تعليق *  textarea]                │
//  ├────────────────────────────────────────────────────────────────────────┤
//  │ أنا  ○ ذكر  ○ أنثى                                                    │
//  ├────────────────────────────────────────────────────────────────────────┤
//  │ لمزيد من المعلومات...  بيان المشاركة  و  قواعد الاشتراك   [إرسال]    │
//  └────────────────────────────────────────────────────────────────────────┘
document.addEventListener('DOMContentLoaded', function () {
    var lang        = document.documentElement.getAttribute('lang') || 'ar';
    var isAr        = lang === 'ar';
    var labelText   = isAr ? 'تعليق' : 'Feedback';
    var required    = '<span class="text-danger ms-1" aria-hidden="true">*</span>';
    var placeholder = isAr ? 'النص المُدخل' : 'Enter your feedback';

    document.querySelectorAll('.page-question-yes, .page-question-no').forEach(function (section, i) {
        if (section.querySelector('.dga-comments-box')) return;

        var genderRow  = section.querySelector('.d-flex.justify-content-start.gap-3.my-3');
        if (!genderRow) return;
        var contentCol = genderRow.parentElement; // col-12 my-3

        // ── Left column: move h6 heading + all checkboxes into it ─────────
        var leftCol = document.createElement('div');
        leftCol.className = 'dga-feedback-questions';

        var heading = contentCol.querySelector('h6');
        if (heading) leftCol.appendChild(heading);

        // Use `div.form-check.mb-2` — checkboxes are <div>s.
        // The submit button lives in <li class="form-check mb-2"> and must stay in the <ul>.
        Array.from(contentCol.querySelectorAll('div.form-check.mb-2')).forEach(function (el) {
            leftCol.appendChild(el);
        });

        // ── Right column: textarea (unlimited, scrolls on overflow) ───────
        var uid = 'feedback-comments-' + i;
        var box = document.createElement('div');
        box.className = 'dga-comments-box';
        box.innerHTML =
            '<label for="' + uid + '" class="form-label dga-text-black mb-2 fw-600">' +
                labelText + required +
            '</label>' +
            '<textarea id="' + uid + '" name="comments" class="form-control dga-textarea" ' +
                'placeholder="' + placeholder + '" required></textarea>';

        var rightCol = document.createElement('div');
        rightCol.className = 'dga-feedback-textarea-col';
        rightCol.appendChild(box);

        // ── Two-column wrapper ─────────────────────────────────────────────
        var twoCol = document.createElement('div');
        twoCol.className = 'dga-feedback-two-col';
        twoCol.appendChild(leftCol);
        twoCol.appendChild(rightCol);

        // Insert two-col wrapper before gender row; gender row stays below
        contentCol.insertBefore(twoCol, genderRow);

        // ── Restructure bottom row: [info text + links] LEFT | [إرسال] RIGHT ─
        // DGA template: "w-full flex justify-between md:items-center max-md:flex-col"
        var submitUl = contentCol.querySelector('ul.d-flex');
        if (submitUl) {
            // Extract info text (span inside first li)
            var infoTextEl = submitUl.querySelector('li > span');
            var infoText   = infoTextEl ? infoTextEl.textContent.trim() : '';

            // Extract links HTML from .feedback-btns li
            var linksLi   = submitUl.querySelector('li.feedback-btns');
            var linksHtml = linksLi ? linksLi.innerHTML : '';

            // Extract submit button
            var submitBtn = submitUl.querySelector('.feedback-submit-btn');

            // Build DGA bottom row
            var bottomRow = document.createElement('div');
            bottomRow.className = 'dga-feedback-bottom-row';

            // Left: info text + links as one paragraph (matches DGA <p>)
            var infoPara = document.createElement('p');
            infoPara.className = 'dga-feedback-info-text';
            infoPara.innerHTML = infoText + ' ' + linksHtml;
            bottomRow.appendChild(infoPara);

            // Right: submit button
            if (submitBtn) {
                bottomRow.appendChild(submitBtn);
            }

            submitUl.parentNode.replaceChild(bottomRow, submitUl);
        }

    });
});


// ── DGA: External Link Icon ──────────────────────────────────────────────────
// Appends the approved external-link icon to every link pointing outside the
// current site, EXCLUDING social-media icons and mailto/tel/anchor links.
document.addEventListener('DOMContentLoaded', function () {
    const externalIconSVG =
        '<svg class="external-link-icon" xmlns="http://www.w3.org/2000/svg" ' +
        'width="16" height="16" viewBox="0 0 17 17" fill="currentColor" ' +
        'aria-hidden="true" focusable="false">' +
        '<path d="M8.1241 16.25H8.125C11.8283 16.25 13.6867 16.25 14.9683 14.9683C16.18 13.755 ' +
        '16.2425 11.9541 16.2483 8.87581C16.2483 8.53081 15.9692 8.25 15.6242 8.25H15.6225C15.2775 ' +
        '8.25 14.9975 8.52919 14.9975 8.87419C14.9917 11.8667 14.9042 13.2641 14.0833 14.085C13.1675 ' +
        '15 11.4825 15 8.12419 15C4.76585 15 3.08 15 2.165 14.085C1.25 13.1691 1.25 11.4833 1.25 ' +
        '8.12502C1.25 4.76668 1.25002 3.08087 2.16585 2.16504C2.98585 1.34421 4.38331 1.25583 ' +
        '7.37581 1.25C7.72165 1.25 8 0.969186 8 0.624186C7.99917 0.279186 7.72 0 7.375 0H7.37333C4.29416 ' +
        '0.00583333 2.49332 0.0683235 1.28166 1.28166C0 2.56248 0 4.42164 0 8.12491C0 11.8282 0 ' +
        '13.6867 1.28166 14.9683C2.56248 16.25 4.42166 16.25 8.1241 16.25Z"/>' +
        '<path d="M6.89175 9.45009C7.01425 9.57093 7.17341 9.63173 7.33258 9.63173C7.49342 9.63173 ' +
        '7.6534 9.56926 7.7759 9.44676L14.9251 2.25592C14.9742 2.76092 15.0126 3.55843 14.9951 ' +
        '4.80426C14.9901 5.15009 15.2659 5.43337 15.6109 5.43837C15.9576 5.44671 16.2401 5.16757 ' +
        '16.2451 4.82257C16.2967 1.19825 15.9071 0.807065 15.6978 0.597002C15.4878 0.386968 ' +
        '15.0968 -0.00407002 11.4751 0.0475851C11.1301 0.0525851 10.8542 0.3367 10.8592 0.6817C10.8642 ' +
        '1.02337 11.1434 1.29759 11.4842 1.29759H11.4934C12.7442 1.28009 13.5425 1.31839 14.0459 ' +
        '1.36839L6.88922 8.5659C6.64589 8.8109 6.64675 9.20676 6.89175 9.45009Z"/>' +
        '</svg>';

    const currentHostname = window.location.hostname;

    document.querySelectorAll('a[href]').forEach(function (link) {
        const href = link.getAttribute('href');

        // Only process http/https links
        if (!href || !href.startsWith('http')) return;

        // Skip if icon already injected
        if (link.querySelector('.external-link-icon')) return;

        // Skip social-media icon wrappers
        if (link.classList.contains('footer-social__icon')) return;

        // Skip download buttons (btn class, download attribute, or file links)
        if (link.classList.contains('btn')) return;
        if (link.hasAttribute('download')) return;
        if (/\.(pdf|zip|docx?|xlsx?|pptx?|csv|txt|rar|7z)(\?.*)?$/i.test(href)) return;

        // Confirm link leads to a different hostname
        try {
            const url = new URL(href);
            if (url.hostname === currentHostname) return;
        } catch (e) {
            return;
        }

        // Insert icon at the end of the link
        link.insertAdjacentHTML('beforeend', externalIconSVG);
        link.setAttribute('target', '_blank');
        link.setAttribute('rel', 'noopener noreferrer');
    });
});


// ── DGA: Animated Bottom Line ─────────────────────────────────────────────────
// ::after cannot render on <textarea>/<input> (replaced elements).
// Wraps each DGA field in .dga-field-wrap at runtime (display:block — no visual
// change to layout) so CSS :focus-within::after draws the animated 2px black
// bottom line per DGA --form-field-border-pressed spec.
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.dga-textarea, .hcis-inputs, .search-input').forEach(function (el) {
        if (el.closest('.dga-field-wrap')) return;
        var wrap = document.createElement('div');
        wrap.className = 'dga-field-wrap';
        el.parentNode.insertBefore(wrap, el);
        wrap.appendChild(el);
    });
});


// ── DGA: Feedback two-column layout — questions | textarea ───────────────────
// h6 heading stays full-width above. Two columns beneath it:
// Left: checkboxes + gender row  |  Right: textarea
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.page-question-yes, .page-question-no').forEach(function (section) {
        if (section.querySelector('.dga-feedback-two-col')) return;

        // Find the col that actually contains the textarea (NOT the yes/no button col)
        var commentsBox = section.querySelector('.dga-comments-box');
        if (!commentsBox) return;
        var contentCol = commentsBox.closest('.col-12');
        if (!contentCol) return;

        // ── Left column: checkboxes + gender row (h6 stays above, full-width) ─
        var leftCol = document.createElement('div');
        leftCol.className = 'dga-feedback-questions';

        Array.from(contentCol.querySelectorAll('div.form-check.mb-2')).forEach(function (el) {
            leftCol.appendChild(el);
        });

        var genderRow = contentCol.querySelector('.d-flex.justify-content-start.gap-3.my-3');
        if (genderRow) leftCol.appendChild(genderRow);

        // ── Right column: existing .dga-comments-box ──────────────────────────
        var rightCol = document.createElement('div');
        rightCol.className = 'dga-feedback-textarea-col';

        rightCol.appendChild(commentsBox);

        // ── Two-column wrapper ────────────────────────────────────────────────
        var twoCol = document.createElement('div');
        twoCol.className = 'dga-feedback-two-col';
        twoCol.appendChild(leftCol);
        twoCol.appendChild(rightCol);

        // Insert before the submit <ul>
        var submitUl = contentCol.querySelector('ul.d-flex');
        contentCol.insertBefore(twoCol, submitUl || null);
    });
});
