/* =============================================================
   CandleCraft Academy — progressive enhancement v3
   ============================================================= */
(function () {
    'use strict';

    var root = document.documentElement;
    root.classList.add('js-ready');
    var prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    // ---------- Mobile drawer ----------
    (function () {
        var drawer = document.querySelector('[data-cc-drawer]');
        if (!drawer) return;
        var openers = document.querySelectorAll('[data-cc-drawer-open]');
        var closers = drawer.querySelectorAll('[data-cc-drawer-close]');

        function open() {
            drawer.classList.add('is-open');
            drawer.setAttribute('aria-hidden', 'false');
            document.body.style.overflow = 'hidden';
            openers.forEach(function (b) { b.setAttribute('aria-expanded', 'true'); });
        }
        function close() {
            drawer.classList.remove('is-open');
            drawer.setAttribute('aria-hidden', 'true');
            document.body.style.overflow = '';
            openers.forEach(function (b) { b.setAttribute('aria-expanded', 'false'); });
        }
        openers.forEach(function (b) { b.addEventListener('click', open); });
        closers.forEach(function (b) { b.addEventListener('click', close); });
        drawer.addEventListener('click', function (e) { if (e.target === drawer) close(); });
        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && drawer.classList.contains('is-open')) close();
        });
    })();

    // ---------- Pill-group (interest area, experience level, etc.) ----------
    document.querySelectorAll('[data-cc-pill]').forEach(function (pill) {
        pill.addEventListener('click', function () {
            var group = pill.closest('[data-cc-pill-group]') || pill.parentElement;
            if (!group) return;
            group.querySelectorAll('[data-cc-pill]').forEach(function (p) {
                var on = p === pill;
                p.classList.toggle('is-on', on);
                p.setAttribute('aria-pressed', on ? 'true' : 'false');
            });
            var scope = pill.closest('form') || document;
            var target = scope.querySelector('[data-cc-pill-value="' + (pill.dataset.target || '') + '"]') ||
                         group.querySelector('[data-cc-pill-value]') ||
                         scope.querySelector('[data-cc-pill-value]');
            if (target) target.value = pill.dataset.value || '';
        });
    });

    // ---------- Category rail: simple client-side filter for program cards ----------
    document.querySelectorAll('[data-cc-cat]').forEach(function (cat) {
        cat.addEventListener('click', function () {
            var rail = cat.closest('[data-cc-cat-rail]');
            if (!rail) return;
            rail.querySelectorAll('[data-cc-cat]').forEach(function (c) {
                c.classList.toggle('is-on', c === cat);
            });
            var target = cat.dataset.target;
            var value = cat.dataset.cat;
            var wrap = target ? document.querySelector(target) : null;
            if (!wrap) return;
            wrap.querySelectorAll('[data-cc-cat-item]').forEach(function (item) {
                var tags = (item.dataset.catTags || '').split(',');
                var show = value === 'all' || tags.indexOf(value) !== -1;
                item.style.display = show ? '' : 'none';
            });
        });
    });

    // ---------- FAQ accordion ----------
    document.querySelectorAll('[data-cc-faq]').forEach(function (q) {
        q.addEventListener('click', function () {
            var item = q.closest('.cc-faq__item');
            if (!item) return;
            item.classList.toggle('is-open');
            var expanded = item.classList.contains('is-open');
            q.setAttribute('aria-expanded', expanded ? 'true' : 'false');
        });
    });

    // ---------- Counters ----------
    (function () {
        var counters = document.querySelectorAll('[data-cc-counter]');
        if (!counters.length) return;
        if (prefersReduced || !('IntersectionObserver' in window)) {
            counters.forEach(function (el) { el.textContent = el.getAttribute('data-cc-counter-to') || el.textContent; });
            return;
        }
        counters.forEach(function (el) { el.textContent = '0'; });
        var io = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (!entry.isIntersecting) return;
                var el = entry.target;
                io.unobserve(el);
                var to = parseInt(el.getAttribute('data-cc-counter-to') || '0', 10);
                var start = performance.now();
                (function tick(t) {
                    var p = Math.min(1, (t - start) / 1400);
                    var eased = 1 - Math.pow(1 - p, 3);
                    el.textContent = String(Math.round(to * eased));
                    if (p < 1) requestAnimationFrame(tick);
                })(performance.now());
            });
        }, { threshold: 0.5 });
        counters.forEach(function (el) { io.observe(el); });
    })();

    // ---------- Scroll-reveal ----------
    (function () {
        var reveals = document.querySelectorAll('.cc-reveal');
        if (!reveals.length) return;
        if (!('IntersectionObserver' in window) || prefersReduced) {
            reveals.forEach(function (el) { el.classList.add('is-visible'); });
            return;
        }
        var io = new IntersectionObserver(function (entries) {
            entries.forEach(function (entry) {
                if (entry.isIntersecting) {
                    entry.target.classList.add('is-visible');
                    io.unobserve(entry.target);
                }
            });
        }, { threshold: 0.1, rootMargin: '0px 0px -5% 0px' });
        reveals.forEach(function (el) { io.observe(el); });
    })();

    // ---------- Floating enquire pill ----------
    (function () {
        var pill = document.querySelector('[data-cc-floating-enquire]');
        if (!pill) return;
        var hero = document.getElementById('hero');
        pill.hidden = false;
        if (hero && 'IntersectionObserver' in window) {
            var io = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    pill.classList.toggle('is-visible', !entry.isIntersecting);
                });
            }, { threshold: 0, rootMargin: '-80px 0px 0px 0px' });
            io.observe(hero);
        } else {
            pill.classList.add('is-visible');
        }
    })();

    // ---------- Booking: slot picker ----------
    document.querySelectorAll('[data-cc-slot-picker]').forEach(function (picker) {
        picker.addEventListener('click', function (e) {
            var btn = e.target.closest('[data-cc-slot]');
            if (!btn || btn.disabled) return;
            picker.querySelectorAll('[data-cc-slot]').forEach(function (b) { b.classList.toggle('is-on', b === btn); });
            var hidden = document.querySelector('[data-cc-slot-value]');
            if (hidden) hidden.value = btn.dataset.slotId || '';
            var submit = document.querySelector('[data-cc-booking-submit]');
            if (submit) submit.disabled = false;
        });
    });

    // ---------- AI Chatbot ----------
    (function () {
        var launch = document.querySelector('[data-cc-chat-launch]');
        var panel = document.querySelector('[data-cc-chat-panel]');
        var close = document.querySelector('[data-cc-chat-close]');
        var form = document.querySelector('[data-cc-chat-form]');
        var input = document.querySelector('[data-cc-chat-input]');
        var scroll = document.querySelector('[data-cc-chat-scroll]');
        if (!launch || !panel || !form || !input || !scroll) return;

        var history = []; // { role: 'user'|'assistant', content: string }
        var pending = false;

        function openPanel() {
            panel.classList.add('is-open');
            panel.setAttribute('aria-hidden', 'false');
            document.body.classList.add('cc-has-chat-open');
            setTimeout(function () { input.focus(); }, 80);
        }
        function closePanel() {
            panel.classList.remove('is-open');
            panel.setAttribute('aria-hidden', 'true');
            document.body.classList.remove('cc-has-chat-open');
        }
        launch.addEventListener('click', openPanel);
        close.addEventListener('click', closePanel);

        function addMsg(role, text) {
            var el = document.createElement('div');
            el.className = 'cc-chat-msg cc-chat-msg--' + (role === 'user' ? 'user' : (role === 'error' ? 'err' : 'bot'));
            el.textContent = text;
            scroll.appendChild(el);
            scroll.scrollTop = scroll.scrollHeight;
            return el;
        }
        function showTyping() {
            var el = document.createElement('div');
            el.className = 'cc-chat-typing';
            el.innerHTML = '<span></span><span></span><span></span>';
            el.setAttribute('data-typing', '1');
            scroll.appendChild(el);
            scroll.scrollTop = scroll.scrollHeight;
            return el;
        }

        function csrfToken() {
            var m = document.querySelector('meta[name="csrfToken"]');
            if (m) return m.getAttribute('content') || '';
            // CakePHP sets csrfToken cookie by default
            var parts = document.cookie.split('; ');
            for (var i = 0; i < parts.length; i++) {
                var kv = parts[i].split('=');
                if (kv[0] === 'csrfToken') return decodeURIComponent(kv[1] || '');
            }
            return '';
        }

        function send(text) {
            if (pending || !text.trim()) return;
            pending = true;
            input.disabled = true;
            addMsg('user', text);
            history.push({ role: 'user', content: text });
            var typing = showTyping();

            fetch('/api/chat', {
                method: 'POST',
                credentials: 'same-origin',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-Token': csrfToken(),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ messages: history })
            }).then(function (r) {
                return r.json().then(function (data) { return { ok: r.ok, data: data }; });
            }).then(function (res) {
                typing.remove();
                if (res.ok && res.data && res.data.reply) {
                    addMsg('bot', res.data.reply);
                    history.push({ role: 'assistant', content: res.data.reply });
                } else {
                    var msg = (res.data && res.data.error) || 'Sorry, something went wrong. Try again.';
                    addMsg('error', msg);
                    history.pop();
                }
            }).catch(function () {
                typing.remove();
                addMsg('error', 'Network error. Please try again.');
                history.pop();
            }).finally(function () {
                pending = false;
                input.disabled = false;
                input.focus();
            });
        }

        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var text = input.value;
            if (!text.trim()) return;
            input.value = '';
            autosize();
            send(text);
        });

        input.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                form.requestSubmit();
            }
        });

        function autosize() {
            input.style.height = 'auto';
            input.style.height = Math.min(100, input.scrollHeight) + 'px';
        }
        input.addEventListener('input', autosize);
    })();

})();
