{% extends "base.html" %}

{% block title %}Strategie{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto space-y-6">
    <div class="card-bg border rounded-2xl p-6 relative overflow-hidden">
        <div class="absolute -right-20 -top-16 w-56 h-56 bg-brand-highlight/10 rounded-full blur-3xl"></div>
        <div class="relative">
            <div class="flex items-center gap-3 mb-3">
                <div class="w-10 h-10 rounded-xl bg-brand-highlight/20 flex items-center justify-center">
                    <svg class="w-5 h-5 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <h1 class="text-2xl font-bold text-white">Strategie</h1>
                    <p class="text-gray-400">Strukturierte Profil-Analyse basierend auf deinen LinkedIn-Posts.</p>
                </div>
            </div>
            {% if analysis_created_at %}
            <div class="inline-flex items-center gap-2 text-xs text-gray-300 bg-brand-bg/60 border border-brand-bg-light rounded-full px-3 py-1">
                <span class="w-1.5 h-1.5 bg-green-400 rounded-full"></span>
                Letzte Analyse: {{ analysis_created_at.strftime('%d.%m.%Y %H:%M') }}
            </div>
            {% endif %}
        </div>
    </div>

    {% if success %}
    <div class="bg-green-900/50 border border-green-500 text-green-200 px-4 py-3 rounded-lg">
        Profil-Analyse erfolgreich gespeichert!
    </div>
    {% endif %}

    {% if error %}
    <div class="bg-red-900/50 border border-red-500 text-red-200 px-4 py-3 rounded-lg">
        {{ error }}
    </div>
    {% endif %}

    {% if not profile_analysis %}
    <div class="card-bg border rounded-2xl p-8 text-center">
        <div class="w-16 h-16 bg-yellow-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg class="w-8 h-8 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
            </svg>
        </div>
        <p class="text-gray-300 mb-2">Noch keine Profil-Analyse vorhanden.</p>
        <p class="text-gray-500 text-sm">Bitte wende dich an den Administrator, um eine Analyse zu starten.</p>
    </div>
    {% endif %}

    <form id="strategyForm" method="POST" action="/employee/strategy" class="space-y-6">
        <input type="hidden" id="analysis_original_json" value="{{ analysis_json | e }}">
        <input type="hidden" id="analysis_json" name="analysis_json" value="">

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 5H9m6 4H9m6 4H9m6 4H9"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Schreibstil</h2>
            </div>
            <div class="grid md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Tonalität</label>
                    <input type="text" id="writing_tone" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.tone if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Perspektive</label>
                    <input type="text" id="writing_perspective" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.perspective if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Ansprache</label>
                    <input type="text" id="writing_form_of_address" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.form_of_address if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Satzdynamik</label>
                    <input type="text" id="writing_sentence_dynamics" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.sentence_dynamics if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Ø Post-Länge</label>
                    <input type="text" id="writing_average_post_length" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.average_post_length if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Ø Wortanzahl</label>
                    <input type="number" id="writing_average_word_count" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.writing_style.average_word_count if profile_analysis and profile_analysis.writing_style else '' }}">
                </div>
            </div>
        </div>

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 11c0 1.657-1.343 3-3 3S6 12.657 6 11s1.343-3 3-3 3 1.343 3 3zm6 7a6 6 0 00-12 0"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Sprachlicher Fingerabdruck</h2>
            </div>
            <div class="grid md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Energie-Level (1-10)</label>
                    <input type="number" id="linguistic_energy_level" min="1" max="10"
                           class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.linguistic_fingerprint.energy_level if profile_analysis and profile_analysis.linguistic_fingerprint else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Formalität (1-10)</label>
                    <input type="number" id="linguistic_formality_level" min="1" max="10"
                           class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.linguistic_fingerprint.formality_level if profile_analysis and profile_analysis.linguistic_fingerprint else '' }}">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-300 mb-1">Ausrufe / Betonung</label>
                    <textarea id="linguistic_shouting_usage" rows="2"
                              class="w-full input-bg border rounded-lg px-4 py-2 text-white">{{ profile_analysis.linguistic_fingerprint.shouting_usage if profile_analysis and profile_analysis.linguistic_fingerprint else '' }}</textarea>
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-300 mb-1">Interpunktion</label>
                    <textarea id="linguistic_punctuation_patterns" rows="2"
                              class="w-full input-bg border rounded-lg px-4 py-2 text-white">{{ profile_analysis.linguistic_fingerprint.punctuation_patterns if profile_analysis and profile_analysis.linguistic_fingerprint else '' }}</textarea>
                </div>
            </div>

            <div class="mt-4">
                <label class="block text-sm font-medium text-gray-300 mb-2">Signature Phrases</label>
                <div id="signature_phrases" class="space-y-2">
                    {% for phrase in profile_analysis.linguistic_fingerprint.signature_phrases or [] %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endfor %}
                    {% if not profile_analysis or not profile_analysis.linguistic_fingerprint or not profile_analysis.linguistic_fingerprint.signature_phrases %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Beispielphrase">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endif %}
                </div>
                <button type="button" onclick="addListItem('signature_phrases', 'Beispielphrase')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
            </div>

            <div class="mt-4">
                <label class="block text-sm font-medium text-gray-300 mb-2">Narrative Anchors</label>
                <div id="narrative_anchors" class="space-y-2">
                    {% for phrase in profile_analysis.linguistic_fingerprint.narrative_anchors or [] %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endfor %}
                    {% if not profile_analysis or not profile_analysis.linguistic_fingerprint or not profile_analysis.linguistic_fingerprint.narrative_anchors %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Story-Element">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endif %}
                </div>
                <button type="button" onclick="addListItem('narrative_anchors', 'Story-Element')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
            </div>
        </div>

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7h16M4 12h16M4 17h10"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Phrasen-Bibliothek</h2>
            </div>
            <div class="grid md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Hook-Phrasen</label>
                    <div id="hook_phrases" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.hook_phrases or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.hook_phrases %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Hook">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('hook_phrases', 'Hook')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Transition-Phrasen</label>
                    <div id="transition_phrases" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.transition_phrases or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.transition_phrases %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Übergang">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('transition_phrases', 'Übergang')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Emotionale Ausdrücke</label>
                    <div id="emotional_expressions" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.emotional_expressions or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.emotional_expressions %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Ausdruck">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('emotional_expressions', 'Ausdruck')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">CTA-Phrasen</label>
                    <div id="cta_phrases" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.cta_phrases or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.cta_phrases %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="CTA">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('cta_phrases', 'CTA')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Filler-Ausdrücke</label>
                    <div id="filler_expressions" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.filler_expressions or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.filler_expressions %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Filler">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('filler_expressions', 'Filler')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Ending-Phrasen</label>
                    <div id="ending_phrases" class="space-y-2">
                        {% for phrase in profile_analysis.phrase_library.ending_phrases or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.phrase_library or not profile_analysis.phrase_library.ending_phrases %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Abschluss">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('ending_phrases', 'Abschluss')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>
            </div>
        </div>

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19V6l12-2v13"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Ton-Analyse</h2>
            </div>
            <div class="grid md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Primärer Ton</label>
                    <input type="text" id="tone_primary" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.tone_analysis.primary_tone if profile_analysis and profile_analysis.tone_analysis else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Sekundäre Töne</label>
                    <div id="tone_secondary" class="space-y-2">
                        {% for phrase in profile_analysis.tone_analysis.secondary_tones or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.tone_analysis or not profile_analysis.tone_analysis.secondary_tones %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Sekundärer Ton">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('tone_secondary', 'Sekundärer Ton')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>
            </div>
        </div>

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a4 4 0 00-4-4h-1M9 20H4v-2a4 4 0 014-4h1m4-4a4 4 0 11-8 0 4 4 0 018 0zm6 2a3 3 0 100-6 3 3 0 000 6z"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Zielgruppen-Insights</h2>
            </div>
            <div class="grid md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Branche / Kontext</label>
                    <input type="text" id="audience_industry_context" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.audience_insights.industry_context if profile_analysis and profile_analysis.audience_insights else '' }}">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-1">Zielgruppe</label>
                    <input type="text" id="audience_target" class="w-full input-bg border rounded-lg px-4 py-2 text-white"
                           value="{{ profile_analysis.audience_insights.target_audience if profile_analysis and profile_analysis.audience_insights else '' }}">
                </div>
            </div>
            <div class="mt-4">
                <label class="block text-sm font-medium text-gray-300 mb-2">Pain Points</label>
                <div id="audience_pain_points" class="space-y-2">
                    {% for phrase in profile_analysis.audience_insights.pain_points_addressed or [] %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endfor %}
                    {% if not profile_analysis or not profile_analysis.audience_insights or not profile_analysis.audience_insights.pain_points_addressed %}
                    <div class="flex gap-2">
                        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Pain Point">
                        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                    </div>
                    {% endif %}
                </div>
                <button type="button" onclick="addListItem('audience_pain_points', 'Pain Point')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
            </div>
        </div>

        <div class="card-bg border rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                    <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4h7v7H4V4zm9 0h7v7h-7V4zM4 13h7v7H4v-7zm9 0h7v7h-7v-7z"/>
                    </svg>
                </div>
                <h2 class="text-lg font-semibold text-white">Topic Patterns</h2>
            </div>
            <div class="grid md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Hauptthemen</label>
                    <div id="topic_main" class="space-y-2">
                        {% for phrase in profile_analysis.topic_patterns.main_topics or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.topic_patterns or not profile_analysis.topic_patterns.main_topics %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Thema">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('topic_main', 'Thema')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Wiederkehrende Themen</label>
                    <div id="topic_recurring" class="space-y-2">
                        {% for phrase in profile_analysis.topic_patterns.recurring_themes or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.topic_patterns or not profile_analysis.topic_patterns.recurring_themes %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Thema">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('topic_recurring', 'Thema')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-300 mb-2">Formate</label>
                    <div id="topic_formats" class="space-y-2">
                        {% for phrase in profile_analysis.topic_patterns.content_formats or [] %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" value="{{ phrase }}">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endfor %}
                        {% if not profile_analysis or not profile_analysis.topic_patterns or not profile_analysis.topic_patterns.content_formats %}
                        <div class="flex gap-2">
                            <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="Format">
                            <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
                        </div>
                        {% endif %}
                    </div>
                    <button type="button" onclick="addListItem('topic_formats', 'Format')" class="mt-2 text-brand-highlight text-sm hover:underline">Hinzufügen</button>
                </div>
            </div>
        </div>

        <details class="card-bg border rounded-2xl p-6">
            <summary class="flex items-center justify-between cursor-pointer text-white font-semibold">
                <span class="flex items-center gap-3">
                    <span class="w-9 h-9 rounded-lg bg-brand-highlight/15 flex items-center justify-center">
                        <svg class="w-4 h-4 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 6h8M8 12h8m-5 6h5"/>
                        </svg>
                    </span>
                    Zusatzdaten
                </span>
                <span class="text-xs text-gray-400">Optional</span>
            </summary>
            <div class="mt-4 space-y-3">
                <div class="text-sm text-gray-400">
                    Erweiterte Felder als strukturierte Listen. Werte lassen sich hinzufügen oder entfernen.
                </div>
                <div id="extras_fields" class="space-y-4"></div>
                <button type="button" onclick="addExtrasField()" class="text-brand-highlight text-sm hover:underline">
                    Zusatzfeld hinzufügen
                </button>
            </div>
        </details>

        <div class="flex justify-end">
            <button type="submit" class="btn-primary font-medium py-3 px-8 rounded-lg transition-colors">
                Analyse speichern
            </button>
        </div>
    </form>
</div>

<script>
function addListItem(containerId, placeholderText) {
    const container = document.getElementById(containerId);
    if (!container) return;
    const div = document.createElement('div');
    div.className = 'flex gap-2';
    div.innerHTML = `
        <input type="text" class="flex-1 input-bg border rounded-lg px-4 py-2 text-white" placeholder="${placeholderText}">
        <button type="button" onclick="this.parentElement.remove()" class="px-3 py-2 text-red-400 hover:text-red-300">✕</button>
    `;
    container.appendChild(div);
}

function collectList(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return [];
    return Array.from(container.querySelectorAll('input'))
        .map(input => input.value.trim())
        .filter(Boolean);
}

function toNumber(value) {
    if (value === '' || value === null || value === undefined) return null;
    const num = Number(value);
    return Number.isNaN(num) ? null : num;
}

function parseOriginal() {
    const raw = document.getElementById('analysis_original_json')?.value || '';
    try {
        return raw ? JSON.parse(raw) : {};
    } catch (e) {
        return {};
    }
}

function buildAnalysisJson() {
    const base = parseOriginal();

    const writingStyle = {
        tone: document.getElementById('writing_tone')?.value.trim() || '',
        perspective: document.getElementById('writing_perspective')?.value.trim() || '',
        form_of_address: document.getElementById('writing_form_of_address')?.value.trim() || '',
        sentence_dynamics: document.getElementById('writing_sentence_dynamics')?.value.trim() || '',
        average_post_length: document.getElementById('writing_average_post_length')?.value.trim() || '',
        average_word_count: toNumber(document.getElementById('writing_average_word_count')?.value)
    };

    const linguisticFingerprint = {
        energy_level: toNumber(document.getElementById('linguistic_energy_level')?.value),
        formality_level: toNumber(document.getElementById('linguistic_formality_level')?.value),
        shouting_usage: document.getElementById('linguistic_shouting_usage')?.value.trim() || '',
        punctuation_patterns: document.getElementById('linguistic_punctuation_patterns')?.value.trim() || '',
        signature_phrases: collectList('signature_phrases'),
        narrative_anchors: collectList('narrative_anchors')
    };

    const phraseLibrary = {
        hook_phrases: collectList('hook_phrases'),
        transition_phrases: collectList('transition_phrases'),
        emotional_expressions: collectList('emotional_expressions'),
        cta_phrases: collectList('cta_phrases'),
        filler_expressions: collectList('filler_expressions'),
        ending_phrases: collectList('ending_phrases')
    };

    const toneAnalysis = {
        primary_tone: document.getElementById('tone_primary')?.value.trim() || '',
        secondary_tones: collectList('tone_secondary')
    };

    const audienceInsights = {
        industry_context: document.getElementById('audience_industry_context')?.value.trim() || '',
        target_audience: document.getElementById('audience_target')?.value.trim() || '',
        pain_points_addressed: collectList('audience_pain_points')
    };

    const topicPatterns = {
        main_topics: collectList('topic_main'),
        recurring_themes: collectList('topic_recurring'),
        content_formats: collectList('topic_formats')
    };

    base.writing_style = writingStyle;
    base.linguistic_fingerprint = linguisticFingerprint;
    base.phrase_library = phraseLibrary;
    base.tone_analysis = toneAnalysis;
    base.audience_insights = audienceInsights;
    base.topic_patterns = topicPatterns;

    const extras = collectExtras();
    Object.keys(extras).forEach((key) => {
        base[key] = extras[key];
    });

    return base;
}

const form = document.getElementById('strategyForm');
if (form) {
    form.addEventListener('submit', (event) => {
        const built = buildAnalysisJson();
        document.getElementById('analysis_json').value = JSON.stringify(built, null, 2);
    });
}

function addExtrasField(name = '', values = []) {
    const container = document.getElementById('extras_fields');
    if (!container) return;

    const field = document.createElement('div');
    field.className = 'bg-brand-bg/40 border border-brand-bg-light rounded-xl p-4 space-y-3';
    field.innerHTML = `
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div class="flex-1">
                <label class="block text-xs uppercase tracking-wide text-gray-400 mb-1">Feldname</label>
                <input type="text" class="extras-name w-full input-bg border rounded-lg px-3 py-2 text-white text-sm" placeholder="z.B. Produkt-Features" value="${name || ''}">
            </div>
            <button type="button" class="text-red-400 hover:text-red-300 text-sm" onclick="this.closest('.extras-field').remove()">Feld entfernen</button>
        </div>
        <div class="extras-values space-y-2"></div>
        <button type="button" class="text-brand-highlight text-sm hover:underline add-extra-value">Wert hinzufügen</button>
    `;
    field.classList.add('extras-field');
    container.appendChild(field);

    const valuesContainer = field.querySelector('.extras-values');
    const addValueBtn = field.querySelector('.add-extra-value');
    addValueBtn.addEventListener('click', () => addExtrasValue(valuesContainer, ''));

    if (!values || values.length === 0) {
        addExtrasValue(valuesContainer, '');
    } else {
        values.forEach((value) => addExtrasValue(valuesContainer, value));
    }
}

function addExtrasValue(container, value) {
    const row = document.createElement('div');
    row.className = 'flex gap-2 items-start';
    row.innerHTML = `
        <input type="text" class="flex-1 input-bg border rounded-lg px-3 py-2 text-white text-sm" placeholder="Wert" value="${value || ''}">
        <button type="button" class="px-3 py-2 text-red-400 hover:text-red-300" onclick="this.parentElement.remove()">✕</button>
    `;
    container.appendChild(row);
}

function collectExtras() {
    const container = document.getElementById('extras_fields');
    if (!container) return {};
    const extras = {};
    container.querySelectorAll('.extras-field').forEach((field) => {
        const nameInput = field.querySelector('.extras-name');
        const name = nameInput ? nameInput.value.trim() : '';
        if (!name) return;
        const values = Array.from(field.querySelectorAll('.extras-values input'))
            .map(input => input.value.trim())
            .filter(Boolean);
        if (values.length) {
            extras[name] = values;
        }
    });
    return extras;
}

function normalizeExtrasValue(value) {
    if (Array.isArray(value)) return value.map(item => String(item));
    if (value === null || value === undefined) return [];
    if (typeof value === 'object') {
        if (Array.isArray(value.typical_emojis)) {
            return value.typical_emojis.map(item => String(item));
        }
        if (typeof value.typical_emojis === 'string' && value.typical_emojis.trim()) {
            return value.typical_emojis.split(/\s+/).map(item => item.trim()).filter(Boolean);
        }
        return Object.entries(value).map(([key, val]) => `${key}: ${val}`);
    }
    return [String(value)];
}

function collectAllStrings(obj, acc) {
    if (obj === null || obj === undefined) return acc;
    if (typeof obj === 'string') {
        acc.push(obj);
        return acc;
    }
    if (Array.isArray(obj)) {
        obj.forEach(item => collectAllStrings(item, acc));
        return acc;
    }
    if (typeof obj === 'object') {
        Object.values(obj).forEach(value => collectAllStrings(value, acc));
    }
    return acc;
}

function extractEmojis(text) {
    if (!text) return [];
    const matches = text.match(/\p{Extended_Pictographic}/gu);
    return matches ? matches : [];
}

function getEmojiSummary(base) {
    const strings = collectAllStrings(base, []);
    const all = strings.flatMap(extractEmojis);
    const uniq = Array.from(new Set(all));
    return uniq;
}

function extractExtras() {
    const base = parseOriginal();
    const emojiSummary = getEmojiSummary(base);
    const extras = {};
    Object.keys(base || {}).forEach((key) => {
        if (!['writing_style','linguistic_fingerprint','phrase_library','tone_analysis','audience_insights','topic_patterns'].includes(key)) {
            extras[key] = base[key];
        }
    });
    const entries = Object.entries(extras);
    if (!entries.length) {
        addExtrasField();
        return;
    }
    entries.forEach(([key, value]) => {
        if (key === 'visual_patterns' && Array.isArray(value)) {
            const patched = value.map((item) => {
                const text = String(item);
                if (text.includes('emoji_usage') && text.includes('[object Object]')) {
                    const emojisText = emojiSummary.length ? emojiSummary.join(' ') : '';
                    return emojisText ? `emoji_usage: ${emojisText}` : '';
                }
                return text.includes('[object Object]') ? '' : text;
            }).filter(Boolean);
            if (patched.length) {
                addExtrasField(key, patched);
            }
            return;
        }

        const normalized = normalizeExtrasValue(value).filter((entry) => !String(entry).includes('[object Object]'));
        if (normalized.length) {
            addExtrasField(key, normalized);
        }
    });
}
extractExtras();

</script>
{% endblock %}
