<!--
   Copyright 2025-2026 AIIrondev

   Licensed under the Inventarsystem EULA (Endbenutzer-Lizenzvertrag).
   See Legal/LICENSE for the full license text.
   Unauthorized commercial use, SaaS hosting, or removal of branding is prohibited.
   For commercial licensing inquiries: https://github.com/AIIrondev
-->
{% extends "base.html" %}

{% block title %}Register{% endblock %}

{% block content %}
<div class="container">
    <div class="header-section">
        <h1>Neuen Benutzer registrieren</h1>
        <p class="subtitle">Erstellen Sie ein neues Benutzerkonto und legen Sie Zugriffsrechte fest</p>
    </div>

    <div class="flash-container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="flash {{ category }}">
                        <span class="flash-icon">{% if category == 'success' %}✓{% else %}!{% endif %}</span>
                        <span class="flash-message">{{ message }}</span>
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
    </div>

    <div class="content">
        <div class="form-card">
            <form method="POST" action="{{ url_for('register') }}">
                <div class="form-group">
                    <label for="name">Vorname</label>
                    <div class="input-container">
                        <span class="input-icon">👤</span>
                        <input type="text" id="name" name="name" placeholder="Geben Sie den Vornamen ein" required onchange="generateUsername()" oninput="generateUsername()">
                    </div>
                    <label for="last-name">Nachname</label>
                    <div class="input-container">
                        <span class="input-icon">👤</span>
                        <input type="text" id="last-name" name="last-name" placeholder="Geben Sie den Nachnamen ein" required onchange="generateUsername()" oninput="generateUsername()">
                    </div>
                    <label for="username">Benutzername <span style="color: #9ca3af;">(wird automatisch generiert)</span></label>
                    <div class="input-container">
                        <span class="input-icon">👤</span>
                        <input type="text" id="username" name="username" placeholder="Automatisch aus Name und Nachname" readonly style="background-color: #f3f4f6; cursor: not-allowed;">
                    </div>
                    <p class="anonymize-hint">Klarnamen werden nur zur Erzeugung des Benutzernamens als Kürzel (z.B. SimFri) verwendet; bei Kollision wird automatisch ein Buchstabe mehr genommen.</p>
                </div>
                
                <div class="form-group">
                    <label for="password">Passwort</label>
                    <div class="password-rules" id="password-rules" aria-live="polite">
                        <p class="password-rules-title">Passwort-Anforderungen (live):</p>
                        <ul>
                            <li id="pw-rule-length" class="pw-rule">Mindestens 12 Zeichen</li>
                            <li id="pw-rule-lower" class="pw-rule">Mindestens ein Kleinbuchstabe</li>
                            <li id="pw-rule-upper" class="pw-rule">Mindestens ein Grossbuchstabe</li>
                            <li id="pw-rule-digit" class="pw-rule">Mindestens eine Zahl</li>
                            <li id="pw-rule-symbol" class="pw-rule">Mindestens ein Sonderzeichen</li>
                        </ul>
                    </div>
                    <div class="input-container">
                        <span class="input-icon">🔒</span>
                        <input type="password" id="password" name="password" placeholder="Geben Sie ein sicheres Passwort ein" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="permission-preset">Berechtigungs-Preset</label>
                    <select id="permission-preset" name="permission_preset" class="form-select">
                        {% for preset_key, preset in permission_presets.items() %}
                        <option value="{{ preset_key }}">{{ preset.label }}</option>
                        {% endfor %}
                    </select>

                    <label style="display:flex; align-items:center; gap:8px; margin-top:12px; color:#1f2937;">
                        <input type="checkbox" id="use-custom-permissions" name="use_custom_permissions" style="width:auto;">
                        Individuelle Berechtigungen statt Preset setzen
                    </label>

                    <div id="custom-permissions" style="display:none; margin-top:12px;">
                        <div class="permission-panels">
                            <div class="permission-panel">
                                <h4>Aktionsrechte</h4>
                                {% for action_key, action_label in permission_action_options %}
                                <label class="permission-check">
                                    <input type="checkbox" class="permission-action-checkbox" name="action_{{ action_key }}">
                                    <span>{{ action_label }}</span>
                                </label>
                                {% endfor %}
                            </div>
                            <div class="permission-panel">
                                <h4>Seitenrechte</h4>
                                {% for endpoint_name, endpoint_label in permission_page_options %}
                                <label class="permission-check">
                                    <input type="checkbox" class="permission-page-checkbox" name="page_{{ endpoint_name }}">
                                    <span>{{ endpoint_label }}</span>
                                </label>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group form-actions">
                    <button type="submit" class="action-button register-button">Benutzer registrieren</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
:root {
    --primary-color: #3498db;
    --primary-dark: #2980b9;
    --success-color: #2ecc71;
    --error-color: #e74c3c;
    --text-color: var(--ui-text);
    --light-bg: #f9f9f9;
    --border-radius: 8px;
    --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    --transition: all 0.3s ease;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: var(--light-bg);
    margin: 0;
    padding: 0;
    color: var(--text-color);
    line-height: 1.6;
}

.container {
    max-width: 800px;
    margin: 2rem auto;
    padding: 0 1.5rem;
}

.header-section {
    text-align: center;
    margin-bottom: 2rem;
    padding-bottom: 1.5rem;
    border-bottom: 1px solid #eee;
}

.header-section h1 {
    font-size: 2.5rem;
    margin-bottom: 0.5rem;
    color: var(--primary-color);
}

.subtitle {
    font-size: 1.1rem;
    color: #777;
    margin-top: 0;
}

.content {
    background-color: var(--ui-surface);
    padding: 2rem;
    border-radius: var(--border-radius);
    box-shadow: var(--shadow);
    margin-bottom: 2rem;
}

.form-card {
    max-width: 500px;
    margin: 0 auto;
}

.form-group {
    margin-bottom: 1.5rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    color: var(--primary-dark);
}

.input-container {
    position: relative;
}

.input-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: #aaa;
    font-size: 1.2rem;
}

input[type="text"],
input[type="password"],
.form-select {
    width: 100%;
    padding: 0.8rem 1rem 0.8rem 3rem;
    border: 1px solid #ddd;
    border-radius: var(--border-radius);
    font-size: 1rem;
    transition: var(--transition);
    box-sizing: border-box;
}

input[type="text"]:focus,
input[type="password"]:focus,
.form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
    outline: none;
}

.form-select {
    padding-left: 1rem;
}

input::placeholder {
    color: #aaa;
}

.form-actions {
    margin-top: 2rem;
}

.action-button {
    background-color: var(--primary-color);
    color: white;
    border: none;
    padding: 0.8rem 1.5rem;
    border-radius: 30px;
    cursor: pointer;
    font-weight: 600;
    transition: var(--transition);
    width: 100%;
    font-size: 1rem;
}

.action-button:hover {
    background-color: var(--primary-dark);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.register-button {
    background-color: var(--success-color);
}

.register-button:hover {
    background-color: #27ae60;
}

.navigation-buttons {
    text-align: center;
    margin: 1.5rem 0;
}

.back-button {
    display: inline-flex;
    align-items: center;
    color: var(--primary-color);
    text-decoration: none;
    font-weight: 500;
    transition: var(--transition);
    padding: 0.5rem 1rem;
    border-radius: var(--border-radius);
}

.back-button:hover {
    background-color: rgba(52, 152, 219, 0.1);
}

.back-icon {
    margin-right: 0.5rem;
    font-size: 1.2rem;
}

.flash-container {
    margin-bottom: 1.5rem;
}

.flash {
    display: flex;
    align-items: center;
    padding: 1rem;
    margin-bottom: 1rem;
    border-radius: var(--border-radius);
    animation: fadeIn 0.3s ease-in-out;
}

.flash-icon {
    margin-right: 0.8rem;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.3);
}

.flash.success {
    background-color: #d4edda;
    color: #155724;
    border-left: 4px solid var(--success-color);
}

.flash.error {
    background-color: #f8d7da;
    color: #721c24;
    border-left: 4px solid var(--error-color);
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
    .container {
        padding: 0 1rem;
        margin: 1rem auto;
    }
    
    .content {
        padding: 1.5rem;
    }
    
    .header-section h1 {
        font-size: 2rem;
    }
}

.password-rules {
    margin-bottom: 10px;
    padding: 10px 12px;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    background: var(--ui-surface-soft);
}

.password-rules-title {
    margin: 0 0 8px;
    font-weight: 700;
    color: #1f2937;
    font-size: 0.92rem;
}

.password-rules ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

.pw-rule {
    position: relative;
    padding-left: 22px;
    margin: 5px 0;
    color: #b91c1c;
    font-size: 0.9rem;
}

.pw-rule::before {
    content: '✗';
    position: absolute;
    left: 0;
    top: 0;
    font-weight: 700;
}

.pw-rule.ok {
    color: #166534;
}

.pw-rule.ok::before {
    content: '✓';
}

.anonymize-hint {
    margin-top: 10px;
    margin-bottom: 0;
    background: #f0f9ff;
    border: 1px solid #bae6fd;
    border-radius: 8px;
    padding: 10px 12px;
    color: #0c4a6e;
    font-size: 0.92rem;
}

.permission-panels {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 12px;
}

.permission-panel {
    border: 1px solid #d1d5db;
    border-radius: 8px;
    padding: 10px;
    background: var(--ui-surface-soft);
}

.permission-panel h4 {
    margin: 0 0 8px;
    font-size: 1rem;
    color: #1f2937;
}

.permission-check {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 4px 0;
    color: #1f2937;
}
</style>

<script>
// Function to generate username from first and last name (helper function)
function cleanNameForUsername(text) {
    if (!text) return '';
    // Remove special characters, convert umlauts, lowercase
    let cleaned = text
        .replace(/[^a-zA-Zäöüß\s-]/g, '')
        .trim()
        .toLowerCase();
    
    // Convert German umlauts to ASCII
    cleaned = cleaned
        .replace(/ä/g, 'ae')
        .replace(/ö/g, 'oe')
        .replace(/ü/g, 'ue')
        .replace(/ß/g, 'ss');
    
    return cleaned;
}

// Generate username from name and last_name fields
function generateUsername() {
    const firstName = cleanNameForUsername(document.getElementById('name').value || '');
    const lastName = cleanNameForUsername(document.getElementById('last-name').value || '');
    let username = '';
    
    if (firstName && lastName) {
        username = (firstName.slice(0, 3) + lastName.slice(0, 3));
    } else if (firstName) {
        username = firstName.slice(0, 6);
    } else if (lastName) {
        username = lastName.slice(0, 6);
    }
    
    // Set the username field
    const usernameField = document.getElementById('username');
    if (usernameField) {
        usernameField.value = username || '';
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const permissionPresets = {{ permission_presets | tojson }};
    const presetSelect = document.getElementById('permission-preset');
    const useCustomPermissions = document.getElementById('use-custom-permissions');
    const customPermissions = document.getElementById('custom-permissions');

    function applyPresetToPermissionForm(presetKey) {
        const preset = permissionPresets[presetKey] || {};
        const actionDefaults = preset.actions || {};
        const pageDefaults = preset.pages || {};

        document.querySelectorAll('.permission-action-checkbox').forEach(function (checkbox) {
            const key = checkbox.name.replace('action_', '');
            checkbox.checked = !!actionDefaults[key];
        });

        document.querySelectorAll('.permission-page-checkbox').forEach(function (checkbox) {
            const key = checkbox.name.replace('page_', '');
            checkbox.checked = !!pageDefaults[key];
        });
    }

    function toggleCustomPermissions() {
        if (!useCustomPermissions || !customPermissions) {
            return;
        }
        customPermissions.style.display = useCustomPermissions.checked ? 'block' : 'none';
    }

    if (presetSelect) {
        presetSelect.addEventListener('change', function () {
            applyPresetToPermissionForm(this.value);
        });
        applyPresetToPermissionForm(presetSelect.value);
    }

    if (useCustomPermissions) {
        useCustomPermissions.addEventListener('change', toggleCustomPermissions);
        toggleCustomPermissions();
    }

    const passwordInput = document.getElementById('password');
    const passwordRules = {
        length: document.getElementById('pw-rule-length'),
        lower: document.getElementById('pw-rule-lower'),
        upper: document.getElementById('pw-rule-upper'),
        digit: document.getElementById('pw-rule-digit'),
        symbol: document.getElementById('pw-rule-symbol')
    };

    function setRuleState(node, ok) {
        if (!node) {
            return;
        }
        node.classList.toggle('ok', !!ok);
    }

    function updatePasswordRules() {
        if (!passwordInput) {
            return;
        }

        const value = String(passwordInput.value || '');
        setRuleState(passwordRules.length, value.length >= 12);
        setRuleState(passwordRules.lower, /[a-z]/.test(value));
        setRuleState(passwordRules.upper, /[A-Z]/.test(value));
        setRuleState(passwordRules.digit, /[0-9]/.test(value));
        setRuleState(passwordRules.symbol, /[^A-Za-z0-9]/.test(value));
    }

    if (passwordInput) {
        passwordInput.addEventListener('input', updatePasswordRules);
        passwordInput.addEventListener('blur', updatePasswordRules);
        updatePasswordRules();
    }
});
</script>
{% endblock %}