/* ==========================================================================
   Become a Member — multi-step form logic + animated counters.
   No dependencies. Submission posts to a Google Form once wired (GOOGLE_FORM
   below); until then it logs the payload and still shows the success screen.
   ========================================================================== */
(function () {
    /* ---- animated counters ---- */
    var nums = [].slice.call(document.querySelectorAll('.mm-num-value[data-count]'));
    if (nums.length && 'IntersectionObserver' in window) {
        var io = new IntersectionObserver(function (entries) {
            entries.forEach(function (en) {
                if (!en.isIntersecting) return;
                io.unobserve(en.target);
                var el = en.target, target = parseInt(el.getAttribute('data-count'), 10) || 0, suf = el.getAttribute('data-suffix') || '';
                var start = null, dur = 1400;
                function tick(ts) {
                    if (!start) start = ts;
                    var p = Math.min((ts - start) / dur, 1);
                    el.textContent = Math.floor(p * target).toLocaleString() + (p === 1 ? suf : '');
                    if (p < 1) requestAnimationFrame(tick);
                }
                requestAnimationFrame(tick);
            });
        }, { threshold: 0.4 });
        nums.forEach(function (n) { io.observe(n); });
    }

    /* ---- floating "Become a member" CTA: show after the hero, hide near the form/footer ---- */
    (function () {
        var sticky = document.querySelector('.mm-sticky-cta');
        if (!sticky) return;
        var hero = document.querySelector('.mm-hero');
        var joinForm = document.getElementById('join-form');
        var finalCta = document.querySelector('.mm-final');
        function update() {
            var pastHero = hero ? (window.scrollY > hero.offsetHeight - 100) : (window.scrollY > 500);
            var nearTarget = [joinForm, finalCta].some(function (el) {
                if (!el) return false;
                var r = el.getBoundingClientRect();
                return r.top < window.innerHeight * 0.85 && r.bottom > 0;
            });
            if (pastHero && !nearTarget) { sticky.hidden = false; sticky.classList.remove('is-hiding'); }
            else if (!sticky.hidden) { sticky.classList.add('is-hiding'); }
        }
        window.addEventListener('scroll', update, { passive: true });
        window.addEventListener('resize', update);
        update();
    })();

    /* ---- multi-step form ---- */
    var form = document.querySelector('.ms-form');
    if (!form) return;
    var section = form.closest('.ms-section');
    var success = section.querySelector('.ms-success');
    var progress = form.querySelector('.ms-progress');
    var bar = form.querySelector('.ms-progress-bar');
    var ptext = form.querySelector('.ms-progress-text');
    var alertBox = form.querySelector('.ms-alert');
    var back = form.querySelector('.ms-back');
    var next = form.querySelector('.ms-next');
    var submit = form.querySelector('.ms-submit');
    var STEP = progress.getAttribute('data-step'), OF = progress.getAttribute('data-of');

    var steps = {};
    [].slice.call(form.querySelectorAll('.ms-step')).forEach(function (s) { steps[s.getAttribute('data-step')] = s; });
    var FLOWS = {
        student: ['path', 's-basic', 's-status', 's-intention', 's-interests', 's-city', 's-personal', 's-consent'],
        supporter: ['path', 'p-basic', 'p-support', 'p-message', 'p-consent']
    };
    var state = { path: null, order: ['path'], idx: 0 };

    // single-select radio groups (status, city)
    [].slice.call(form.querySelectorAll('.ms-radios')).forEach(function (group) {
        [].slice.call(group.querySelectorAll('.ms-radio')).forEach(function (btn) {
            btn.addEventListener('click', function () {
                [].slice.call(group.querySelectorAll('.ms-radio')).forEach(function (b) { b.classList.remove('is-selected'); });
                btn.classList.add('is-selected');
                var step = group.closest('.ms-step'), val = btn.getAttribute('data-value');
                [].slice.call(step.querySelectorAll('.ms-cond')).forEach(function (c) { c.hidden = c.getAttribute('data-when') !== val; });
                [].slice.call(step.querySelectorAll('.ms-msg')).forEach(function (m) {
                    var w = m.getAttribute('data-when');
                    m.hidden = !(w === '*any' || w === val);
                });
            });
        });
    });

    // multi-select chip groups (intention, interests, support)
    [].slice.call(form.querySelectorAll('.ms-multi')).forEach(function (group) {
        [].slice.call(group.querySelectorAll('.ms-chip')).forEach(function (chip) {
            chip.addEventListener('click', function () {
                chip.classList.toggle('is-selected');
                var step = group.closest('.ms-step');
                [].slice.call(step.querySelectorAll('.ms-msg')).forEach(function (m) {
                    var sel = group.querySelector('.ms-chip[data-value="' + m.getAttribute('data-when') + '"]');
                    if (sel) m.hidden = !sel.classList.contains('is-selected');
                });
            });
        });
    });

    // path choice
    [].slice.call(form.querySelectorAll('.ms-path')).forEach(function (p) {
        p.addEventListener('click', function () {
            state.path = p.getAttribute('data-path');
            [].slice.call(form.querySelectorAll('.ms-path')).forEach(function (x) { x.classList.remove('is-selected'); });
            p.classList.add('is-selected');
            state.order = FLOWS[state.path];
            state.idx = 1;
            progress.hidden = false;
            render();
        });
    });

    function render() {
        Object.keys(steps).forEach(function (k) { steps[k].hidden = (k !== state.order[state.idx]); });
        var total = state.order.length;
        bar.style.width = ((state.idx + 1) / total * 100) + '%';
        ptext.textContent = STEP + ' ' + (state.idx + 1) + ' ' + OF + ' ' + total;
        back.hidden = state.idx === 0;
        var last = state.idx === total - 1;
        var onPath = state.order[state.idx] === 'path';
        next.hidden = last || onPath;
        // never show submit on the path step (you advance by picking a card)
        submit.hidden = !last || onPath;
        if (last) submit.textContent = state.path === 'student' ? submit.getAttribute('data-student') : submit.getAttribute('data-supporter');
        alertBox.hidden = true;
    }

    function validate() {
        var step = steps[state.order[state.idx]], ok = true;
        [].slice.call(step.querySelectorAll('[data-required="1"]')).forEach(function (el) {
            if (el.closest('.ms-cond') && el.closest('.ms-cond').hidden) return;
            if (el.classList.contains('ms-radios')) { if (!el.querySelector('.ms-radio.is-selected')) ok = false; }
            else if (el.type === 'checkbox') { if (!el.checked) ok = false; }
            else if (el.type === 'email') { if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(el.value)) ok = false; }
            else { if (!el.value || !el.value.trim()) ok = false; }
        });
        return ok;
    }

    next.addEventListener('click', function () {
        if (!validate()) { alertBox.textContent = alertBox.getAttribute('data-required-msg') || alertBox.textContent; alertBox.hidden = false; return; }
        if (state.idx < state.order.length - 1) { state.idx++; render(); form.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
    });
    back.addEventListener('click', function () {
        if (state.idx > 0) { state.idx--; render(); }
    });

    function collect() {
        var d = { type: state.path };
        [].slice.call(form.querySelectorAll('[data-name]')).forEach(function (el) {
            if (el.closest('.ms-cond') && el.closest('.ms-cond').hidden) return;
            var name = el.getAttribute('data-name');
            if (el.classList.contains('ms-radios')) { var s = el.querySelector('.ms-radio.is-selected'); if (s) d[name] = s.getAttribute('data-value'); }
            else if (el.classList.contains('ms-multi')) { var sel = [].slice.call(el.querySelectorAll('.ms-chip.is-selected')).map(function (c) { return c.getAttribute('data-value'); }); if (sel.length) d[name] = sel.join(', '); }
            else if (el.type === 'checkbox') { d[name] = el.checked ? 'yes' : 'no'; }
            else if (el.value && el.value.trim()) { d[name] = el.value.trim(); }
        });
        return d;
    }

    // Google Form (membership). "city"/"membership" are derived; "summary" holds everything.
    var GOOGLE_FORM = {
        action: 'https://docs.google.com/forms/d/e/1FAIpQLSeaNQr05ba9TpJUfMHkj_FExcc4DVCGor0GZvV0PMMNWsW7lg/formResponse',
        fields: {
            type: 'entry.206257317',
            firstName: 'entry.1213078413',
            lastName: 'entry.845432178',
            email: 'entry.858040424',
            phone: 'entry.1768532046',
            city: 'entry.120922456',
            university: 'entry.1976875358',
            membership: 'entry.1099851320',
            consent: 'entry.867370083',
            summary: 'entry.627782554'
        }
    };
    function sendToForm(d) {
        if (!GOOGLE_FORM.action) { console.log('[MSOS membership] not wired yet, payload:', d); return; }
        var m = {
            type: d.type || '',
            firstName: d.firstName || '',
            lastName: d.lastName || '',
            email: d.email || '',
            phone: d.phone || '',
            city: d.connectCity || d.cityNow || '',
            university: d.university || '',
            membership: d.type === 'supporter' ? (d.support || '') : (d.intention || ''),
            consent: (d.consentContact === 'yes' && d.consentPrivacy === 'yes') ? 'yes' : 'no',
            summary: Object.keys(d).map(function (k) { return k + ': ' + d[k]; }).join('\n')
        };
        var params = new URLSearchParams();
        Object.keys(GOOGLE_FORM.fields).forEach(function (k) { if (m[k]) params.append(GOOGLE_FORM.fields[k], m[k]); });
        try { fetch(GOOGLE_FORM.action, { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: params.toString() }); } catch (e) { }
    }

    /* ---- soft anti-abuse: honeypot + localStorage cooldown/cap ----
       A static site cannot rate-limit by IP (no backend). These are client-side
       soft limits that stop casual flooding and bots; the Apps Script adds a
       server-side per-email dedupe and daily cap as the real safety net. */
    var hp = form.querySelector('.ms-hp input');
    var LS_KEY = 'msos_member_submits';
    var MIN_GAP_MS = 30 * 1000;         // at least 30s between submissions
    var WINDOW_MS = 24 * 60 * 60 * 1000; // rolling 24h window
    var MAX_IN_WINDOW = 3;               // max 3 submissions / 24h from this browser
    function recentSubmits() {
        var now = Date.now(), arr;
        try { arr = JSON.parse(localStorage.getItem(LS_KEY) || '[]'); } catch (e) { arr = []; }
        if (!Array.isArray(arr)) arr = [];
        return arr.filter(function (t) { return typeof t === 'number' && (now - t) < WINDOW_MS; });
    }
    function coolingDown() {
        var arr = recentSubmits(), now = Date.now();
        if (arr.length >= MAX_IN_WINDOW) return true;
        if (arr.length && (now - Math.max.apply(null, arr)) < MIN_GAP_MS) return true;
        return false;
    }
    function recordSubmit() {
        var arr = recentSubmits(); arr.push(Date.now());
        try { localStorage.setItem(LS_KEY, JSON.stringify(arr)); } catch (e) { }
    }
    function showAlert(kind) {
        var msg = alertBox.getAttribute(kind === 'cooldown' ? 'data-cooldown-msg' : 'data-required-msg');
        if (msg) alertBox.textContent = msg;
        alertBox.hidden = false;
    }

    submit.addEventListener('click', function () {
        // Bot trap: honeypot must stay empty. Silently succeed (no feedback for bots).
        if (hp && hp.value) { form.hidden = true; success.hidden = false; return; }
        if (!validate()) { showAlert('required'); return; }
        if (coolingDown()) { showAlert('cooldown'); return; }
        submit.disabled = true;
        var d = collect();
        sendToForm(d);
        recordSubmit();
        form.hidden = true;
        var t = success.querySelector('.ms-success-title'), p = success.querySelector('.ms-success-text');
        t.textContent = d.type === 'student' ? t.getAttribute('data-student-title') : t.getAttribute('data-supporter-title');
        p.textContent = d.type === 'student' ? p.getAttribute('data-student-text') : p.getAttribute('data-supporter-text');
        success.hidden = false;
        success.scrollIntoView({ behavior: 'smooth', block: 'center' });
    });

    // Locked single-flow mode: pages that only offer one path (e.g. the Support
    // page, supporter-only) set data-only-flow="supporter" to skip the path
    // chooser and start straight in that flow.
    var lockedFlow = form.getAttribute('data-only-flow');
    if (lockedFlow && FLOWS[lockedFlow]) {
        state.path = lockedFlow;
        state.order = FLOWS[lockedFlow].filter(function (s) { return s !== 'path'; });
        state.idx = 0;
        progress.hidden = false;
    }

    render();
})();
