<?php get_header(); ?>

<div class="container site-main">
    <div class="content-area">
        <div class="bewerbung-container">

            <header class="page-header">
                <h1 class="page-title">
                    <i class="fas fa-clipboard-list"></i>
                    <?php echo esc_html( get_theme_mod('mm_bewerbung_title', __('Bewirb dich bei uns!', 'minecraft-modern-theme')) ); ?>
                </h1>
                <p class="page-description">
                    <?php echo esc_html( get_theme_mod('mm_bewerbung_desc', __('Du möchtest Teil unseres Teams werden? Füll das Formular aus und wir melden uns bei dir.', 'minecraft-modern-theme')) ); ?>
                </p>
            </header>

            <?php if ( ! get_theme_mod('mm_bewerbung_enabled', false) ) : ?>
                <div class="bewerbung-disabled">
                    <i class="fas fa-lock"></i>
                    <p><?php _e('Bewerbungen sind momentan nicht möglich.', 'minecraft-modern-theme'); ?></p>
                </div>
            <?php else : ?>

            <div id="bewerbung-success" class="bewerbung-success" style="display:none;">
                <i class="fas fa-check-circle"></i>
                <p id="bewerbung-success-msg"></p>
            </div>

            <form id="bewerbung-form" class="bewerbung-form" novalidate>
                <?php wp_nonce_field('mm_bewerbung_nonce', 'mm_bew_nonce_field'); ?>

                <div class="bew-grid">

                    <!-- Minecraft Username -->
                    <div class="bew-field">
                        <label for="bew_mc_name" class="bew-label">
                            <i class="fas fa-gamepad"></i>
                            <?php _e('Minecraft Username', 'minecraft-modern-theme'); ?>
                            <span class="bew-required">*</span>
                        </label>
                        <div class="bew-mc-wrap">
                            <input type="text" id="bew_mc_name" name="mc_name"
                                   class="bew-input" required maxlength="16"
                                   placeholder="z.B. Steve_123"
                                   autocomplete="off">
                            <div class="bew-mc-avatar" id="bew-mc-avatar">
                                <img src="" alt="" id="bew-mc-avatar-img" style="display:none;">
                                <i class="fas fa-user" id="bew-mc-avatar-placeholder"></i>
                            </div>
                        </div>
                        <p class="bew-hint"><?php _e('Dein exakter Minecraft-Username (Groß-/Kleinschreibung beachten)', 'minecraft-modern-theme'); ?></p>
                    </div>

                    <!-- Discord Username -->
                    <div class="bew-field">
                        <label for="bew_discord" class="bew-label">
                            <i class="fab fa-discord"></i>
                            <?php _e('Discord Username', 'minecraft-modern-theme'); ?>
                            <span class="bew-required">*</span>
                        </label>
                        <input type="text" id="bew_discord" name="discord"
                               class="bew-input" required maxlength="50"
                               placeholder="z.B. Steve#1234 oder @steve">
                        <p class="bew-hint"><?php _e('Dein Discord-Name damit wir dich erreichen können', 'minecraft-modern-theme'); ?></p>
                    </div>

                    <!-- Alter -->
                    <div class="bew-field bew-field--small">
                        <label for="bew_alter" class="bew-label">
                            <i class="fas fa-birthday-cake"></i>
                            <?php _e('Alter', 'minecraft-modern-theme'); ?>
                            <span class="bew-required">*</span>
                        </label>
                        <input type="number" id="bew_alter" name="alter"
                               class="bew-input" required min="1" max="99"
                               placeholder="z.B. 16">
                        <?php
                        $min = absint(get_theme_mod('mm_bewerbung_min_alter', 14));
                        if ($min > 0) :
                        ?>
                        <p class="bew-hint"><?php printf( __('Mindestalter: %d Jahre', 'minecraft-modern-theme'), $min ); ?></p>
                        <?php endif; ?>
                    </div>

                </div><!-- .bew-grid -->

                <!-- Warum mitspielen -->
                <div class="bew-field">
                    <label for="bew_warum" class="bew-label">
                        <i class="fas fa-question-circle"></i>
                        <?php _e('Warum möchtest du mitspielen?', 'minecraft-modern-theme'); ?>
                        <span class="bew-required">*</span>
                    </label>
                    <textarea id="bew_warum" name="warum" class="bew-textarea" required
                              rows="4" maxlength="1000"
                              placeholder="<?php esc_attr_e('Erzähl uns warum du auf unseren Server möchtest und was du dir davon erhoffst...', 'minecraft-modern-theme'); ?>"></textarea>
                    <div class="bew-char-count"><span id="warum-count">0</span>/1000</div>
                </div>

                <!-- Erfahrung / Vorstellung -->
                <div class="bew-field">
                    <label for="bew_erfahrung" class="bew-label">
                        <i class="fas fa-star"></i>
                        <?php _e('Erfahrung & Vorstellung', 'minecraft-modern-theme'); ?>
                        <span class="bew-required">*</span>
                    </label>
                    <textarea id="bew_erfahrung" name="erfahrung" class="bew-textarea" required
                              rows="5" maxlength="2000"
                              placeholder="<?php esc_attr_e('Stell dich kurz vor: Wie lange spielst du Minecraft? Welche Erfahrungen bringst du mit? Was macht dich besonders?', 'minecraft-modern-theme'); ?>"></textarea>
                    <div class="bew-char-count"><span id="erfahrung-count">0</span>/2000</div>
                </div>

                <!-- Fehler-Meldung -->
                <div id="bewerbung-error" class="bewerbung-error" style="display:none;">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span id="bewerbung-error-msg"></span>
                </div>

                <!-- Submit -->
                <div class="bew-submit-wrap">
                    <button type="submit" id="bewerbung-submit" class="bew-submit-btn">
                        <i class="fas fa-paper-plane"></i>
                        <?php _e('Bewerbung absenden', 'minecraft-modern-theme'); ?>
                    </button>
                    <p class="bew-submit-hint">
                        <i class="fas fa-shield-alt"></i>
                        <?php _e('Mit * markierte Felder sind Pflichtfelder. Deine Daten werden nur intern gespeichert.', 'minecraft-modern-theme'); ?>
                    </p>
                </div>

            </form>

            <?php endif; ?>

        </div><!-- .bewerbung-container -->
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var form       = document.getElementById('bewerbung-form');
    var submitBtn  = document.getElementById('bewerbung-submit');
    var errorBox   = document.getElementById('bewerbung-error');
    var errorMsg   = document.getElementById('bewerbung-error-msg');
    var successBox = document.getElementById('bewerbung-success');
    var successMsg = document.getElementById('bewerbung-success-msg');

    if (!form) return;

    // ── Minecraft Avatar live laden ──
    var mcInput    = document.getElementById('bew_mc_name');
    var avatarImg  = document.getElementById('bew-mc-avatar-img');
    var avatarIcon = document.getElementById('bew-mc-avatar-placeholder');
    var avatarTimer;

    if (mcInput) {
        mcInput.addEventListener('input', function() {
            clearTimeout(avatarTimer);
            var val = this.value.trim();
            if (val.length >= 3) {
                avatarTimer = setTimeout(function() {
                    var url = 'https://mc-heads.net/avatar/' + encodeURIComponent(val) + '/40';
                    avatarImg.src = url;
                    avatarImg.style.display = 'block';
                    avatarIcon.style.display = 'none';
                    avatarImg.onerror = function() {
                        avatarImg.style.display = 'none';
                        avatarIcon.style.display = 'block';
                    };
                }, 600);
            } else {
                avatarImg.style.display = 'none';
                avatarIcon.style.display = 'block';
            }
        });
    }

    // ── Zeichenzähler ──
    function addCounter(textareaId, countId) {
        var ta = document.getElementById(textareaId);
        var ct = document.getElementById(countId);
        if (!ta || !ct) return;
        ta.addEventListener('input', function() {
            ct.textContent = this.value.length;
            ct.style.color = this.value.length > this.maxLength * 0.9 ? '#ff6b6b' : '';
        });
    }
    addCounter('bew_warum', 'warum-count');
    addCounter('bew_erfahrung', 'erfahrung-count');

    // ── Formular absenden ──
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        errorBox.style.display = 'none';

        var nonce = document.getElementById('mm_bew_nonce_field');
        if (!nonce) return;

        var data = new FormData();
        data.append('action', 'mm_submit_bewerbung');
        data.append('nonce',  nonce.value);
        data.append('mc_name',   document.getElementById('bew_mc_name').value.trim());
        data.append('discord',   document.getElementById('bew_discord').value.trim());
        data.append('alter',     document.getElementById('bew_alter').value.trim());
        data.append('warum',     document.getElementById('bew_warum').value.trim());
        data.append('erfahrung', document.getElementById('bew_erfahrung').value.trim());

        submitBtn.disabled = true;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo esc_js(__("Wird gesendet...","minecraft-modern-theme")); ?>';

        fetch('<?php echo esc_url(admin_url("admin-ajax.php")); ?>', {
            method: 'POST',
            body: data
        })
        .then(function(r){ return r.json(); })
        .then(function(res) {
            if (res.success) {
                form.style.display = 'none';
                successMsg.textContent = res.data.msg;
                successBox.style.display = 'flex';
                window.scrollTo({ top: successBox.offsetTop - 80, behavior: 'smooth' });
            } else {
                errorMsg.textContent = res.data.msg;
                errorBox.style.display = 'flex';
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> <?php echo esc_js(__("Bewerbung absenden","minecraft-modern-theme")); ?>';
                window.scrollTo({ top: errorBox.offsetTop - 80, behavior: 'smooth' });
            }
        })
        .catch(function() {
            errorMsg.textContent = '<?php echo esc_js(__("Verbindungsfehler. Bitte erneut versuchen.","minecraft-modern-theme")); ?>';
            errorBox.style.display = 'flex';
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> <?php echo esc_js(__("Bewerbung absenden","minecraft-modern-theme")); ?>';
        });
    });
});
</script>

<?php get_footer(); ?>