<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registrasi Akun - PAPENTARA</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest"></script>

    <!-- Custom Font: Inter -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="assets/style.css">
    <style>
:root {
    --primary-color: #0d6efd;
    --success-color: #198754;
    --danger-color: #dc3545;
    --warning-color: #ffc107;
    --info-color: #0dcaf0;
    --secondary-color: #6c757d;
    --light-color: #f8f9fa;
    --dark-color: #212529;
}

body {
    font-family: 'Inter', sans-serif;
}

/* Toast Notification */
.toast-alert {
    position: fixed;
    top: 20px;
    right: 20px;
    background: white;
    padding: 15px 20px;
    border-radius: 8px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 10px;
    transform: translateX(150%);
    transition: transform 0.3s ease;
    z-index: 9999;
    max-width: 350px;
}

.toast-alert.show {
    transform: translateX(0);
}

.toast-alert-success {
    border-left: 4px solid var(--success-color);
}

.toast-alert-error {
    border-left: 4px solid var(--danger-color);
}

.toast-alert-info {
    border-left: 4px solid var(--info-color);
}

.toast-alert-warning {
    border-left: 4px solid var(--warning-color);
}

.toast-content i {
    width: 20px;
    height: 20px;
}

.toast-alert-success i {
    color: var(--success-color);
}

.toast-alert-error i {
    color: var(--danger-color);
}

.toast-alert-info i {
    color: var(--info-color);
}

.toast-alert-warning i {
    color: var(--warning-color);
}

/* Password strength indicator */
.password-strength-container {
    margin-top: 5px;
}

.password-strength-bar {
    height: 5px;
    border-radius: 3px;
    transition: all 0.3s ease;
}

.password-strength-container .progress {
    background-color: #e9ecef;
    border-radius: 4px;
}

.password-strength-container .progress-bar {
    border-radius: 4px;
    transition: width 0.3s ease, background-color 0.3s ease;
}

/* Icon styles */
.icon-xs {
    width: 14px;
    height: 14px;
    margin-right: 4px;
    flex-shrink: 0;
}

.icon-sm {
    width: 18px;
    height: 18px;
}

.icon-md {
    width: 24px;
    height: 24px;
}

/* Password requirements */
#password-requirements span {
    display: inline-flex;
    align-items: center;
    font-size: 0.85rem;
    margin-right: 12px;
    margin-bottom: 5px;
}

#password-requirements .d-flex {
    flex-wrap: wrap;
}

/* Spinner animation */
.spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Form validation */
.is-valid {
    border-color: var(--success-color) !important;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
}

.is-invalid {
    border-color: var(--danger-color) !important;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
}

/* Form text colors */
.text-success {
    color: var(--success-color) !important;
}

.text-danger {
    color: var(--danger-color) !important;
}

.text-warning {
    color: var(--warning-color) !important;
}

.text-info {
    color: var(--info-color) !important;
}

.text-muted {
    color: var(--secondary-color) !important;
}

/* Password input group */
.password-input-group {
    position: relative;
}

.password-toggle-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: transparent;
    border: none;
    padding: 0;
    cursor: pointer;
    z-index: 5;
    color: var(--secondary-color);
    transition: color 0.2s;
}

.password-toggle-btn:hover {
    color: var(--dark-color);
}

.password-toggle-btn:focus {
    outline: none;
    box-shadow: none;
}

/* Button disabled state */
button[disabled] {
    cursor: not-allowed;
    opacity: 0.6;
    position: relative;
}

button[disabled]::before {
    content: attr(data-tooltip);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background-color: var(--dark-color);
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    z-index: 1000;
    margin-bottom: 5px;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
}

button[disabled]::after {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    border: 5px solid transparent;
    border-top-color: var(--dark-color);
    margin-bottom: -5px;
    z-index: 1000;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s, visibility 0.3s;
}

button[disabled]:hover::before,
button[disabled]:hover::after {
    opacity: 1;
    visibility: visible;
}

/* Navbar hover */
.hover-bg-light:hover {
    background-color: rgba(0, 0, 0, 0.05);
}

/* Footer hover */
.hover-text-white:hover {
    color: white !important;
}

/* Card shadow */
.card {
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card:hover {
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1) !important;
}

/* Responsive adjustments */
@media (max-width: 576px) {
    .card-body {
        padding: 1.5rem !important;
    }
    
    .toast-alert {
        max-width: 90%;
        left: 5%;
        right: 5%;
    }
}

/* Focus styles */
.form-control:focus,
.form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

/* Custom padding for password input with icon */
.form-control.password-with-icon {
    padding-right: 45px;
}

/* Background colors for password strength */
.bg-danger {
    background-color: var(--danger-color) !important;
}

.bg-warning {
    background-color: var(--warning-color) !important;
}

.bg-info {
    background-color: var(--info-color) !important;
}

.bg-success {
    background-color: var(--success-color) !important;
}

.bg-secondary {
    background-color: var(--secondary-color) !important;
}

/* Additional form styling */
.form-text {
    font-size: 0.875rem;
    margin-top: 0.25rem;
}

.form-control.bg-light {
    background-color: var(--light-color) !important;
}

/* Navbar logo styling */
.navbar-brand div:first-child {
    background-color: var(--primary-color);
}

/* Footer styling */
footer.bg-dark {
    background-color: #212529 !important;
}

footer .text-secondary {
    color: #6c757d !important;
}

/* Custom border radius */
.rounded-4 {
    border-radius: 1rem !important;
}

/* Shadow utilities */
.shadow-sm {
    box-shadow: 0 .125rem .25rem rgba(0,0,0,.075) !important;
}

.shadow-lg {
    box-shadow: 0 1rem 3rem rgba(0,0,0,.175) !important;
}

/* Custom width for dropdown */
.dropdown-menu {
    min-width: 200px;
}

/* Animation for fade in */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

.fade-in {
    animation: fadeIn 0.3s ease-in;
}

/* Custom select styling */
.form-select {
    background-position: right 0.75rem center;
    padding-right: 2.5rem;
}

/* Card header styling */
.card-header {
    background-color: rgba(var(--primary-color), 0.05);
    border-bottom: 1px solid rgba(0,0,0,.125);
}

/* Button transition */
.btn {
    transition: all 0.2s ease-in-out;
}

.btn:hover {
    transform: translateY(-1px);
}

/* Custom checkbox styling */
.form-check-input:checked {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

/* Link styling */
a.text-primary:hover {
    color: #0a58ca !important;
}

/* Custom height utilities */
.min-vh-100 {
    min-height: 100vh !important;
}

/* Sticky footer support */
.flex-grow-1 {
    flex-grow: 1 !important;
}

/* Border utilities */
.border-0 {
    border: 0 !important;
}

/* Position utilities */
.position-relative {
    position: relative !important;
}

/* Z-index utilities */
.z-index-1000 {
    z-index: 1000 !important;
}

/* Loading overlay */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    display: none;
}

.loading-overlay.active {
    display: flex;
}

/* Custom scrollbar */
::-webkit-scrollbar {
    width: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: var(--primary-color);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #0a58ca;
}

/* Selection color */
::selection {
    background-color: var(--primary-color);
    color: white;
}

/* Placeholder styling */
::placeholder {
    color: #6c757d !important;
    opacity: 0.7 !important;
}

/* Focus outline removal for non-keyboard interactions */
*:focus:not(:focus-visible) {
    outline: none;
}

/* Print styles */
@media print {
    .navbar,
    footer,
    .toast-alert,
    .password-toggle-btn {
        display: none !important;
    }
    
    .card {
        border: 1px solid #000 !important;
        box-shadow: none !important;
    }
}
</style>
</head>
<body class="d-flex flex-column min-vh-100">

    <!-- NAVIGATION -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom sticky-top shadow-sm">
        <div class="container-xl">
            <!-- Logo -->
            <a class="navbar-brand d-flex align-items-center" href="../">
                <div class="bg-primary p-2 rounded me-2 d-flex align-items-center justify-content-center">
                    <i data-lucide="book-open" class="text-white icon-md"></i>
                </div>
                <div style="line-height: 1.2;">
                    <span class="d-block fw-bold text-dark">PAPENTARA</span>
                    <span class="d-block text-primary small fw-medium" style="font-size: 0.75rem; letter-spacing: 0.5px;">Keanggotaan dan Seminar</span>
                </div>
            </a>

            <!-- Mobile Toggle -->
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>

            <!-- Links -->
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto align-items-lg-center">
                    <li class="nav-item"><a class="nav-link" href="../">Beranda</a></li>
                    <li class="nav-item"><a class="nav-link" href="../seminars">Seminar</a></li>
                    <li class="nav-item"><a class="nav-link" href="../membership">Keanggotaan</a></li>
                    
                    <!-- Divider for Mobile -->
                    <li class="nav-item d-lg-none"><hr class="dropdown-divider"></li>

                    <!-- Guest State -->
                    <li id="nav-guest" class="nav-item ms-lg-3 d-flex gap-2">
                        <a href="./" class="btn btn-outline-secondary btn-sm px-3 fw-medium">Masuk</a>
                        <a href="./register" class="btn btn-primary btn-sm px-3 fw-medium">Daftar</a>
                    </li>

                    <!-- User State -->
                    <li id="nav-user" class="nav-item dropdown ms-lg-3 d-none">
                        <a class="nav-link dropdown-toggle d-flex align-items-center gap-2 p-1 pe-3 rounded hover-bg-light" href="#" role="button" data-bs-toggle="dropdown">
                            <div class="bg-primary bg-opacity-10 text-primary rounded-circle d-flex align-items-center justify-content-center fw-bold" style="width: 35px; height: 35px;" id="user-avatar">
                                B
                            </div>
                            <div class="d-none d-lg-block text-start lh-1">
                                <small class="d-block fw-bold text-dark" id="user-name-display">User</small>
                                <small class="d-block text-muted" style="font-size: 0.7rem;" id="user-role-display">User</small>
                            </div>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0 mt-2">
                            <li><a class="dropdown-item" href="dashboard"><i data-lucide="layout-dashboard" class="icon-sm me-2"></i> Dashboard</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="handleLogout()"><i data-lucide="log-out" class="icon-sm me-2"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- LOADING OVERLAY -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <!-- MAIN CONTENT -->
    <main class="flex-grow-1">
        <div class="container py-5 min-vh-100 d-flex align-items-center justify-content-center">
            <div class="card border-0 shadow-lg rounded-4 overflow-hidden" style="max-width: 500px; width: 100%;">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <h3 class="fw-bold text-primary">Buat Akun Baru</h3>
                        <p class="text-muted">Menjadi Anggota atau untuk Seminar</p>
                    </div>
                    
                    <form id="registerForm">
                        <!-- Hidden CSRF Token Field -->
                        <input type="hidden" id="csrf_token" name="csrf_token" value="">
                        
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Nama Lengkap (dengan gelar)</label>
                            <input type="text" id="register-name" class="form-control bg-light" placeholder="Contoh: Dr. Budi Santoso, M.Pd" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-medium small">Institusi / Sekolah</label>
                            <input type="text" id="register-institution" class="form-control bg-light" placeholder="SMAN 1 Nusantara" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-medium small">Nomor WhatsApp</label>
                            <input type="tel" id="register-phone" class="form-control bg-light" placeholder="0812xxxx" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Email</label>
                            <input type="email" id="register-email" class="form-control bg-light" placeholder="contoh@email.com" required>
                        </div>
                        
                        <!-- Dropdown Provinsi -->
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Provinsi</label>
                            <select id="register-province" class="form-select bg-light" required>
                                <option value="">Loading provinsi...</option>
                            </select>
                            <div class="form-text">Pilih provinsi tempat tinggal Anda</div>
                        </div>
                        
                        <!-- Dropdown Kabupaten/Kota -->
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Kabupaten/Kota</label>
                            <select id="register-city" class="form-select bg-light" required disabled>
                                <option value="">Pilih provinsi terlebih dahulu</option>
                            </select>
                            <div class="form-text">Pilih kabupaten/kota tempat tinggal Anda</div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Alamat Lengkap</label>
                            <textarea id="register-address" class="form-control bg-light" rows="2" placeholder="Jl. Contoh No. 123, RT/RW, Kode Pos" required></textarea>
                            <div class="form-text">Masukkan alamat lengkap termasuk nomor rumah, jalan, RT/RW</div>
                        </div>
                        
                        <!-- Password Field dengan Tombol Mata -->
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Buat Password</label>
                            <div class="password-input-group position-relative">
                                <input type="password" id="register-password" class="form-control bg-light password-with-icon" placeholder="Minimal 8 karakter" required minlength="8">
                                <button type="button" class="password-toggle-btn" id="toggle-password" aria-label="Tampilkan password">
                                    <i data-lucide="eye" class="icon-sm"></i>
                                </button>
                            </div>
                            <div class="password-strength-container">
                                <div class="progress mt-1" style="height: 8px;">
                                    <div id="password-strength-indicator" class="progress-bar" role="progressbar" style="width: 0%"></div>
                                </div>
                                <div id="password-strength-text" class="form-text small mt-1">Kekuatan: -</div>
                                <div id="password-requirements" class="small mt-2">
                                    <div class="text-muted">Password harus mengandung:</div>
                                    <div class="d-flex flex-wrap gap-3 mt-1">
                                        <span id="req-length" class="text-danger">
                                            <i data-lucide="x-circle" class="icon-xs"></i> Minimal 8 karakter
                                        </span>
                                        <span id="req-lowercase" class="text-danger">
                                            <i data-lucide="x-circle" class="icon-xs"></i> Huruf kecil
                                        </span>
                                        <span id="req-uppercase" class="text-danger">
                                            <i data-lucide="x-circle" class="icon-xs"></i> Huruf besar
                                        </span>
                                        <span id="req-number" class="text-danger">
                                            <i data-lucide="x-circle" class="icon-xs"></i> Angka
                                        </span>
                                        <span id="req-special" class="text-muted">
                                            <i data-lucide="circle" class="icon-xs"></i> Simbol (opsional)
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Konfirmasi Password Field dengan Tombol Mata -->
                        <div class="mb-3">
                            <label class="form-label fw-medium small">Konfirmasi Password</label>
                            <div class="password-input-group position-relative">
                                <input type="password" id="register-password-confirm" class="form-control bg-light password-with-icon" placeholder="Ketik ulang password" required minlength="8">
                                <button type="button" class="password-toggle-btn" id="toggle-password-confirm" aria-label="Tampilkan password">
                                    <i data-lucide="eye" class="icon-sm"></i>
                                </button>
                            </div>
                            <div class="form-text text-danger d-none" id="password-match-error">Password tidak sama!</div>
                        </div>

                        <!-- Checkbox Persetujuan -->
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="register-terms" required>
                                <label class="form-check-label small" for="register-terms">
                                    Saya setuju dengan 
                                    <a href="#" target="_blank" class="text-primary">Kebijakan Layanan</a> 
                                    dan 
                                    <a href="#" target="_blank" class="text-primary">Kebijakan Privasi</a>
                                </label>
                                <div class="invalid-feedback small">
                                    Anda harus menyetujui kebijakan layanan dan privasi untuk mendaftar.
                                </div>
                            </div>
                        </div>

                        <!-- Checkbox Newsletter (Opsional) -->
                        <div class="mb-4">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="register-newsletter">
                                <label class="form-check-label small" for="register-newsletter">
                                    Saya ingin menerima informasi terbaru tentang seminar, workshop, dan promosi melalui email
                                </label>
                            </div>
                        </div>

                        <div class="d-grid mb-4">
                            <button type="submit" class="btn btn-primary py-2 fw-bold" id="register-submit-btn">Daftar Sekarang</button>
                        </div>
                    </form>
                    
                    <div class="text-center small">
                        <p class="text-muted m-0">Sudah punya akun? <a href="./login" class="text-decoration-none fw-bold">Masuk disini</a></p>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- FOOTER -->
    <footer class="bg-dark text-light pt-5 pb-3">
        <div class="container-xl">
            <div class="row g-4 mb-5">
                <div class="col-md-5">
                    <div class="d-flex align-items-center gap-2 mb-3">
                        <i data-lucide="book-open" class="text-primary icon-md"></i>
                        <h4 class="fw-bold m-0">PAPENTARA</h4>
                    </div>
                    <p class="text-secondary small col-md-10">
                        Perkumpulan Afirmasi Pengajar Nusantara. Wadah profesional bagi guru untuk berkembang, berbagi, dan bersinergi memajukan pendidikan Indonesia.
                    </p>
                </div>
                <div class="col-md-3">
                    <h6 class="fw-bold text-white mb-3">Tautan Cepat</h6>
                    <ul class="list-unstyled d-flex flex-column gap-2 text-secondary small">
                        <li><a href="../" class="text-decoration-none text-secondary hover-text-white">Beranda</a></li>
                        <li><a href="../seminars" class="text-decoration-none text-secondary hover-text-white">Daftar Seminar</a></li>
                        <li><a href="../membership" class="text-decoration-none text-secondary hover-text-white">Info Keanggotaan</a></li>
                    </ul>
                </div>
                <div class="col-md-4">
                    <h6 class="fw-bold text-white mb-3">Hubungi Kami</h6>
                    <ul class="list-unstyled d-flex flex-column gap-2 text-secondary small">
                        <li class="d-flex gap-2"><i data-lucide="map-pin" class="icon-sm"></i> Jakarta, Indonesia</li>
                        <li class="d-flex gap-2"><i data-lucide="mail" class="icon-sm"></i> admin@papentara.org</li>
                        <li class="d-flex gap-2"><i data-lucide="phone" class="icon-sm"></i> +62 812-3456-7890</li>
                    </ul>
                </div>
            </div>
            <div class="border-top border-secondary border-opacity-25 pt-3 text-center">
                <small class="text-secondary">&copy; 2026 PAPENTARA. All rights reserved.</small>
            </div>
        </div>
    </footer>

    <!-- Bootstrap Bundle JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <!-- App Logic -->
    <script>
    // Inisialisasi Lucide Icons
    document.addEventListener('DOMContentLoaded', function() {
        lucide.createIcons();
        
        // 1. Generate CSRF token saat halaman dimuat
        generateCSRFToken();
        
        // 2. Load data provinsi dari API wilayah.id
        loadProvinces();
        
        // 3. Setup register form
        const registerForm = document.getElementById('registerForm');
        if (registerForm) {
            registerForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                // ======== TUTUP SEMUA PASSWORD SEBELUM SUBMIT ========
                hideAllPasswords();
                
                // Validasi CSRF token
                const csrfToken = document.getElementById('csrf_token').value;
                if (!csrfToken) {
                    showToast("Token keamanan tidak valid. Silakan refresh halaman.", "error");
                    return;
                }
                
                // Validasi checkbox terms
                const termsCheckbox = document.getElementById('register-terms');
                if (!termsCheckbox.checked) {
                    termsCheckbox.classList.add('is-invalid');
                    showToast("Anda harus menyetujui kebijakan layanan dan privasi!", "error");
                    termsCheckbox.focus();
                    return;
                }
                termsCheckbox.classList.remove('is-invalid');
                
                // Validasi form
                const formValidation = validateFormBeforeSubmit();
                if (!formValidation.valid) {
                    showToast(formValidation.message, "error");
                    if (formValidation.element) {
                        document.getElementById(formValidation.element).focus();
                    }
                    return;
                }
                
                // Collect form data
                const formData = new FormData();
                formData.append('csrf_token', csrfToken);
                formData.append('name', document.getElementById('register-name').value.trim());
                formData.append('institution', document.getElementById('register-institution').value.trim());
                formData.append('phone', document.getElementById('register-phone').value.trim());
                formData.append('email', document.getElementById('register-email').value.trim().toLowerCase());
                formData.append('password', document.getElementById('register-password').value);
                formData.append('province_code', document.getElementById('register-province').value);
                formData.append('province_name', document.getElementById('register-province').options[document.getElementById('register-province').selectedIndex].text);
                formData.append('city_code', document.getElementById('register-city').value);
                formData.append('city_name', document.getElementById('register-city').options[document.getElementById('register-city').selectedIndex].text);
                formData.append('address', document.getElementById('register-address').value.trim());
                formData.append('agree_terms', termsCheckbox.checked ? '1' : '0');
                formData.append('newsletter', document.getElementById('register-newsletter').checked ? '1' : '0');
                
                const btn = document.getElementById('register-submit-btn');
                const originalText = btn.innerHTML;
                
                btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Mendaftar...';
                btn.disabled = true;
                
                // Tampilkan loading overlay
                showLoading(true);
                
                // Kirim data ke server
                try {
                    const response = await fetch('login/register_send.php', {
                        method: 'POST',
                        body: formData
                    });
                    
                    const result = await response.json();
                    
                    // Sembunyikan loading overlay
                    showLoading(false);
                    
                    if (result.success) {
                        // Hapus CSRF token yang sudah digunakan dari localStorage
                        localStorage.removeItem('csrf_token');
                        
                        showToast(result.message, "success");
                        
                        // Redirect ke dashboard
                        setTimeout(() => {
                            window.location.href = './dashboard';
                        }, 1500);
                    } else {
                        // Jika CSRF token tidak valid, generate ulang
                        if (result.invalid_csrf) {
                            generateCSRFToken();
                        }
                        showToast(result.message, "error");
                        btn.innerHTML = originalText;
                        btn.disabled = false;
                    }
                } catch (error) {
                    // Sembunyikan loading overlay
                    showLoading(false);
                    
                    console.error('Error:', error);
                    showToast("Terjadi kesalahan koneksi!", "error");
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            });
        }
        
        // 4. Setup password validation
        setupPasswordValidation();
        
        // 5. Setup terms checkbox validation
        setupTermsValidation();
        
        // 6. Setup tombol mata untuk password
        setupPasswordToggleButtons();
        
        // 7. Setup auto-hide password saat form kehilangan fokus
        setupAutoHidePassword();
    });
    
    // ========== FUNGSI TOGGLE PASSWORD VISIBILITY ==========
    function setupPasswordToggleButtons() {
        // Tombol untuk password utama
        const togglePasswordBtn = document.getElementById('toggle-password');
        const passwordInput = document.getElementById('register-password');
        
        if (togglePasswordBtn && passwordInput) {
            togglePasswordBtn.addEventListener('click', function() {
                togglePasswordVisibility(passwordInput, togglePasswordBtn);
            });
        }
        
        // Tombol untuk konfirmasi password
        const toggleConfirmBtn = document.getElementById('toggle-password-confirm');
        const confirmInput = document.getElementById('register-password-confirm');
        
        if (toggleConfirmBtn && confirmInput) {
            toggleConfirmBtn.addEventListener('click', function() {
                togglePasswordVisibility(confirmInput, toggleConfirmBtn);
            });
        }
    }
    
    function togglePasswordVisibility(inputElement, toggleButton) {
        const icon = toggleButton.querySelector('i');
        
        if (inputElement.type === 'password') {
            inputElement.type = 'text';
            icon.setAttribute('data-lucide', 'eye-off');
        } else {
            inputElement.type = 'password';
            icon.setAttribute('data-lucide', 'eye');
        }
        
        // Render ulang ikon
        lucide.createIcons();
    }
    
    // ========== FUNGSI AUTO-HIDE PASSWORD ==========
    function setupAutoHidePassword() {
        const passwordInput = document.getElementById('register-password');
        const confirmInput = document.getElementById('register-password-confirm');
        const togglePasswordBtn = document.getElementById('toggle-password');
        const toggleConfirmBtn = document.getElementById('toggle-password-confirm');
        
        // Auto-hide saat input kehilangan fokus
        if (passwordInput && togglePasswordBtn) {
            passwordInput.addEventListener('blur', function() {
                if (passwordInput.type === 'text') {
                    passwordInput.type = 'password';
                    const icon = togglePasswordBtn.querySelector('i');
                    icon.setAttribute('data-lucide', 'eye');
                    lucide.createIcons();
                }
            });
        }
        
        if (confirmInput && toggleConfirmBtn) {
            confirmInput.addEventListener('blur', function() {
                if (confirmInput.type === 'text') {
                    confirmInput.type = 'password';
                    const icon = toggleConfirmBtn.querySelector('i');
                    icon.setAttribute('data-lucide', 'eye');
                    lucide.createIcons();
                }
            });
        }
        
        // Auto-hide saat user menekan tombol Escape
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                hideAllPasswords();
            }
        });
    }
    
    function hideAllPasswords() {
        // Sembunyikan semua password sebelum submit
        const passwordInput = document.getElementById('register-password');
        const confirmInput = document.getElementById('register-password-confirm');
        const togglePasswordBtn = document.getElementById('toggle-password');
        const toggleConfirmBtn = document.getElementById('toggle-password-confirm');
        
        if (passwordInput && passwordInput.type === 'text') {
            passwordInput.type = 'password';
            if (togglePasswordBtn) {
                const icon = togglePasswordBtn.querySelector('i');
                icon.setAttribute('data-lucide', 'eye');
            }
        }
        
        if (confirmInput && confirmInput.type === 'text') {
            confirmInput.type = 'password';
            if (toggleConfirmBtn) {
                const icon = toggleConfirmBtn.querySelector('i');
                icon.setAttribute('data-lucide', 'eye');
            }
        }
        
        // Render ulang ikon
        lucide.createIcons();
    }
    
    // ========== FUNGSI LOAD DATA PROVINSI ==========
    async function loadProvinces() {
        const provinceSelect = document.getElementById('register-province');
        if (!provinceSelect) return;
        
        try {
            provinceSelect.disabled = true;
            provinceSelect.innerHTML = '<option value="">Loading provinsi...</option>';
            
            // Cek cache di localStorage
            const cacheKey = 'provinces_data';
            const cacheTimeKey = 'provinces_cache_time';
            
            const cachedData = localStorage.getItem(cacheKey);
            const cacheTime = localStorage.getItem(cacheTimeKey);
            
            // Jika cache masih valid (24 jam), gunakan cache
            if (cachedData && cacheTime && (Date.now() - parseInt(cacheTime)) < (24 * 60 * 60 * 1000)) {
                const provinces = JSON.parse(cachedData);
                populateProvinceSelect(provinces);
                provinceSelect.disabled = false;
                return;
            }
            
            // Fetch data dari API
            const response = await fetch('login/api_wilayah.php?endpoint=provinces');
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            // Validasi format data
            if (!data || !Array.isArray(data)) {
                if (data && data.data && Array.isArray(data.data)) {
                    // Format: {data: [...]}
                    populateProvinceSelect(data.data);
                    // Simpan ke cache
                    localStorage.setItem(cacheKey, JSON.stringify(data.data));
                } else if (data && Array.isArray(data.provinces)) {
                    // Format: {provinces: [...]}
                    populateProvinceSelect(data.provinces);
                    // Simpan ke cache
                    localStorage.setItem(cacheKey, JSON.stringify(data.provinces));
                } else {
                    throw new Error('Format data tidak valid');
                }
            } else {
                // Format: [...]
                populateProvinceSelect(data);
                // Simpan ke cache
                localStorage.setItem(cacheKey, JSON.stringify(data));
            }
            
            localStorage.setItem(cacheTimeKey, Date.now().toString());
            
        } catch (error) {
            console.error('Error loading provinces:', error);
            
            // Fallback ke cache jika ada (meski sudah kadaluarsa)
            const cachedData = localStorage.getItem('provinces_data');
            if (cachedData) {
                try {
                    const provinces = JSON.parse(cachedData);
                    populateProvinceSelect(provinces);
                    showToast("Menggunakan data cache yang tersimpan.", "warning");
                } catch (e) {
                    provinceSelect.innerHTML = '<option value="">Gagal memuat data provinsi</option>';
                }
            } else {
                provinceSelect.innerHTML = '<option value="">Gagal memuat data provinsi</option>';
                showToast("Gagal memuat data provinsi. Silakan refresh halaman.", "error");
            }
        } finally {
            provinceSelect.disabled = false;
            lucide.createIcons();
        }
    }
    
    function populateProvinceSelect(provinces) {
        const provinceSelect = document.getElementById('register-province');
        
        // Kosongkan dropdown terlebih dahulu
        provinceSelect.innerHTML = '<option value="">Pilih Provinsi</option>';
        
        // Sort provinces by name
        provinces.sort((a, b) => {
            const nameA = a.name || a.province_name || '';
            const nameB = b.name || b.province_name || '';
            return nameA.localeCompare(nameB);
        });
        
        // Tambahkan opsi untuk setiap provinsi
        provinces.forEach(province => {
            const option = document.createElement('option');
            option.value = province.code || province.id || province.province_code || '';
            option.textContent = province.name || province.province_name || '';
            provinceSelect.appendChild(option);
        });
        
        // Event listener untuk provinsi
        provinceSelect.addEventListener('change', function() {
            const provinceCode = this.value;
            const citySelect = document.getElementById('register-city');
            
            if (provinceCode) {
                // Reset dan disable kota sementara
                citySelect.innerHTML = '<option value="">Loading kabupaten/kota...</option>';
                citySelect.disabled = true;
                
                loadCities(provinceCode);
            } else {
                citySelect.innerHTML = '<option value="">Pilih provinsi terlebih dahulu</option>';
                citySelect.disabled = true;
            }
        });
    }
    
    // ========== FUNGSI LOAD DATA KOTA ==========
    async function loadCities(provinceCode) {
        const citySelect = document.getElementById('register-city');
        if (!citySelect || !provinceCode) return;
        
        try {
            // Tampilkan loading state
            citySelect.innerHTML = '<option value="">Loading kabupaten/kota...</option>';
            citySelect.disabled = true;
            
            // Cek cache
            const cacheKey = `cities_${provinceCode}`;
            const cacheTimeKey = `cities_cache_${provinceCode}`;
            
            const cachedData = localStorage.getItem(cacheKey);
            const cacheTime = localStorage.getItem(cacheTimeKey);
            
            // Jika cache masih valid (7 hari), gunakan cache
            if (cachedData && cacheTime && (Date.now() - parseInt(cacheTime)) < (7 * 24 * 60 * 60 * 1000)) {
                const cities = JSON.parse(cachedData);
                populateCitySelect(cities);
                citySelect.disabled = false;
                return;
            }
            
            // Fetch data dari API - sesuaikan dengan endpoint yang benar
            const response = await fetch(`login/api_wilayah.php?endpoint=regencies&province_code=${provinceCode}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            
            // Validasi format data
            if (!data || !Array.isArray(data)) {
                if (data && data.data && Array.isArray(data.data)) {
                    populateCitySelect(data.data);
                    // Simpan ke cache
                    localStorage.setItem(cacheKey, JSON.stringify(data.data));
                } else if (data && Array.isArray(data.cities)) {
                    populateCitySelect(data.cities);
                    // Simpan ke cache
                    localStorage.setItem(cacheKey, JSON.stringify(data.cities));
                } else {
                    throw new Error('Format data tidak valid');
                }
            } else {
                populateCitySelect(data);
                // Simpan ke cache
                localStorage.setItem(cacheKey, JSON.stringify(data));
            }
            
            localStorage.setItem(cacheTimeKey, Date.now().toString());
            
        } catch (error) {
            console.error('Error loading cities:', error);
            
            // Fallback ke cache jika ada
            const cachedData = localStorage.getItem(`cities_${provinceCode}`);
            if (cachedData) {
                try {
                    const cities = JSON.parse(cachedData);
                    populateCitySelect(cities);
                    showToast("Menggunakan data cache yang tersimpan.", "warning");
                } catch (e) {
                    citySelect.innerHTML = '<option value="">Gagal memuat data kabupaten/kota</option>';
                }
            } else {
                citySelect.innerHTML = '<option value="">Gagal memuat data kabupaten/kota</option>';
                showToast("Gagal memuat data kabupaten/kota. Silakan pilih provinsi lain atau coba lagi.", "error");
            }
        } finally {
            citySelect.disabled = false;
        }
    }
    
    function populateCitySelect(cities) {
        const citySelect = document.getElementById('register-city');
        citySelect.innerHTML = '<option value="">Pilih Kabupaten/Kota</option>';
        
        // Sort cities by name
        cities.sort((a, b) => {
            const nameA = a.name || a.city_name || '';
            const nameB = b.name || b.city_name || '';
            return nameA.localeCompare(nameB);
        });
        
        // Group by type (Kota/Kabupaten)
        const kotaList = [];
        const kabupatenList = [];
        
        cities.forEach(city => {
            const cityName = city.name || city.city_name || '';
            if (cityName.toLowerCase().includes('kota')) {
                kotaList.push(city);
            } else {
                kabupatenList.push(city);
            }
        });
        
        // Tambahkan optgroup untuk Kota
        if (kotaList.length > 0) {
            const kotaGroup = document.createElement('optgroup');
            kotaGroup.label = "Kota";
            kotaList.forEach(city => {
                const option = document.createElement('option');
                option.value = city.code || city.id || city.city_code || '';
                option.textContent = city.name || city.city_name || '';
                kotaGroup.appendChild(option);
            });
            citySelect.appendChild(kotaGroup);
        }
        
        // Tambahkan optgroup untuk Kabupaten
        if (kabupatenList.length > 0) {
            const kabupatenGroup = document.createElement('optgroup');
            kabupatenGroup.label = "Kabupaten";
            kabupatenList.forEach(city => {
                const option = document.createElement('option');
                option.value = city.code || city.id || city.city_code || '';
                option.textContent = city.name || city.city_name || '';
                kabupatenGroup.appendChild(option);
            });
            citySelect.appendChild(kabupatenGroup);
        }
        
        // Jika tidak ada data, tampilkan pesan
        if (kotaList.length === 0 && kabupatenList.length === 0) {
            citySelect.innerHTML = '<option value="">Data tidak tersedia</option>';
        }
    }
    
    // ========== FUNGSI CHECK PASSWORD STRENGTH ==========
    function checkPasswordStrength(password) {
        let score = 0;
        const requirements = {
            length: false,
            lowercase: false,
            uppercase: false,
            number: false,
            special: false
        };
        
        // Check length (minimal 8 karakter)
        if (password.length >= 8) {
            score += 1;
            requirements.length = true;
        }
        
        // Check lowercase
        if (/[a-z]/.test(password)) {
            score += 1;
            requirements.lowercase = true;
        }
        
        // Check uppercase
        if (/[A-Z]/.test(password)) {
            score += 1;
            requirements.uppercase = true;
        }
        
        // Check numbers
        if (/[0-9]/.test(password)) {
            score += 1;
            requirements.number = true;
        }
        
        // Check special characters (bonus)
        if (/[^A-Za-z0-9]/.test(password)) {
            score += 1;
            requirements.special = true;
        }
        
        // Extra points for length
        if (password.length >= 12) score += 1;
        if (password.length >= 16) score += 1;
        
        // Max score 6
        score = Math.min(score, 6);
        
        return {
            score: score,
            requirements: requirements
        };
    }
    
    function updatePasswordStrengthIndicator(strength, password) {
        const indicator = document.getElementById('password-strength-indicator');
        const text = document.getElementById('password-strength-text');
        const requirements = strength.requirements;
        
        // Update requirements icons
        updateRequirementIcon('req-length', requirements.length, 'Minimal 8 karakter');
        updateRequirementIcon('req-lowercase', requirements.lowercase, 'Huruf kecil');
        updateRequirementIcon('req-uppercase', requirements.uppercase, 'Huruf besar');
        updateRequirementIcon('req-number', requirements.number, 'Angka');
        updateRequirementIcon('req-special', requirements.special, 'Simbol (opsional)', true);
        
        // Determine strength level
        let level = {
            text: 'Sangat Lemah',
            color: 'danger',
            width: '16%',
            description: 'Password terlalu lemah'
        };
        
        if (password.length === 0) {
            level = {
                text: '-',
                color: 'secondary',
                width: '0%',
                description: 'Masukkan password'
            };
        } else if (strength.score <= 2) {
            level = {
                text: 'Sangat Lemah',
                color: 'danger',
                width: '16%',
                description: 'Tambahkan lebih banyak karakter dan variasi'
            };
        } else if (strength.score === 3) {
            level = {
                text: 'Lemah',
                color: 'danger',
                width: '33%',
                description: 'Coba tambahkan huruf besar, angka, atau simbol'
            };
        } else if (strength.score === 4) {
            level = {
                text: 'Cukup',
                color: 'warning',
                width: '50%',
                description: 'Password cukup baik, bisa lebih kuat'
            };
        } else if (strength.score === 5) {
            level = {
                text: 'Kuat',
                color: 'info',
                width: '66%',
                description: 'Password kuat'
            };
        } else if (strength.score >= 6) {
            level = {
                text: 'Sangat Kuat',
                color: 'success',
                width: '100%',
                description: 'Password sangat kuat!'
            };
        }
        
        // Update UI
        if (indicator) {
            indicator.style.width = level.width;
            indicator.className = `progress-bar bg-${level.color}`;
        }
        
        if (text) {
            text.innerHTML = `<strong>Kekuatan: ${level.text}</strong> - ${level.description}`;
            text.className = `form-text small text-${level.color}`;
        }
        
        // Update submit button state based on minimum requirements
        const submitBtn = document.getElementById('register-submit-btn');
        const minRequirementsMet = requirements.length && requirements.lowercase && 
                                  requirements.uppercase && requirements.number;
        
        if (submitBtn) {
            if (password.length > 0 && !minRequirementsMet) {
                submitBtn.disabled = true;
                submitBtn.setAttribute('data-tooltip', "Password belum memenuhi syarat minimum");
            } else {
                submitBtn.disabled = false;
                submitBtn.removeAttribute('data-tooltip');
            }
        }
        
        return minRequirementsMet;
    }
    
    // ========== FUNGSI UPDATE REQUIREMENT ICON ==========
    function updateRequirementIcon(elementId, met, text, optional = false) {
        const element = document.getElementById(elementId);
        if (!element) return;
        
        element.innerHTML = '';
        
        const icon = document.createElement('i');
        icon.className = 'icon-xs';
        
        let iconName, colorClass;
        
        if (optional) {
            // Untuk karakter khusus (opsional)
            if (met) {
                iconName = 'check-circle';
                colorClass = 'text-success';
            } else {
                iconName = 'circle';
                colorClass = 'text-muted';
            }
        } else {
            // Untuk persyaratan wajib
            if (met) {
                iconName = 'check-circle';
                colorClass = 'text-success';
            } else {
                iconName = 'x-circle';
                colorClass = 'text-danger';
            }
        }
        
        icon.setAttribute('data-lucide', iconName);
        element.appendChild(icon);
        element.appendChild(document.createTextNode(' ' + text));
        element.className = colorClass;
        
        lucide.createIcons();
    }
    
    // ========== FUNGSI SETUP PASSWORD VALIDATION ==========
    function setupPasswordValidation() {
        const passwordInput = document.getElementById('register-password');
        const confirmPasswordInput = document.getElementById('register-password-confirm');
        
        if (passwordInput) {
            passwordInput.addEventListener('input', function() {
                const password = this.value;
                const strength = checkPasswordStrength(password);
                updatePasswordStrengthIndicator(strength, password);
                validatePasswordMatch();
            });
        }
        
        function validatePasswordMatch() {
            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;
            const errorDiv = document.getElementById('password-match-error');
            
            if (confirmPassword === '') {
                confirmPasswordInput.classList.remove('is-invalid', 'is-valid');
                if (errorDiv) errorDiv.classList.add('d-none');
                return;
            }
            
            if (password === confirmPassword) {
                confirmPasswordInput.classList.remove('is-invalid');
                confirmPasswordInput.classList.add('is-valid');
                if (errorDiv) errorDiv.classList.add('d-none');
            } else {
                confirmPasswordInput.classList.remove('is-valid');
                confirmPasswordInput.classList.add('is-invalid');
                if (errorDiv) errorDiv.classList.remove('d-none');
            }
        }
        
        if (passwordInput && confirmPasswordInput) {
            confirmPasswordInput.addEventListener('input', validatePasswordMatch);
        }
    }
    
    // ========== FUNGSI VALIDASI FORM SEBELUM SUBMIT ==========
    function validateFormBeforeSubmit() {
        // Validasi nama lengkap
        const name = document.getElementById('register-name').value.trim();
        if (!name) {
            return {
                valid: false,
                message: "Nama lengkap harus diisi!",
                element: 'register-name'
            };
        }
        
        // Validasi institusi
        const institution = document.getElementById('register-institution').value.trim();
        if (!institution) {
            return {
                valid: false,
                message: "Institusi/sekolah harus diisi!",
                element: 'register-institution'
            };
        }
        
        // Validasi nomor WhatsApp
        const phone = document.getElementById('register-phone').value.trim();
        if (!phone) {
            return {
                valid: false,
                message: "Nomor WhatsApp harus diisi!",
                element: 'register-phone'
            };
        }
        
        // Validasi format nomor WhatsApp (minimal 10 digit, maksimal 15 digit, hanya angka)
        const phoneRegex = /^[0-9]{10,15}$/;
        if (!phoneRegex.test(phone)) {
            return {
                valid: false,
                message: "Nomor WhatsApp harus berisi 10-15 digit angka!",
                element: 'register-phone'
            };
        }
        
        // Validasi email
        const email = document.getElementById('register-email').value.trim();
        if (!email) {
            return {
                valid: false,
                message: "Email harus diisi!",
                element: 'register-email'
            };
        }
        
        // Validasi format email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return {
                valid: false,
                message: "Format email tidak valid!",
                element: 'register-email'
            };
        }
        
        // Validasi provinsi
        const province = document.getElementById('register-province').value;
        if (!province) {
            return {
                valid: false,
                message: "Provinsi harus dipilih!",
                element: 'register-province'
            };
        }
        
        // Validasi kota
        const city = document.getElementById('register-city').value;
        if (!city) {
            return {
                valid: false,
                message: "Kabupaten/kota harus dipilih!",
                element: 'register-city'
            };
        }
        
        // Validasi alamat
        const address = document.getElementById('register-address').value.trim();
        if (!address) {
            return {
                valid: false,
                message: "Alamat lengkap harus diisi!",
                element: 'register-address'
            };
        }
        
        // Validasi password
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-password-confirm').value;
        
        // Validasi password match
        if (password !== confirmPassword) {
            return {
                valid: false,
                message: "Konfirmasi password tidak sama!",
                element: 'register-password-confirm'
            };
        }
        
        // Validasi password strength
        const strength = checkPasswordStrength(password);
        const minRequirementsMet = strength.requirements.length && 
                                   strength.requirements.lowercase && 
                                   strength.requirements.uppercase && 
                                   strength.requirements.number;
        
        if (!minRequirementsMet) {
            return {
                valid: false,
                message: "Password belum memenuhi syarat minimum!",
                element: 'register-password'
            };
        }
        
        // Validasi password terlalu pendek
        if (password.length < 8) {
            return {
                valid: false,
                message: "Password minimal 8 karakter!",
                element: 'register-password'
            };
        }
        
        return {
            valid: true,
            message: "",
            element: null
        };
    }
    
    // ========== FUNGSI SETUP TERMS VALIDATION ==========
    function setupTermsValidation() {
        const termsCheckbox = document.getElementById('register-terms');
        if (termsCheckbox) {
            termsCheckbox.addEventListener('change', function() {
                if (this.checked) {
                    this.classList.remove('is-invalid');
                }
            });
        }
    }
    
    // ========== FUNGSI CSRF TOKEN ==========
    function generateCSRFToken() {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let token = '';
        for (let i = 0; i < 32; i++) {
            token += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        
        const timestamp = Date.now();
        const fullToken = token + '_' + timestamp;
        
        const tokenData = {
            token: fullToken,
            expires: timestamp + (30 * 60 * 1000) // 30 menit
        };
        
        localStorage.setItem('csrf_token', JSON.stringify(tokenData));
        
        const csrfInput = document.getElementById('csrf_token');
        if (csrfInput) {
            csrfInput.value = fullToken;
        }
        
        return fullToken;
    }
    
    // ========== FUNGSI SHOW TOAST ==========
    function showToast(message, type = "info") {
        const toast = document.createElement('div');
        toast.className = `toast-alert toast-alert-${type} fade-in`;
        toast.innerHTML = `
            <div class="toast-content d-flex align-items-center">
                <i data-lucide="${type === 'success' ? 'check-circle' : type === 'error' ? 'x-circle' : type === 'warning' ? 'alert-triangle' : 'info'}"></i>
                <span class="ms-2">${message}</span>
            </div>
        `;
        
        document.body.appendChild(toast);
        lucide.createIcons();
        
        setTimeout(() => toast.classList.add('show'), 10);
        
        // Hapus toast setelah 5 detik
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 5000);
    }
    
    // ========== FUNGSI SHOW/HIDE LOADING ==========
    function showLoading(show) {
        const loadingOverlay = document.getElementById('loadingOverlay');
        if (loadingOverlay) {
            if (show) {
                loadingOverlay.classList.add('active');
            } else {
                loadingOverlay.classList.remove('active');
            }
        }
    }
    
    // ========== FUNGSI UNTUK NAVIGASI ==========
    function handleLogout() {
        localStorage.removeItem('currentUser');
        localStorage.removeItem('csrf_token');
        window.location.href = './login';
    }
    
    // ========== FUNGSI CEK STATUS LOGIN ==========
    window.addEventListener('load', function() {
        const currentUser = localStorage.getItem('currentUser');
        const navGuest = document.getElementById('nav-guest');
        const navUser = document.getElementById('nav-user');
        
        if (currentUser) {
            // User sudah login
            if (navGuest) navGuest.classList.add('d-none');
            if (navUser) navUser.classList.remove('d-none');
            
            try {
                const userData = JSON.parse(currentUser);
                if (userData.name) {
                    const userNameDisplay = document.getElementById('user-name-display');
                    const userRoleDisplay = document.getElementById('user-role-display');
                    const userAvatar = document.getElementById('user-avatar');
                    
                    if (userNameDisplay) userNameDisplay.textContent = userData.name.split(' ')[0];
                    if (userRoleDisplay) userRoleDisplay.textContent = userData.isMember ? 'Anggota' : 'User';
                    if (userAvatar) userAvatar.textContent = userData.name.charAt(0).toUpperCase();
                }
            } catch (e) {
                console.error('Error parsing user data:', e);
            }
        } else {
            // User belum login
            if (navGuest) navGuest.classList.remove('d-none');
            if (navUser) navUser.classList.add('d-none');
        }
    });
    
    // ========== FUNGSI TAMBAHAN ==========
    // Validasi input nomor telepon hanya angka
    document.getElementById('register-phone')?.addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '');
    });
    
    // Auto kapitalisasi nama
    document.getElementById('register-name')?.addEventListener('input', function(e) {
        // Biarkan user mengetik, hanya format saat blur
    });
    
    document.getElementById('register-name')?.addEventListener('blur', function(e) {
        if (this.value) {
            // Format: Dr. Budi Santoso, M.Pd
            // Biarkan user mengetik sesuai keinginan
        }
    });
    
    // Auto lowercase email
    document.getElementById('register-email')?.addEventListener('blur', function(e) {
        if (this.value) {
            this.value = this.value.toLowerCase();
        }
    });
    
    // Enter untuk submit form
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.target.matches('textarea')) {
            e.preventDefault();
            const submitBtn = document.getElementById('register-submit-btn');
            if (submitBtn && !submitBtn.disabled) {
                submitBtn.click();
            }
        }
    });
    
    // Prevent form resubmission on refresh
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }
    </script>
</body>
</html>