// --- DATA MOCKUP ---
const MOCK_SEMINARS = [
    {
        id: 1,
        title: "Strategi Implementasi Kurikulum Merdeka",
        image: "https://images.unsplash.com/photo-1544531586-fde5298cdd40?auto=format&fit=crop&q=80&w=800",
        date: "2024-05-20",
        time: "09:00 - 12:00 WIB",
        speaker: "Dr. Budi Santoso, M.Pd",
        priceNonMember: 150000,
        priceMember: 100000,
        type: "Webinar Zoom",
        status: "Open",
        description: "Membahas tuntas strategi penerapan kurikulum merdeka di tingkat sekolah dasar dan menengah dengan pendekatan praktis."
    },
    {
        id: 2,
        title: "Workshop Penulisan Karya Ilmiah Guru",
        image: "https://images.unsplash.com/photo-1517048676732-d65bc937f952?auto=format&fit=crop&q=80&w=800",
        date: "2024-06-10",
        time: "08:00 - 15:00 WIB",
        speaker: "Prof. Siti Aminah",
        priceNonMember: 250000,
        priceMember: 175000,
        type: "Hybrid (Offline & Zoom)",
        status: "Open",
        description: "Pelatihan intensif penulisan jurnal ilmiah untuk kenaikan pangkat guru."
    },
    {
        id: 3,
        title: "Manajemen Kelas di Era Digital",
        image: "https://images.unsplash.com/photo-1531403009284-440f080d1e12?auto=format&fit=crop&q=80&w=800",
        date: "2024-04-15",
        time: "13:00 - 15:00 WIB",
        speaker: "Rina Wijaya, S.Psi",
        priceNonMember: 0,
        priceMember: 0,
        type: "Webinar Zoom",
        status: "Selesai",
        description: "Tips dan trik mengelola fokus siswa gen-Z menggunakan teknologi pembelajaran interaktif."
    }
];

// --- GLOBAL STATE ---
let currentUser = JSON.parse(localStorage.getItem('currentUser')) || null; 
let currentSeminarId = localStorage.getItem('currentSeminarId') || null;
let checkoutItem = null;

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    updateAuthUI();
    
    // Check if we need to render seminars on this page
    if (document.getElementById('home-seminar-list')) {
        renderHomeSeminars();
    }
    
    if (document.getElementById('seminar-list-container')) {
        renderAllSeminars();
    }
    
    if (document.getElementById('detail-title')) {
        renderSeminarDetail();
    }
    
    // Check if we need to setup login form
    if (document.getElementById('loginForm')) {
        setupLoginForm();
    }
});

function formatRupiah(num) {
    return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', minimumFractionDigits: 0 }).format(num);
}

function renderHomeSeminars() {
    const homeList = document.getElementById('home-seminar-list');
    if (!homeList) return;
    
    const seminars = MOCK_SEMINARS.slice(0, 3);
    const cards = seminars.map(createCardHTML).join('');
    homeList.innerHTML = cards;
    lucide.createIcons();
}

function renderAllSeminars() {
    const container = document.getElementById('seminar-list-container');
    if (!container) return;
    
    const cards = MOCK_SEMINARS.map(createCardHTML).join('');
    container.innerHTML = cards;
    lucide.createIcons();
}

function createCardHTML(seminar) {
    return `
        <div class="col-md-4">
            <div class="card h-100 border-0 shadow-sm hover-card overflow-hidden">
                <div class="position-relative" style="height: 200px;">
                    <img src="${seminar.image}" alt="${seminar.title}" class="w-100 h-100 object-fit-cover">
                    <div class="position-absolute top-0 end-0 p-2">
                        <span class="badge ${seminar.status === 'Open' ? 'bg-success' : 'bg-secondary'}">${seminar.status}</span>
                    </div>
                </div>
                <div class="card-body d-flex flex-column p-4">
                    <div class="d-flex gap-3 text-muted small mb-2">
                        <span class="d-flex align-items-center gap-1"><i data-lucide="calendar" width="14"></i> ${seminar.date}</span>
                        <span class="d-flex align-items-center gap-1"><i data-lucide="video" width="14"></i> ${seminar.type}</span>
                    </div>
                    <h5 class="card-title fw-bold mb-2 text-truncate-2">${seminar.title}</h5>
                    <p class="card-text text-muted small flex-grow-1 text-truncate-3">${seminar.description}</p>
                    
                    <hr class="opacity-10 my-3">
                    
                    <div class="mb-3 d-flex justify-content-between align-items-end">
                        <div><small class="text-muted d-block" style="font-size: 0.7rem;">UMUM</small> <span class="text-decoration-line-through text-muted small">${formatRupiah(seminar.priceNonMember)}</span></div>
                        <div class="text-end"><small class="text-primary fw-bold d-block" style="font-size: 0.7rem;">MEMBER</small> <span class="text-primary fw-bold">${seminar.priceMember === 0 ? 'GRATIS' : formatRupiah(seminar.priceMember)}</span></div>
                    </div>

                    <a href="seminar-detail?id=${seminar.id}" 
                       class="btn w-100 fw-medium ${seminar.status === 'Open' ? 'btn-primary' : 'btn-outline-secondary'} ${seminar.status !== 'Open' ? 'disabled' : ''}">
                        ${seminar.status === 'Open' ? 'Detail & Daftar' : 'Selesai'}
                    </a>
                </div>
            </div>
        </div>
    `;
}

function renderSeminarDetail() {
    const urlParams = new URLSearchParams(window.location.search);
    const seminarId = parseInt(urlParams.get('id'));
    
    if (!seminarId) {
        window.location.href = 'seminars';
        return;
    }
    
    const seminar = MOCK_SEMINARS.find(s => s.id === seminarId);
    if (!seminar) {
        window.location.href = 'seminars';
        return;
    }
    
    currentSeminarId = seminarId;
    localStorage.setItem('currentSeminarId', seminarId);
    
    // Update page content
    document.getElementById('detail-image').src = seminar.image;
    document.getElementById('detail-title').innerText = seminar.title;
    document.getElementById('detail-type').innerText = seminar.type;
    document.getElementById('detail-status').innerText = seminar.status;
    document.getElementById('detail-speaker').innerText = seminar.speaker;
    document.getElementById('detail-datetime').innerText = `${seminar.date} | ${seminar.time}`;
    document.getElementById('detail-desc').innerText = seminar.description;
    document.getElementById('detail-price-public').innerText = formatRupiah(seminar.priceNonMember);
    document.getElementById('detail-price-member').innerText = formatRupiah(seminar.priceMember);
    
    // Update registration button
    const regBtn = document.getElementById('btn-register-seminar');
    const warning = document.getElementById('detail-login-warning');
    
    if (currentUser) {
        const price = currentUser.isMember ? seminar.priceMember : seminar.priceNonMember;
        
        if (price === 0) {
            regBtn.innerText = currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId) 
                ? "Sudah Terdaftar (GRATIS)" 
                : "Daftar GRATIS";
            regBtn.disabled = currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId);
            regBtn.className = `btn btn-success btn-lg px-5 rounded-pill shadow-sm fw-bold`;
        } else {
            regBtn.innerText = currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId)
                ? "Sudah Terdaftar (Berbayar)"
                : "Daftar Sekarang & Bayar";
            regBtn.disabled = currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId);
            regBtn.className = `btn btn-${currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId) ? 'secondary' : 'primary'} btn-lg px-5 rounded-pill shadow-sm fw-bold`;
        }
        
        if (warning) {
            warning.classList.remove('d-flex');
            warning.classList.add('d-none');
        }
    } else {
        regBtn.innerText = "Login untuk Daftar";
        regBtn.disabled = true;
        regBtn.className = "btn btn-secondary btn-lg px-5 rounded-pill shadow-sm fw-bold";
        if (warning) {
            warning.classList.remove('d-none');
            warning.classList.add('d-flex');
        }
    }
    
    // Add event listener to registration button
    if (regBtn) {
        regBtn.addEventListener('click', function() {
            handleSeminarRegistration(seminarId);
        });
    }
    
    lucide.createIcons();
}

function updateAuthUI() {
    const guestNav = document.getElementById('nav-guest');
    const userNav = document.getElementById('nav-user');
    
    if (!guestNav || !userNav) return;
    
    if (currentUser) {
        guestNav.classList.add('d-none');
        guestNav.classList.remove('d-flex');
        userNav.classList.remove('d-none');
        
        document.getElementById('user-avatar').innerText = currentUser.name.charAt(0);
        document.getElementById('user-name-display').innerText = currentUser.name.split(' ')[0];
        document.getElementById('user-role-display').innerText = currentUser.isMember ? 'Anggota Aktif' : 'User';
        
        // Update dashboard if exists
        if (document.getElementById('dashboard-avatar')) {
            document.getElementById('dashboard-avatar').innerText = currentUser.name.charAt(0);
            document.getElementById('dashboard-name').innerText = currentUser.name;
            document.getElementById('dashboard-inst').innerText = currentUser.institution;
            const badge = document.getElementById('dashboard-status-badge');
            
            if (currentUser.isMember) {
                badge.innerText = "Member Aktif";
                badge.className = "badge bg-primary rounded-pill";
                if (document.getElementById('card-member-view')) {
                    document.getElementById('card-member-view').classList.remove('d-none');
                    document.getElementById('card-guest-view').classList.add('d-none');
                    document.getElementById('card-name').innerText = currentUser.name;
                    document.getElementById('card-exp').innerText = new Date(currentUser.memberExpiry).toLocaleDateString('id-ID');
                }
                if (document.getElementById('member-active-badge')) {
                    document.getElementById('member-active-badge').classList.remove('d-none');
                }
                if (document.getElementById('btn-join-membership')) {
                    document.getElementById('btn-join-membership').innerText = "Perpanjang Keanggotaan";
                }
            } else {
                badge.innerText = "User Umum";
                badge.className = "badge bg-secondary rounded-pill";
                if (document.getElementById('card-member-view')) {
                    document.getElementById('card-member-view').classList.add('d-none');
                    document.getElementById('card-guest-view').classList.remove('d-none');
                }
                if (document.getElementById('member-active-badge')) {
                    document.getElementById('member-active-badge').classList.add('d-none');
                }
                if (document.getElementById('btn-join-membership')) {
                    document.getElementById('btn-join-membership').innerText = "Daftar Member Sekarang";
                }
            }
            
            // Render user's seminars
            renderUserSeminars();
        }
    } else {
        guestNav.classList.remove('d-none');
        guestNav.classList.add('d-flex');
        userNav.classList.add('d-none');
    }
}

function handleLogin(email, password) {
    // Simulate login
    currentUser = {
        name: "Budi Purnomo",
        email: email,
        phone: "081234567890",
        institution: "SMAN 1 Nusantara",
        isMember: false,
        memberSince: null,
        memberExpiry: null,
        joinedSeminars: [3]
    };
    
    localStorage.setItem('currentUser', JSON.stringify(currentUser));
    showToast("Login Berhasil! Selamat datang..", "success");
    updateAuthUI();
    
    // Redirect to dashboard after short delay
    setTimeout(() => {
        window.location.href = 'dashboard';
    }, 1000);
}

function setupLoginForm() {
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const email = document.getElementById('login-email').value;
            const password = document.getElementById('login-password').value;
            
            handleLogin(email, password);
        });
    }
}

function handleLogout() {
    currentUser = null;
    localStorage.removeItem('currentUser');
    showToast("Berhasil Logout", "info");
    updateAuthUI();
    
    setTimeout(() => {
        window.location.href = 'index.php';
    }, 500);
}

function handleSeminarRegistration(seminarId) {
    if (!currentUser) {
        showToast("Silakan login terlebih dahulu", "danger");
        window.location.href = 'login';
        return;
    }
    
    const seminar = MOCK_SEMINARS.find(s => s.id === seminarId);
    if (!seminar) return;
    
    // Check if already registered
    if (currentUser.joinedSeminars && currentUser.joinedSeminars.includes(seminarId)) {
        showToast("Anda sudah terdaftar di seminar ini", "info");
        return;
    }
    
    const price = currentUser.isMember ? seminar.priceMember : seminar.priceNonMember;
    
    if (price === 0) {
        // Free seminar
        if (!currentUser.joinedSeminars) currentUser.joinedSeminars = [];
        currentUser.joinedSeminars.push(seminarId);
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        showToast(`Pendaftaran Seminar "${seminar.title}" Berhasil (GRATIS)!`, "success");
        
        // Refresh the page
        setTimeout(() => {
            window.location.reload();
        }, 1500);
    } else {
        // Paid seminar - show checkout modal
        showCheckoutModal(
            `Pendaftaran Seminar: ${seminar.title}`,
            price,
            `SEMINAR-${seminar.id}-${Date.now()}`
        );
    }
}

function showCheckoutModal(itemName, amount, reference) {
    if (!currentUser) {
        showToast("Anda harus login untuk melanjutkan pembayaran.", "danger");
        window.location.href = 'login';
        return;
    }
    
    checkoutItem = {
        name: itemName,
        amount: amount,
        reference: reference
    };
    
    // Create modal dynamically if it doesn't exist
    let modal = document.getElementById('checkoutModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.innerHTML = `
            <div class="modal fade" id="checkoutModal" tabindex="-1" aria-labelledby="checkoutModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content rounded-4 shadow-lg border-0">
                        <div class="modal-header bg-primary text-white border-0 rounded-top-4">
                            <h5 class="modal-title fw-bold" id="checkoutModalLabel">Detail Pembayaran</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body p-4">
                            <h6 class="fw-bold mb-3" id="checkout-item-name"></h6>
                            
                            <ul class="list-group list-group-flush mb-4 small">
                                <li class="list-group-item px-0 d-flex justify-content-between">
                                    <span class="text-muted">Email Pengguna</span>
                                    <span id="checkout-email" class="fw-medium"></span>
                                </li>
                                <li class="list-group-item px-0 d-flex justify-content-between">
                                    <span class="text-muted">Nomor WhatsApp</span>
                                    <span id="checkout-phone" class="fw-medium"></span>
                                </li>
                                <li class="list-group-item px-0 d-flex justify-content-between bg-light rounded-2 py-2 fw-bold text-dark">
                                    <span>TOTAL TAGIHAN</span>
                                    <span id="checkout-amount"></span>
                                </li>
                            </ul>

                            <p class="text-muted small mb-3"><i data-lucide="shield-check" width="16" class="inline me-1 text-success"></i> Pembayaran akan diproses melalui *iPaymu*.</p>

                            <div class="d-grid">
                                <button onclick="initiatePayment(this)" class="btn btn-success btn-lg fw-bold" id="btn-pay-now">
                                    <i data-lucide="credit-card" width="20" class="inline me-2"></i> Lanjut ke Pembayaran iPaymu
                                </button>
                            </div>
                            <p class="text-center small mt-2">Anda akan dialihkan ke halaman iPaymu.</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }
    
    // Update modal content
    document.getElementById('checkoutModalLabel').innerText = `Bayar ${itemName}`;
    document.getElementById('checkout-item-name').innerText = itemName;
    document.getElementById('checkout-email').innerText = currentUser.email;
    document.getElementById('checkout-phone').innerText = currentUser.phone;
    document.getElementById('checkout-amount').innerText = formatRupiah(amount);
    document.getElementById('btn-pay-now').setAttribute('data-reference', reference);
    
    // Show modal
    const checkoutModal = new bootstrap.Modal(document.getElementById('checkoutModal'));
    checkoutModal.show();
    lucide.createIcons();
}

function initiatePayment(button) {
    const btn = button;
    const originalText = btn.innerHTML;
    
    btn.innerHTML = `
        <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
        Memproses...
    `;
    btn.disabled = true;
    
    // Simulate payment processing
    setTimeout(() => {
        showToast("Pembayaran berhasil diproses! Anda terdaftar di seminar.", "success");
        
        // Close modal
        const modal = bootstrap.Modal.getInstance(document.getElementById('checkoutModal'));
        modal.hide();
        
        // Update user's seminar list
        if (currentUser && checkoutItem) {
            const seminarId = parseInt(checkoutItem.reference.split('-')[1]);
            if (!currentUser.joinedSeminars) currentUser.joinedSeminars = [];
            if (!currentUser.joinedSeminars.includes(seminarId)) {
                currentUser.joinedSeminars.push(seminarId);
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
            }
        }
        
        // Redirect to dashboard
        setTimeout(() => {
            window.location.href = 'dashboard';
        }, 1000);
    }, 2000);
}

function handleJoinMembership() {
    if (!currentUser) {
        showToast("Silakan login terlebih dahulu", "danger");
        window.location.href = 'login';
        return;
    }
    
    const memberPrice = 150000;
    
    if (currentUser.isMember) {
        showCheckoutModal(
            "Perpanjangan Member PAPENTARA 1 Tahun", 
            memberPrice, 
            `MEMBER-RENEWAL-${Date.now()}`
        );
    } else {
        showCheckoutModal(
            "Pendaftaran Member PAPENTARA 1 Tahun", 
            memberPrice, 
            `MEMBER-NEW-${Date.now()}`
        );
    }
}

function renderUserSeminars() {
    const mySeminarsList = document.getElementById('dashboard-seminar-list');
    if (!mySeminarsList || !currentUser || !currentUser.joinedSeminars) return;
    
    const mySeminars = MOCK_SEMINARS.filter(s => currentUser.joinedSeminars.includes(s.id));
    
    if (mySeminars.length > 0) {
        mySeminarsList.innerHTML = mySeminars.map(s => `
            <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
                <div class="card-body p-3 d-flex flex-column flex-md-row gap-3 align-items-center">
                    <img src="${s.image}" class="rounded object-fit-cover" width="80" height="80">
                    <div class="flex-grow-1 text-center text-md-start">
                        <h6 class="fw-bold mb-1">${s.title}</h6>
                        <small class="text-muted">${s.date} | ${s.time}</small>
                    </div>
                    <div>
                        ${s.priceNonMember === 0 || currentUser.joinedSeminars.includes(s.id) 
                            ? '<button class="btn btn-outline-primary btn-sm rounded-pill px-3">Link Zoom</button>' 
                            : '<span class="badge bg-warning text-dark">Menunggu Bayar</span>'}
                    </div>
                </div>
            </div>
        `).join('');
    } else {
        mySeminarsList.innerHTML = '<div class="alert alert-light text-center border-0 shadow-sm py-4">Belum ada seminar yang diikuti.</div>';
    }
    
    lucide.createIcons();
}

function switchDashboardTab(tabId) {
    // Hide all tabs
    document.querySelectorAll('.dashboard-tab').forEach(el => {
        el.classList.remove('d-block');
        el.classList.add('d-none');
    });
    
    // Remove active class from all tab buttons
    document.querySelectorAll('.list-group-item').forEach(el => {
        el.classList.remove('active');
    });
    
    // Show selected tab
    document.getElementById(`tab-${tabId}`).classList.remove('d-none');
    document.getElementById(`tab-${tabId}`).classList.add('d-block');
    
    // Activate selected tab button
    document.getElementById(`tab-btn-${tabId}`).classList.add('active');
    lucide.createIcons();
}

function showToast(message, type = 'success') {
    const toastEl = document.getElementById('liveToast');
    const toastBody = document.getElementById('toast-message');
    
    if (!toastEl || !toastBody) return;
    
    // Set Color Scheme
    toastEl.classList.remove('bg-success', 'bg-danger', 'bg-info', 'bg-primary');
    
    if (type === 'success') {
        toastEl.classList.add('bg-success');
    } else if (type === 'danger') {
        toastEl.classList.add('bg-danger');
    } else if (type === 'info') {
        toastEl.classList.add('bg-info');
    } else {
        toastEl.classList.add('bg-primary');
    }
    
    toastBody.innerText = message;
    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}