/**
 * FITZONE GYM — Main JavaScript
 * Toast, Cart, Count-up, Filters, Upload Preview
 */

// ============================================================
// Global Base URL
// ============================================================
const baseUrl = document.querySelector('meta[name="base-url"]')?.content || '';

// ============================================================
// Toast Notification
// ============================================================
function showToast(message, type = 'success') {
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    const toast = document.createElement('div');
    toast.className = `toast ${type === 'error' ? 'error' : ''}`;
    toast.textContent = message;
    container.appendChild(toast);

    setTimeout(() => {
        toast.classList.add('removing');
        toast.addEventListener('animationend', () => toast.remove());
    }, 3000);
}

// ============================================================
// Cart Count Update
// ============================================================
function updateCartCount(count) {
    document.querySelectorAll('.cart-count').forEach(el => {
        el.textContent = count;
        if (count > 0) {
            el.style.display = 'inline-flex';
        } else {
            el.style.display = 'none';
        }
    });

    // Update floating pill
    const pill = document.querySelector('.cart-float');
    if (pill) {
        if (count > 0) {
            pill.style.display = 'block';
        } else {
            pill.style.display = 'none';
        }
    }
}

// ============================================================
// Add to Cart (AJAX)
// ============================================================
function addToCart(kelasId, namaKelas) {
    const btn = document.getElementById('add-btn-' + kelasId);
    if (btn) {
        btn.style.animation = 'scaleBtn 0.4s ease';
        btn.addEventListener('animationend', () => {
            btn.style.animation = '';
        }, { once: true });
    }

    const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';

    fetch(baseUrl + '/api/cart_add.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `kelas_id=${kelasId}&csrf_token=${csrf}`
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            showToast(`✓ ${namaKelas} ditambahkan ke keranjang`);
            updateCartCount(data.cart_count);
            updateFloatingPill(data.cart_count, data.cart_total);
        } else {
            showToast(data.message || 'Gagal menambahkan', 'error');
        }
    })
    .catch(() => showToast('Terjadi kesalahan jaringan', 'error'));
}

// ============================================================
// Remove from Cart (AJAX)
// ============================================================
function removeFromCart(kelasId, rowEl) {
    const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';

    fetch(baseUrl + '/api/cart_remove.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `kelas_id=${kelasId}&csrf_token=${csrf}`
    })
    .then(res => res.json())
    .then(data => {
        if (data.status === 'success') {
            if (rowEl) {
                rowEl.classList.add('row-slide-out');
                rowEl.addEventListener('animationend', () => {
                    rowEl.remove();
                    recalcTotal();
                    updateCartCount(data.cart_count);
                    checkEmpty();
                });
            }
            showToast('Item dihapus dari keranjang');
        } else {
            showToast(data.message || 'Gagal menghapus', 'error');
        }
    })
    .catch(() => showToast('Terjadi kesalahan jaringan', 'error'));
}

// ============================================================
// Recalculate Cart Total
// ============================================================
function recalcTotal() {
    let total = 0;
    document.querySelectorAll('.cart-item-price').forEach(el => {
        total += parseInt(el.dataset.harga || 0);
    });
    const totalEl = document.getElementById('cart-total');
    if (totalEl) totalEl.textContent = formatRupiah(total);
}

function checkEmpty() {
    const items = document.querySelectorAll('.cart-item');
    if (items.length === 0) {
        const container = document.getElementById('cart-list');
        if (container) {
            container.innerHTML = `
                <div class="empty-state">
                    <div class="emoji">🛒</div>
                    <p class="text-lg font-bold mb-2">Keranjang Kosong</p>
                    <p class="text-sm text-muted mb-4">Belum ada kelas yang dipilih</p>
                    <a href="${baseUrl}/member/katalog.php" class="btn-volt">Lihat Kelas</a>
                </div>
            `;
        }
    }
}

// ============================================================
// Update Floating Pill
// ============================================================
function updateFloatingPill(count, total) {
    let pill = document.querySelector('.cart-float');
    if (count > 0) {
        if (!pill) {
            pill = document.createElement('a');
            pill.className = 'cart-float';
            pill.href = baseUrl + '/member/keranjang.php';
            document.body.appendChild(pill);
        }
        pill.innerHTML = `🛒 ${count} kelas · ${formatRupiah(total)} →`;
        pill.style.display = 'block';
    } else if (pill) {
        pill.style.display = 'none';
    }
}

// ============================================================
// Format Rupiah
// ============================================================
function formatRupiah(num) {
    return 'Rp ' + num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
}

// ============================================================
// Count-Up Animation
// ============================================================
function countUp(el, target, duration = 1000) {
    let start = 0;
    const step = target / (duration / 16);
    const timer = setInterval(() => {
        start += step;
        if (start >= target) {
            start = target;
            clearInterval(timer);
        }
        el.textContent = Math.floor(start).toLocaleString('id-ID');
    }, 16);
}

// IntersectionObserver for count-up
document.addEventListener('DOMContentLoaded', () => {
    const countEls = document.querySelectorAll('[data-count]');
    if (countEls.length > 0) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const el = entry.target;
                    const target = parseInt(el.dataset.count);
                    countUp(el, target);
                    observer.unobserve(el);
                }
            });
        }, { threshold: 0.3 });

        countEls.forEach(el => observer.observe(el));
    }
});

// ============================================================
// Slot Bar Animation (DOMContentLoaded)
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.slot-fill').forEach(el => {
        const w = el.dataset.width || '0%';
        el.style.setProperty('--w', w);
    });
});

// ============================================================
// Filter Kelas (Client-side)
// ============================================================
function filterKelas() {
    const jenisFilter = document.getElementById('filter-jenis')?.value?.toLowerCase() || 'all';
    const intensitasFilter = document.querySelector('.filter-intensitas.active')?.dataset?.value?.toLowerCase() || 'all';

    document.querySelectorAll('.kelas-card').forEach(card => {
        const jenis = (card.dataset.jenis || '').toLowerCase();
        const intensitas = (card.dataset.intensitas || '').toLowerCase();

        const jenisMatch = jenisFilter === 'all' || jenis === jenisFilter;
        const intensitasMatch = intensitasFilter === 'all' || intensitas === intensitasFilter;

        card.style.display = (jenisMatch && intensitasMatch) ? '' : 'none';
    });
}

// Intensitas toggle buttons
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.filter-intensitas').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('.filter-intensitas').forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            filterKelas();
        });
    });
});

// ============================================================
// Upload File Preview
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
    const fileInput = document.getElementById('bukti-input');
    const preview = document.getElementById('upload-preview');

    if (fileInput && preview) {
        fileInput.addEventListener('change', function () {
            const file = this.files[0];
            if (!file) return;

            // Validate type
            const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
            if (!validTypes.includes(file.type)) {
                showToast('Format file harus JPG atau PNG', 'error');
                this.value = '';
                return;
            }

            // Validate size (max 2MB)
            if (file.size > 2 * 1024 * 1024) {
                showToast('Ukuran file maksimal 2MB', 'error');
                this.value = '';
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                preview.innerHTML = `<img src="${e.target.result}" alt="Preview bukti transfer">`;
                preview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        });
    }
});

// ============================================================
// Mobile Menu Toggle
// ============================================================
function toggleMobileMenu() {
    const menu = document.getElementById('mobile-menu');
    const b1 = document.getElementById('burger-1');
    const b2 = document.getElementById('burger-2');
    const b3 = document.getElementById('burger-3');

    menu.classList.toggle('hidden');

    if (!menu.classList.contains('hidden')) {
        b1.style.transform = 'rotate(45deg) translate(5px, 5px)';
        b2.style.opacity = '0';
        b3.style.transform = 'rotate(-45deg) translate(5px, -5px)';
    } else {
        b1.style.transform = '';
        b2.style.opacity = '';
        b3.style.transform = '';
    }
}

// ============================================================
// Star Rating Interactive
// ============================================================
function setRating(val) {
    document.getElementById('rating-value').value = val;
    document.querySelectorAll('.star-rating .star').forEach((star, i) => {
        star.classList.toggle('active', i < val);
    });
}

// ============================================================
// Flash message auto-hide
// ============================================================
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.flash-toast').forEach(el => {
        setTimeout(() => {
            el.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
            el.style.opacity = '0';
            el.style.transform = 'translateY(-10px)';
            setTimeout(() => el.remove(), 400);
        }, 4000);
    });
});
