<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NeonChat — {{ "Bearbeiten" if mode == "edit" else "Neuer Charakter" }}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', system-ui, sans-serif; background: #0a0a0f; color: #e0e0e8; min-height: 100vh; }
        .container { max-width: 750px; margin: 0 auto; padding: 30px 20px; }
        h1 { font-size: 1.8rem; margin-bottom: 6px; background: linear-gradient(135deg, #ff006e, #8338ec); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .subtitle { color: #6b6b80; margin-bottom: 24px; font-size: 0.9rem; }
        .form-group { margin-bottom: 16px; }
        label { display: block; font-size: 0.85rem; color: #9b9bb0; margin-bottom: 6px; font-weight: 600; }
        label .hint { color: #4b4b60; font-weight: 400; font-size: 0.8rem; }
        input, textarea, select { width: 100%; background: #15151f; border: 1px solid #252535; border-radius: 10px; padding: 10px 14px; color: #e0e0e8; font-size: 0.9rem; font-family: inherit; outline: none; transition: border 0.15s; }
        input:focus, textarea:focus, select:focus { border-color: #8338ec; }
        textarea { resize: vertical; min-height: 60px; line-height: 1.5; }
        .row { display: flex; gap: 12px; }
        .row > div { flex: 1; }
        .btn { padding: 12px 28px; border-radius: 10px; border: none; background: linear-gradient(135deg, #8338ec, #ff006e); color: white; font-size: 1rem; cursor: pointer; font-weight: 600; transition: opacity 0.15s; }
        .btn:hover { opacity: 0.9; }
        .btn-back { background: transparent; border: 1px solid #252535; color: #6b6b80; margin-right: 10px; }
        #models { margin-top: 4px; }
        .section-header { font-size: 1rem; font-weight: 700; color: #8338ec; margin: 24px 0 12px; padding-bottom: 8px; border-bottom: 1px solid #252535; }
        .appearance-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
        .appearance-grid .form-group { margin-bottom: 12px; }
        @media (max-width: 600px) { .appearance-grid { grid-template-columns: 1fr; } }
        .portrait-preview { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; }
        .portrait-preview img { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 2px solid #8338ec; }
        .portrait-preview .info { font-size: 0.85rem; color: #6b6b80; }
    </style>
</head>
<body>
    <div class="container">
        <h1>✦ {{ "Charakter bearbeiten" if mode == "edit" else "Neuer Charakter" }}</h1>
        <p class="subtitle">Definiere Persönlichkeit, Verhalten, Hintergrund und Aussehen.</p>
        
        {% if mode == "edit" and character %}
        <div class="portrait-preview">
            <img id="portraitImg" src="/static/avatars/{{ character_filename }}.png?t={{ range(1,99999) | random }}" 
                 onerror="this.style.display='none'; document.getElementById('portraitPlaceholder').style.display='flex'"
                 style="display: block;">
            <div id="portraitPlaceholder" style="display: none; width: 80px; height: 80px; border-radius: 50%; background: #1e1e2e; align-items: center; justify-content: center; font-size: 2rem;">{{ character.avatar | default('👤') }}</div>
            <div class="info">
                <b>{{ character.name }}</b><br>
                Aktuelles Portrait. Beim Speichern und neu Generieren bleibt das Aussehen konsistent.
            </div>
        </div>
        {% endif %}

        <form id="createForm">
            <div class="section-header">Basis</div>
            <div class="row">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" id="name" placeholder="z.B. Mara" required value="{{ character.name if character else '' }}">
                </div>
                <div class="form-group" style="max-width: 80px;">
                    <label>Avatar</label>
                    <input type="text" id="avatar" value="{{ character.avatar if character else '👤' }}" maxlength="4" style="text-align: center; font-size: 1.5rem;">
                </div>
            </div>
            <div class="form-group">
                <label>Kurze Beschreibung <span class="hint">(für die Übersicht)</span></label>
                <input type="text" id="description" placeholder="z.B. Barista, 28, zynisch aber warmherzig" value="{{ character.description if character else '' }}">
            </div>

            <div class="section-header">Persönlichkeit</div>
            <div class="form-group">
                <label>Persönlichkeit</label>
                <textarea id="personality" placeholder="z.B. Trocken, sarkastisch, aber loyal.">{{ character.personality if character else '' }}</textarea>
            </div>
            <div class="form-group">
                <label>Hintergrund</label>
                <textarea id="background" placeholder="z.B. Arbeitet seit 5 Jahren in einem Café...">{{ character.background if character else '' }}</textarea>
            </div>
            <div class="form-group">
                <label>Verhalten</label>
                <textarea id="behavior" placeholder="z.B. Flucht in Wortwitze wenn nervös.">{{ character.behavior if character else '' }}</textarea>
            </div>
            <div class="form-group">
                <label>Sprachstil</label>
                <textarea id="tone" placeholder="z.B. Umgangssprachlich...">{{ character.tone if character else '' }}</textarea>
            </div>
            <div class="form-group">
                <label>Szenario <span class="hint">(optional)</span></label>
                <input type="text" id="scenario" placeholder="z.B. Du sitzt in einem Café..." value="{{ character.scenario if character else '' }}">
            </div>
            <div class="form-group">
                <label>NSFW / Soziale Regeln <span class="hint">(optional)</span></label>
                <textarea id="nsfw" placeholder="z.B. Keine Einschränkungen.">{{ character.nsfw if character else '' }}</textarea>
            </div>
            <div class="form-group">
                <label>Begrüßung <span class="hint">(erste Nachricht)</span></label>
                <textarea id="greeting" placeholder="z.B. *schaut auf* Na, wieder da?">{{ character.greeting if character else '' }}</textarea>
            </div>

            <div class="section-header">Aussehen <span class="hint" style="font-weight:400;">(für Portrait-Generierung)</span></div>
            <div class="appearance-grid">
                <div class="form-group">
                    <label>Stil</label>
                    <select id="app_style">
                        <option value="anime" {{ 'selected' if character and character.appearance.style == 'anime' else '' }}>Anime</option>
                        <option value="realistic" {{ 'selected' if character and character.appearance.style == 'realistic' else '' }}>Realistisch</option>
                        <option value="comic" {{ 'selected' if character and character.appearance.style == 'comic' else '' }}>Comic</option>
                        <option value="cartoon" {{ 'selected' if character and character.appearance.style == 'cartoon' else '' }}>Cartoon</option>
                        <option value="pixel" {{ 'selected' if character and character.appearance.style == 'pixel' else '' }}>Pixel Art</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Geschlecht</label>
                    <select id="app_gender">
                        <option value="female" {{ 'selected' if character and character.appearance.gender == 'female' else '' }}>Weiblich</option>
                        <option value="male" {{ 'selected' if character and character.appearance.gender == 'male' else '' }}>Männlich</option>
                        <option value="other" {{ 'selected' if character and character.appearance.gender == 'other' else '' }}>Divers</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Alter</label>
                    <input type="text" id="app_age" placeholder="z.B. 28" value="{{ character.appearance.age if character and character.appearance.age else '' }}">
                </div>
                <div class="form-group">
                    <label>Größe</label>
                    <input type="text" id="app_height" placeholder="z.B. 168cm" value="{{ character.appearance.height if character and character.appearance.height else '' }}">
                </div>
                <div class="form-group">
                    <label>Statur</label>
                    <input type="text" id="app_build" placeholder="z.B. schlank" value="{{ character.appearance.build if character and character.appearance.build else '' }}">
                </div>
                <div class="form-group">
                    <label>Haarfarbe</label>
                    <input type="text" id="app_hair_color" placeholder="z.B. dunkelbraun" value="{{ character.appearance.hair_color if character and character.appearance.hair_color else '' }}">
                </div>
                <div class="form-group">
                    <label>Frisur</label>
                    <input type="text" id="app_hair_style" placeholder="z.B. kurz, ungeordnet" value="{{ character.appearance.hair_style if character and character.appearance.hair_style else '' }}">
                </div>
                <div class="form-group">
                    <label>Augenfarbe</label>
                    <input type="text" id="app_eye_color" placeholder="z.B. braun" value="{{ character.appearance.eye_color if character and character.appearance.eye_color else '' }}">
                </div>
                <div class="form-group">
                    <label>Haut</label>
                    <input type="text" id="app_skin" placeholder="z.B. hell" value="{{ character.appearance.skin if character and character.appearance.skin else '' }}">
                </div>
            </div>
            <div class="form-group">
                <label>Kleidung</label>
                <input type="text" id="app_clothing" placeholder="z.B. Café-Schürze, Jeans" value="{{ character.appearance.clothing if character and character.appearance.clothing else '' }}">
            </div>
            <div class="form-group">
                <label>Besondere Merkmale</label>
                <input type="text" id="app_distinctive" placeholder="z.B. müde Augen, Augenringe" value="{{ character.appearance.distinctive if character and character.appearance.distinctive else '' }}">
            </div>

            <div class="section-header">Modell</div>
            <div class="row">
                <div class="form-group">
                    <label>Ollama Modell</label>
                    <select id="model">
                        <option value="">Default</option>
                    </select>
                    <div id="models" style="font-size: 0.8rem; color: #4b4b60;"></div>
                </div>
                <div class="form-group" style="max-width: 100px;">
                    <label>Temperatur</label>
                    <input type="number" id="temperature" value="{{ character.temperature if character and character.temperature else 0.8 }}" min="0.1" max="2.0" step="0.1">
                </div>
            </div>

            <div style="margin-top: 24px;">
                <button type="button" class="btn btn-back" onclick="location.href='/'">← Abbrechen</button>
                <button type="submit" class="btn">{{ "Speichern" if mode == "edit" else "Charakter erstellen" }}</button>
            </div>
        </form>
    </div>

    <script>
        const mode = "{{ mode }}";
        const characterFilename = "{{ character_filename if mode == 'edit' else '' }}";

        // Load models
        fetch('/api/models').then(r => r.json()).then(data => {
            const select = document.getElementById('model');
            if (data.models) {
                data.models.forEach(m => {
                    const opt = document.createElement('option');
                    opt.value = m; opt.textContent = m;
                    {% if character and character.model %}
                    if (m === "{{ character.model }}") opt.selected = true;
                    {% endif %}
                    select.appendChild(opt);
                });
            }
            if (data.error) document.getElementById('models').textContent = '⚠️ ' + data.error;
        });

        document.getElementById('createForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const data = {
                name: document.getElementById('name').value,
                avatar: document.getElementById('avatar').value,
                description: document.getElementById('description').value,
                personality: document.getElementById('personality').value,
                background: document.getElementById('background').value,
                behavior: document.getElementById('behavior').value,
                tone: document.getElementById('tone').value,
                scenario: document.getElementById('scenario').value,
                nsfw: document.getElementById('nsfw').value,
                greeting: document.getElementById('greeting').value,
                model: document.getElementById('model').value,
                temperature: parseFloat(document.getElementById('temperature').value),
                appearance: {
                    style: document.getElementById('app_style').value,
                    gender: document.getElementById('app_gender').value,
                    age: document.getElementById('app_age').value,
                    height: document.getElementById('app_height').value,
                    build: document.getElementById('app_build').value,
                    hair_color: document.getElementById('app_hair_color').value,
                    hair_style: document.getElementById('app_hair_style').value,
                    eye_color: document.getElementById('app_eye_color').value,
                    skin: document.getElementById('app_skin').value,
                    clothing: document.getElementById('app_clothing').value,
                    distinctive: document.getElementById('app_distinctive').value,
                }
            };

            if (mode === 'edit') {
                // Update existing
                const resp = await fetch(`/api/character/update/${characterFilename}`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                const result = await resp.json();
                if (result.status === 'ok') {
                    location.href = '/chat/' + encodeURIComponent(characterFilename);
                }
            } else {
                // Create new
                const resp = await fetch('/api/character/create', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(data)
                });
                const result = await resp.json();
                if (result.status === 'ok') {
                    location.href = '/chat/' + encodeURIComponent(result.character);
                }
            }
        });
    </script>
</body>
</html>