(function () {
    const reveals = document.querySelectorAll('.reveal');
    const menuToggle = document.querySelector('.menu-toggle');
    const navMenu = document.querySelector('.nav');

    if (menuToggle && navMenu) {
        menuToggle.addEventListener('click', function () {
            const isOpen = navMenu.classList.toggle('is-open');
            menuToggle.classList.toggle('is-open', isOpen);
            menuToggle.setAttribute('aria-expanded', String(isOpen));
        });

        navMenu.querySelectorAll('a').forEach((link) => {
            link.addEventListener('click', function () {
                navMenu.classList.remove('is-open');
                menuToggle.classList.remove('is-open');
                menuToggle.setAttribute('aria-expanded', 'false');
            });
        });

        document.addEventListener('click', function (event) {
            if (!navMenu.classList.contains('is-open')) return;
            if (navMenu.contains(event.target) || menuToggle.contains(event.target)) return;

            navMenu.classList.remove('is-open');
            menuToggle.classList.remove('is-open');
            menuToggle.setAttribute('aria-expanded', 'false');
        });
    }

    if ('IntersectionObserver' in window) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('is-visible');
                    observer.unobserve(entry.target);
                }
            });
        }, { threshold: 0.16 });

        reveals.forEach((item) => observer.observe(item));
    } else {
        reveals.forEach((item) => item.classList.add('is-visible'));
    }

    const faqItems = document.querySelectorAll('.faq-item');
    faqItems.forEach((item) => {
        item.addEventListener('toggle', function () {
            if (!item.open) return;
            faqItems.forEach((other) => {
                if (other !== item) {
                    other.open = false;
                }
            });
        });
    });

    const form = document.getElementById('contactForm');
    if (!form) return;

    const submitButton = form.querySelector('button[type="submit"]');
    const defaultSubmitLabel = submitButton ? submitButton.textContent : 'إرسال الرسالة';
    const fallbackApi = 'https://app.tabeley.com/api';
    const configuredBase = window.TABELEY_API_BASE_URL;
    const originBase = `${window.location.origin}/api`;

    const candidates = [configuredBase, originBase, fallbackApi]
        .filter(Boolean)
        .map((url) => String(url).replace(/\/+$/, ''))
        .filter((url, idx, arr) => arr.indexOf(url) === idx);

    function getFieldValue(selector) {
        const field = form.querySelector(selector);
        return field ? field.value.trim() : '';
    }

    async function postFeedback(baseUrl, payload) {
        return fetch(`${baseUrl}/public/feedback`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Accept: 'application/json'
            },
            body: JSON.stringify(payload)
        });
    }

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        const name = getFieldValue('input[type="text"]');
        const email = getFieldValue('input[type="email"]');
        const message = getFieldValue('textarea');

        if (message.length < 5) {
            alert('يرجى كتابة رسالة أوضح قبل الإرسال.');
            return;
        }

        if (submitButton) {
            submitButton.disabled = true;
            submitButton.textContent = 'جارٍ الإرسال...';
        }

        const payload = { message, name, email };
        let sent = false;
        let lastError = null;

        for (const base of candidates) {
            try {
                const response = await postFeedback(base, payload);
                if (response.ok) {
                    sent = true;
                    break;
                }

                const body = await response.text();
                lastError = body || `HTTP ${response.status}`;
            } catch (err) {
                lastError = err;
            }
        }

        if (submitButton) {
            submitButton.disabled = false;
            submitButton.textContent = defaultSubmitLabel;
        }

        if (sent) {
            form.reset();
            alert('تم إرسال رسالتك بنجاح.');
            return;
        }

        console.error('Feedback send failed:', lastError);
        alert('تعذر إرسال الرسالة حالياً. حاول مرة أخرى لاحقاً.');
    });
})();
