/* ============================================================
   main.js – Iron.africa static page JavaScript
   ============================================================ */

/* ----------------------------------------------------------
   1. Closed Transactions Card Slider
   ---------------------------------------------------------- */
const cardWrapper = document.getElementById('cardWrapper');
let currentOffset = 0;

function getSlideWidth() {
    if (window.innerWidth <= 768) {
        return cardWrapper.clientWidth;
    } else {
        const card = cardWrapper.querySelector('.card');
        const cardStyle = window.getComputedStyle(card);
        return card.offsetWidth + parseInt(cardStyle.marginRight);
    }
}

function slideLeft() {
    const slideWidth = getSlideWidth();
    cardWrapper.style.transition = 'none';
    const lastCard = cardWrapper.lastElementChild;
    cardWrapper.prepend(lastCard);
    currentOffset += slideWidth;
    cardWrapper.style.transform = `translateX(-${currentOffset}px)`;
    setTimeout(() => {
        cardWrapper.style.transition = 'transform 0.5s ease-in-out';
        currentOffset -= slideWidth;
        cardWrapper.style.transform = `translateX(${currentOffset}px)`;
    }, 0);
}

function slideRight() {
    const slideWidth = getSlideWidth();
    currentOffset -= slideWidth;
    cardWrapper.style.transition = 'transform 0.5s ease-in-out';
    cardWrapper.style.transform = `translateX(${currentOffset}px)`;
    setTimeout(() => {
        cardWrapper.style.transition = 'none';
        const firstCard = cardWrapper.firstElementChild;
        cardWrapper.appendChild(firstCard);
        currentOffset += slideWidth;
        cardWrapper.style.transform = `translateX(${currentOffset}px)`;
    }, 500);
}

window.addEventListener('resize', () => {
    currentOffset = 0;
    cardWrapper.style.transition = 'none';
    cardWrapper.style.transform = `translateX(${currentOffset}px)`;
});

/* ----------------------------------------------------------
   2. Toast helper
   ---------------------------------------------------------- */
function showReturnToast(message) {
    var toast = document.createElement('div');
    toast.className = 'return-toast';
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(function () { toast.classList.add('show'); }, 10);
    setTimeout(function () { toast.classList.remove('show'); }, 4500);
    setTimeout(function () { toast.remove(); }, 5000);
}

/* ----------------------------------------------------------
   4. Navbar Scroll Effect
   ---------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {
    const navbar = document.querySelector('.navbar');
    
    function handleScroll() {
        if (window.scrollY > 50) {
            navbar.classList.add('navbar-scrolled');
        } else {
            navbar.classList.remove('navbar-scrolled');
        }
    }

    window.addEventListener('scroll', handleScroll);
    handleScroll(); // Check on load
});

/* ----------------------------------------------------------
   3. Lead Modal / Success Modal logic
   ---------------------------------------------------------- */
document.addEventListener('DOMContentLoaded', function () {

    var leadModalEl = document.getElementById('leadModal');
    var leadModal = new bootstrap.Modal(leadModalEl, { backdrop: true });

    var successModalEl = document.getElementById('successModal');
    var successModal = successModalEl ? new bootstrap.Modal(successModalEl, { backdrop: true }) : null;

    // Read status from URL query params (set by process_form.php after redirect)
    var urlParams = new URLSearchParams(window.location.search);
    var submissionStatus = urlParams.get('status') || '';
    var submissionMsg = urlParams.get('msg') || '';

    if (submissionStatus === 'success') {
        successModal && successModal.show();
    } else {
        // Auto-open lead modal on page load
        // leadModal.show();

        // Show error message if present
        if (submissionStatus === 'error' && submissionMsg) {
            showReturnToast(decodeURIComponent(submissionMsg));
        }
    }

    var form = document.getElementById('leadForm');
    var closeBtn = leadModalEl.querySelector('.lead-close');

    closeBtn.addEventListener('click', function () {
        form.reset();
    });

    leadModalEl.addEventListener('hidden.bs.modal', function () {
        form.reset();
    });

    // Go back link hides success modal and cleans the URL
    var goBack = document.getElementById('successGoBack');
    if (goBack && successModal) {
        goBack.addEventListener('click', function (e) {
            e.preventDefault();
            successModal.hide();
            history.replaceState({}, document.title, window.location.pathname);
        });
    }

    // Remind-me-later toast logic (show if timer has elapsed)
    var remindNext = parseInt(localStorage.getItem('iron_remind_next') || '0', 10);
    if (remindNext && Date.now() > remindNext) {
        showReturnToast('Welcome back! New insights are ready to explore.');
        localStorage.removeItem('iron_remind_next');
    }

    // Form validation before submit (allow normal POST to process_form.php)
    form.addEventListener('submit', function (e) {
        if (!form.reportValidity()) {
            e.preventDefault();
        }
        // Otherwise allow the POST to proceed naturally
    });

    /* ----------------------------------------------------------
       4. Job button hover effects
       ---------------------------------------------------------- */
    document.querySelectorAll('.job-btn').forEach(function (btn) {
        btn.addEventListener('mouseenter', function () {
            this.classList.add('hovered');
        });
        btn.addEventListener('mouseleave', function () {
            this.classList.remove('hovered');
        });
    });
});
