<style>
    .file-preview {
        margin-top: 10px;
        min-height: 0;
    }
    .file-preview img {
        max-width: 180px;
        max-height: 180px;
        border-radius: 8px;
        border: 2px solid #e2e8f0;
        object-fit: cover;
        display: block;
    }
    .file-error {
        margin-top: 6px;
        font-size: 0.85rem;
        color: #e53e3e;
        font-weight: 500;
        min-height: 0;
    }
</style>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const MAX_SIZE    = 2 * 1024 * 1024;
        const ALLOWED_EXT = ['jpg', 'jpeg', 'png'];
        const ALLOWED_MIME = ['image/jpeg', 'image/png'];

        const isId = document.documentElement.lang === 'id' || document.cookie.includes('site_lang=id');

        const msg = {
            invalidType : isId
            ? 'Format tidak didukung. Hanya JPG dan PNG.'
            : 'Invalid format. Only JPG and PNG allowed.',
            tooLarge    : isId
            ? 'Ukuran file melebihi batas 2 MB.'
            : 'File size exceeds the 2 MB limit.',
        };

        function getExt(name) {
            return name.split('.').pop().toLowerCase();
        }

        function handle(input) {
            const previewId = input.dataset.preview;
            const errorId   = 'error-' + previewId.replace('preview-', '');

            const previewEl = document.getElementById(previewId);
            const errorEl   = document.getElementById(errorId);

        // Reset dulu
        previewEl.innerHTML  = '';
        errorEl.textContent  = '';
        input.style.outline  = '';

        const file = input.files[0];
        if (!file) return true;

        const ext = getExt(file.name);

        if (!ALLOWED_MIME.includes(file.type) || !ALLOWED_EXT.includes(ext)) {
            errorEl.textContent = msg.invalidType;
            input.style.outline = '2px solid #e53e3e';
            input.value = '';
            return false;
        }

        if (file.size > MAX_SIZE) {
            errorEl.textContent = msg.tooLarge;
            input.style.outline = '2px solid #e53e3e';
            input.value = '';
            return false;
        }

        // Tampilkan thumbnail
        const reader = new FileReader();
        reader.onload = function (e) {
            const img    = document.createElement('img');
            img.src      = e.target.result;
            img.alt      = file.name;
            img.style.cssText = 'max-width:180px;max-height:180px;border-radius:8px;border:2px solid #e2e8f0;object-fit:cover;margin-top:8px;display:block;';
            previewEl.appendChild(img);
        };
        reader.readAsDataURL(file);

        input.style.outline = '2px solid #48bb78';
        return true;
    }

    // Event change tiap input file
    document.querySelectorAll('.file-input').forEach(function (input) {
        input.addEventListener('change', function () {
            handle(this);
        });
    });

    // Validasi ulang saat submit
    const form = document.querySelector('.registration-form');
    if (form) {
        form.addEventListener('submit', function (e) {
            let allValid = true;
            document.querySelectorAll('.file-input').forEach(function (input) {
                if (!handle(input)) allValid = false;
            });
            if (!allValid) {
                e.preventDefault();
                const firstErr = document.querySelector('.file-error:not(:empty)');
                if (firstErr) firstErr.scrollIntoView({ behavior: 'smooth', block: 'center' });
                return;
            }

            const submitButton = form.querySelector('.btn-register');
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.textContent = isId ? 'Mengirim...' : 'Submitting...';
            }

            const loading = document.getElementById('registrationLoading');
            if (loading) {
                loading.hidden = false;
                loading.classList.add('is-open');
                document.body.classList.add('is-registration-modal-open');
            }
        });
    }

    const status = document.getElementById('registrationStatus');
    if (status) {
        status.focus({ preventScroll: true });
        status.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }

    const successModal = document.getElementById('registrationSuccessModal');
    if (successModal) {
        const closeSuccessModal = function () {
            successModal.classList.remove('is-open');
            document.body.classList.remove('is-registration-modal-open');
            setTimeout(function () {
                successModal.hidden = true;
            }, 180);
        };

        successModal.hidden = false;
        requestAnimationFrame(function () {
            successModal.classList.add('is-open');
            document.body.classList.add('is-registration-modal-open');
            const okButton = successModal.querySelector('[data-registration-modal-close]');
            if (okButton) okButton.focus({ preventScroll: true });
        });

        if (window.history && window.history.replaceState) {
            const cleanUrl = new URL(window.location.href);
            cleanUrl.searchParams.delete('status');
            window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search + cleanUrl.hash);
        }

        successModal.addEventListener('click', function (event) {
            if (event.target === successModal || event.target.closest('[data-registration-modal-close]')) {
                closeSuccessModal();
            }
        });

        document.addEventListener('keydown', function (event) {
            if (!successModal.hidden && event.key === 'Escape') {
                closeSuccessModal();
            }
        });
    }
});
</script>
<main class="page-shell page-shell--flush">

    <!-- HERO -->
    <section class="about-hero">

        <div class="container">

            <h1 class="about-hero__title">
                <?php echo tr(
                    'Registration Form',
                    'Formulir Pendaftaran'
                ); ?>
            </h1>

            <p class="about-hero__sub">
                <?php echo tr(
                    'Complete your registration for UK Trail Run 2026.',
                    'Lengkapi pendaftaran untuk UK Trail Run 2026.'
                ); ?>
            </p>

        </div>

    </section>

    <!-- REGISTRATION -->
    <section class="registration-section">

        <div class="container">

            <?php if (isset($_GET['status']) && $_GET['status'] === 'success') { ?>
                <div class="registration-status registration-status--success fade-up visible"
                     id="registrationStatus"
                     role="status"
                     aria-live="polite"
                     tabindex="-1">
                    <span class="registration-status__icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24">
                            <path d="M20 6 9 17l-5-5"></path>
                        </svg>
                    </span>

                    <div class="registration-status__body">
                        <strong>
                            <?php echo tr('Submit successful', 'Submit berhasil'); ?>
                        </strong>

                        <p>
                            <?php echo tr(
                                'Your registration has been received and will be verified by the admin.',
                                'Pendaftaran Anda sudah diterima dan akan diverifikasi oleh admin.'
                            ); ?>
                        </p>
                    </div>
                </div>
            <?php } elseif (isset($_GET['status']) && $_GET['status'] === 'error_captcha') { ?>
                <div class="registration-status fade-up visible"
                     id="registrationStatus"
                     role="alert"
                     aria-live="assertive"
                     tabindex="-1"
                     style="background-color: #fef2f2; border-color: #fca5a5; color: #991b1b; padding: 1rem; border-radius: 8px; margin-bottom: 2rem; display: flex; gap: 1rem;">
                    <span class="registration-status__icon" aria-hidden="true" style="background-color: #fee2e2; color: #ef4444; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">
                        <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="8" x2="12" y2="12"></line>
                            <line x1="12" y1="16" x2="12.01" y2="16"></line>
                        </svg>
                    </span>

                    <div class="registration-status__body">
                        <strong>
                            <?php echo tr('Submit failed', 'Submit gagal'); ?>
                        </strong>

                        <p>
                            <?php echo tr(
                                'reCAPTCHA verification failed. Please try again.',
                                'Verifikasi reCAPTCHA gagal. Silakan coba lagi.'
                            ); ?>
                        </p>
                    </div>
                </div>
            <?php } ?>

            <form action="<?php echo h(BASE_URL . 'submit_registration.php'); ?>"
            method="POST"
            enctype="multipart/form-data"
            class="registration-form fade-up delay-2">

            <input type="hidden" name="lang" value="<?php echo h(current_lang()); ?>">

            <div class="form-grid">

                <!-- FULL NAME -->
                <div class="form-group">

                    <label>
                        <?php echo tr(
                            'Full Name',
                            'Nama Lengkap'
                        ); ?>
                    </label>

                    <input type="text"
                    name="full_name"
                    required>

                </div>

                <!-- GENDER -->
                <div class="form-group">

                    <label>
                        <?php echo tr(
                            'Gender',
                            'Jenis Kelamin'
                        ); ?>
                    </label>

                    <select name="gender" required>

                        <option value="">
                            <?php echo tr(
                                'Select Gender',
                                'Pilih Gender'
                            ); ?>
                        </option>

                        <option>
                            <?php echo tr(
                                'Male',
                                'Laki-laki'
                            ); ?>
                        </option>

                        <option>
                            <?php echo tr(
                                'Female',
                                'Perempuan'
                            ); ?>
                        </option>

                    </select>

                </div>

                <!-- DATE -->
                <div class="form-group">

                    <label>
                        <?php echo tr(
                            'Date of Birth',
                            'Tanggal Lahir'
                        ); ?>
                    </label>

                    <input type="date"
                    name="birth_date"
                    required>

                </div>

                <!-- BLOOD -->
                <div class="form-group">

                    <label>
                        <?php echo tr(
                            'Blood Type',
                            'Golongan Darah'
                        ); ?>
                    </label>

                    <select name="blood_type" required>

                        <option value="">
                            <?php echo tr(
                                'Select Blood Type',
                                'Pilih Golongan Darah'
                            ); ?>
                        </option>

                        <option>A</option>
                        <option>B</option>
                        <option>AB</option>
                        <option>O</option>

                    </select>

                </div>

                <!-- EMAIL -->
                <div class="form-group">

                    <label>Email</label>

                    <input type="email"
                    name="email"
                    required>

                </div>

                <!-- WHATSAPP -->
                <div class="form-group">

                    <label>WhatsApp</label>

                    <input type="text"
                    name="whatsapp"
                    required>

                </div>

                <!-- ADDRESS -->
                <div class="form-group full-width">

                    <label>
                        <?php echo tr(
                            'Address',
                            'Alamat'
                        ); ?>
                    </label>

                    <textarea name="address"
                    rows="4"
                    required></textarea>

                </div>

                <!-- DISTANCE -->
                <div class="form-group">

                    <label>
                        <?php echo tr(
                            'Distance Category',
                            'Kategori Jarak'
                        ); ?>
                    </label>

                    <select name="distance_category"
                    required>

                    <option value="">
                        <?php echo tr(
                            'Select Distance',
                            'Pilih Jarak'
                        ); ?>
                    </option>

                    <option>7K</option>
                    <option>9K</option>

                </select>

            </div>

            <!-- CATEGORY -->
            <div class="form-group">

                <label>
                    <?php echo tr(
                        'Participant Category',
                        'Kategori Peserta'
                    ); ?>
                </label>

                <select name="participant_category"
                required>

                <option value="">
                    <?php echo tr(
                        'Select Category',
                        'Pilih Kategori'
                    ); ?>
                </option>

                <option>
                    <?php echo tr(
                        'General',
                        'Umum'
                    ); ?>
                </option>

                <option>
                    <?php echo tr(
                        'Student',
                        'Pelajar'
                    ); ?>
                </option>

            </select>

        </div>

        <!-- JERSEY -->
        <div class="form-group">

            <label>
                <?php echo tr(
                    'Jersey Size',
                    'Ukuran Jersey'
                ); ?>
            </label>

            <select name="jersey_size"
            required>

            <option value="">
                <?php echo tr(
                    'Select Jersey Size',
                    'Pilih Ukuran Jersey'
                ); ?>
            </option>

            <option>XS</option>
            <option>S</option>
            <option>M</option>
            <option>L</option>
            <option>XL</option>
            <option>XXL</option>

        </select>

    </div>

    <!-- EMERGENCY NAME -->
    <div class="form-group">

        <label>
            <?php echo tr(
                'Emergency Contact Name',
                'Nama Kontak Darurat'
            ); ?>
        </label>

        <input type="text"
        name="emergency_name"
        required>

    </div>

    <!-- EMERGENCY PHONE -->
    <div class="form-group">

        <label>
            <?php echo tr(
                'Emergency Contact Number',
                'Nomor Kontak Darurat'
            ); ?>
        </label>

        <input type="text"
        name="emergency_phone"
        required>

    </div>

    <!-- MEDICAL -->
    <div class="form-group">

        <label>
            <?php echo tr(
                'Medical Notes (Optional)',
                'Catatan Medis (Opsional)'
            ); ?>
        </label>

        <input type="text"
        name="medical_notes">

    </div>

    <!-- KTP -->
    <div class="form-group">
        <label><?php echo tr('Upload KTP / Student Card', 'Upload KTP / Kartu Pelajar'); ?></label>
        <input type="file" name="ktp_file" accept=".jpg,.jpeg,.png" required
        class="file-input" data-preview="preview-ktp">
        <small>JPG, PNG - Max 2MB</small>
        <div class="file-error" id="error-ktp"></div>
        <div class="file-preview" id="preview-ktp"></div>
    </div>

    <!-- PHOTO -->
    <div class="form-group">
        <label><?php echo tr('Upload Photo', 'Upload Foto'); ?></label>
        <input type="file" name="photo_file" accept=".jpg,.jpeg,.png" required
        class="file-input" data-preview="preview-photo">
        <small>JPG, PNG - Max 2MB</small>
        <div class="file-error" id="error-photo"></div>
        <div class="file-preview" id="preview-photo"></div>
    </div>

    <!-- PAYMENT -->
    <div class="form-group full-width">
        <label><?php echo tr('Upload Payment Proof', 'Upload Bukti Pembayaran'); ?></label>
        <input type="file" name="payment_file" accept=".jpg,.jpeg,.png" required
        class="file-input" data-preview="preview-payment">
        <small>JPG, PNG - Max 2MB</small>
        <div class="file-error" id="error-payment"></div>
        <div class="file-preview" id="preview-payment"></div>
    </div>

    <!-- PAYMENT -->
    <div class="payment-info">

        <h4>
            <?php echo tr(
                'Payment Information',
                'Informasi Pembayaran'
            ); ?>
        </h4>

        <p>
            Bank BCA : 5365101687
            <br>
            A/N Mela

            <br><br>

            <small>

                <?php echo tr(
                    'Please upload valid payment proof. Registration will be verified manually by admin.',
                    'Harap upload bukti pembayaran yang valid. Pendaftaran akan diverifikasi manual oleh admin.'
                ); ?>

            </small>

        </p>

    </div>

    <!-- BIB -->
    <div class="payment-info">

        <h4>
            <?php echo tr(
                'Race BIB Information',
                'Informasi BIB Peserta'
            ); ?>
        </h4>

        <p>

            <?php echo tr(
                'BIB number will be generated automatically after registration verification.',
                'Nomor BIB akan dibuat otomatis setelah verifikasi pendaftaran.'
            ); ?>

        </p>

    </div>

    <!-- CAPTCHA -->
    <div class="form-group full-width">
        <label>
            <?php echo tr('Security Verification', 'Verifikasi Keamanan'); ?>
        </label>
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        <div class="g-recaptcha" data-sitekey="6Ld5d_IsAAAAAGIaWSHa5iJT2EZiYWsqyll0KZsg"></div>
    </div>

    <!-- AGREEMENT -->
    <div class="agreement">

        <label>

            <input type="checkbox"
            required>

            <?php echo tr(
                'I agree to follow all race regulations and understand the risks during the event.',
                'Saya setuju mengikuti seluruh peraturan lomba dan memahami risiko selama acara berlangsung.'
            ); ?>

        </label>

    </div>

    <!-- BUTTON -->
    <button type="submit"
    class="btn btn--primary btn-register">

    <?php echo tr(
        'Register Now',
        'Daftar Sekarang'
    ); ?>

</button>

</form>

</div>

</section>

</main>

<div class="registration-modal registration-modal--loading"
     id="registrationLoading"
     role="alert"
     aria-live="assertive"
     hidden>
    <div class="registration-modal__card registration-modal__card--loading">
        <span class="registration-spinner" aria-hidden="true"></span>
        <strong><?php echo tr('Submitting...', 'Mengirim...'); ?></strong>
        <p><?php echo tr('Please wait while your registration is being processed.', 'Mohon tunggu, pendaftaran Anda sedang diproses.'); ?></p>
    </div>
</div>

<?php if (isset($_GET['status']) && $_GET['status'] === 'success') { ?>
    <div class="registration-modal registration-modal--success"
         id="registrationSuccessModal"
         role="dialog"
         aria-modal="true"
         aria-labelledby="registrationSuccessTitle"
         hidden>
        <div class="registration-modal__card">
            <span class="registration-modal__icon" aria-hidden="true">
                <svg viewBox="0 0 24 24">
                    <path d="M20 6 9 17l-5-5"></path>
                </svg>
            </span>

            <h2 id="registrationSuccessTitle">Submit Berhasil</h2>

            <p>
                <?php echo tr(
                    'Your registration has been received and will be verified by the admin.',
                    'Pendaftaran Anda sudah diterima dan akan diverifikasi oleh admin.'
                ); ?>
            </p>

            <button class="btn btn--primary registration-modal__button"
                    type="button"
                    data-registration-modal-close>
                OK
            </button>
        </div>
    </div>
<?php } ?>
