{% extends "company_base.html" %}

{% block title %}Strategie - {{ session.company_name }}{% endblock %}

{% block content %}
<div class="max-w-3xl mx-auto">
    <div id="strategyImportOverlay" class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 hidden">
        <div class="flex items-center justify-center min-h-screen p-6">
            <div class="card-bg border rounded-2xl p-8 w-full max-w-lg text-center space-y-5">
                <div class="w-16 h-16 bg-brand-highlight/20 rounded-full flex items-center justify-center mx-auto">
                    <svg class="w-8 h-8 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <h2 class="text-xl font-semibold text-white mb-1">Strategie wird importiert</h2>
                    <p id="importStatusText" class="text-gray-400 text-sm">PDF wird verarbeitet…</p>
                </div>
                <div class="w-full bg-brand-bg-dark rounded-full h-3 overflow-hidden border border-brand-bg-light">
                    <div id="importProgressBar" class="h-full bg-brand-highlight transition-all duration-300" style="width: 10%"></div>
                </div>
                <div id="importStepText" class="text-xs text-gray-500">Bitte warten – das kann einen Moment dauern.</div>
            </div>
        </div>
    </div>

    <div id="strategyImportModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 hidden">
        <div class="flex items-center justify-center min-h-screen p-6">
            <div class="card-bg border rounded-2xl p-6 w-full max-w-md space-y-4 text-center">
                <div class="w-12 h-12 bg-brand-highlight/20 rounded-full flex items-center justify-center mx-auto">
                    <svg class="w-6 h-6 text-brand-highlight" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                    </svg>
                </div>
                <h3 id="strategyImportModalTitle" class="text-lg font-semibold text-white">Unternehmensstrategie aktualisiert</h3>
                <p id="strategyImportModalBody" class="text-gray-400 text-sm">Bitte prüfen und speichern.</p>
                <button id="strategyImportModalClose" class="btn-primary font-medium py-2.5 px-6 rounded-lg transition-colors">
                    Verstanden
                </button>
            </div>
        </div>
    </div>
    <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between mb-2">
        <h1 class="text-2xl font-bold text-white">Unternehmensstrategie</h1>
        <div class="flex items-center gap-2">
            <input type="file" id="strategyImportInput" accept=".pdf" class="hidden">
            <button type="button" id="strategyImportBtn" class="btn-primary font-medium py-2.5 px-4 rounded-lg transition-colors">
                Importieren
            </button>
        </div>
    </div>
    <p class="text-gray-400 mb-2">Diese Strategie wird bei der Erstellung aller LinkedIn-Posts deiner Mitarbeiter berücksichtigt.</p>
    <p class="text-gray-500 text-sm mb-8">PDF hochladen, analysieren lassen und die Felder automatisch befüllen.</p>

    <div id="strategyFormWrapper">
    {% if success %}
    <div class="bg-green-900/50 border border-green-500 text-green-200 px-4 py-3 rounded-lg mb-6">
        Strategie 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 mb-6">
        {{ error }}
    </div>
    {% endif %}

    <form method="POST" action="/company/strategy" class="space-y-6">
        <!-- Mission & Vision -->
        <div class="card-bg border rounded-xl p-6">
            <h2 class="text-lg font-semibold text-white mb-4">Mission & Vision</h2>
            <div class="space-y-4">
                <div>
                    <label for="mission" class="block text-sm font-medium text-gray-300 mb-1">Mission</label>
                    <textarea id="mission" name="mission" rows="2"
                              class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                              placeholder="Was ist der Zweck deines Unternehmens?">{{ strategy.mission or '' }}</textarea>
                </div>
                <div>
                    <label for="vision" class="block text-sm font-medium text-gray-300 mb-1">Vision</label>
                    <textarea id="vision" name="vision" rows="2"
                              class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                              placeholder="Wo soll dein Unternehmen in Zukunft stehen?">{{ strategy.vision or '' }}</textarea>
                </div>
            </div>
        </div>

        <!-- Brand Voice -->
        <div class="card-bg border rounded-xl p-6">
            <h2 class="text-lg font-semibold text-white mb-4">Brand Voice</h2>
            <div class="space-y-4">
                <div>
                    <label for="brand_voice" class="block text-sm font-medium text-gray-300 mb-1">Markenstimme</label>
                    <textarea id="brand_voice" name="brand_voice" rows="2"
                              class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                              placeholder="Wie soll deine Marke klingen? (z.B. professionell, freundlich, innovativ)">{{ strategy.brand_voice or '' }}</textarea>
                </div>
                <div>
                    <label for="tone_guidelines" class="block text-sm font-medium text-gray-300 mb-1">Tonalität-Richtlinien</label>
                    <textarea id="tone_guidelines" name="tone_guidelines" rows="3"
                              class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                              placeholder="Spezifische Anweisungen zur Tonalität (z.B. Duzen/Siezen, Fachsprache, etc.)">{{ strategy.tone_guidelines or '' }}</textarea>
                </div>
            </div>
        </div>

        <!-- Target Audience -->
        <div class="card-bg border rounded-xl p-6">
            <h2 class="text-lg font-semibold text-white mb-4">Zielgruppe</h2>
            <div>
                <label for="target_audience" class="block text-sm font-medium text-gray-300 mb-1">Beschreibung der Zielgruppe</label>
                <textarea id="target_audience" name="target_audience" rows="3"
                          class="w-full input-bg border rounded-lg px-4 py-3 text-white"
                          placeholder="Wer ist deine Zielgruppe auf LinkedIn?">{{ strategy.target_audience or '' }}</textarea>
            </div>
        </div>

        <!-- Content Pillars -->
        <div class="card-bg border rounded-xl p-6">
            <h2 class="text-lg font-semibold text-white mb-4">Content-Säulen</h2>
            <p class="text-gray-400 text-sm mb-4">Die Hauptthemen, über die dein Unternehmen postet.</p>
            <div id="content-pillars" class="space-y-2">
                {% for pillar in strategy.content_pillars or [] %}
                <div class="flex gap-2">
                    <input type="text" name="content_pillar" value="{{ pillar }}"
                           class="flex-1 input-bg border rounded-lg px-4 py-2 text-white"
                           placeholder="z.B. Innovation, Nachhaltigkeit, Teamkultur">
                    <button type="button" onclick="this.parentElement.remove()"
                            class="px-3 py-2 text-red-400 hover:text-red-300">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
                {% endfor %}
                {% if not strategy.content_pillars %}
                <div class="flex gap-2">
                    <input type="text" name="content_pillar"
                           class="flex-1 input-bg border rounded-lg px-4 py-2 text-white"
                           placeholder="z.B. Innovation, Nachhaltigkeit, Teamkultur">
                    <button type="button" onclick="this.parentElement.remove()"
                            class="px-3 py-2 text-red-400 hover:text-red-300">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
                {% endif %}
            </div>
            <button type="button" onclick="addPillar()"
                    class="mt-3 text-brand-highlight text-sm hover:underline flex items-center gap-1">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                </svg>
                Weitere Säule hinzufügen
            </button>
        </div>

        <!-- Do's and Don'ts -->
        <div class="grid md:grid-cols-2 gap-6">
            <!-- Do's -->
            <div class="card-bg border rounded-xl p-6">
                <h2 class="text-lg font-semibold text-green-400 mb-4">Do's</h2>
                <div id="dos-list" class="space-y-2">
                    {% for do in strategy.dos or [] %}
                    <div class="flex gap-2">
                        <input type="text" name="do_item" value="{{ do }}"
                               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
                               placeholder="z.B. Erfolge feiern">
                        <button type="button" onclick="this.parentElement.remove()"
                                class="px-2 py-2 text-red-400 hover:text-red-300">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                    {% endfor %}
                    {% if not strategy.dos %}
                    <div class="flex gap-2">
                        <input type="text" name="do_item"
                               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
                               placeholder="z.B. Erfolge feiern">
                        <button type="button" onclick="this.parentElement.remove()"
                                class="px-2 py-2 text-red-400 hover:text-red-300">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                    {% endif %}
                </div>
                <button type="button" onclick="addDo()"
                        class="mt-3 text-green-400 text-sm hover:underline flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Hinzufügen
                </button>
            </div>

            <!-- Don'ts -->
            <div class="card-bg border rounded-xl p-6">
                <h2 class="text-lg font-semibold text-red-400 mb-4">Don'ts</h2>
                <div id="donts-list" class="space-y-2">
                    {% for dont in strategy.donts or [] %}
                    <div class="flex gap-2">
                        <input type="text" name="dont_item" value="{{ dont }}"
                               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
                               placeholder="z.B. Konkurrenz kritisieren">
                        <button type="button" onclick="this.parentElement.remove()"
                                class="px-2 py-2 text-red-400 hover:text-red-300">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                    {% endfor %}
                    {% if not strategy.donts %}
                    <div class="flex gap-2">
                        <input type="text" name="dont_item"
                               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
                               placeholder="z.B. Konkurrenz kritisieren">
                        <button type="button" onclick="this.parentElement.remove()"
                                class="px-2 py-2 text-red-400 hover:text-red-300">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                            </svg>
                        </button>
                    </div>
                    {% endif %}
                </div>
                <button type="button" onclick="addDont()"
                        class="mt-3 text-red-400 text-sm hover:underline flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/>
                    </svg>
                    Hinzufügen
                </button>
            </div>
        </div>

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

<script>
function addPillar() {
    const container = document.getElementById('content-pillars');
    const div = document.createElement('div');
    div.className = 'flex gap-2';
    div.innerHTML = `
        <input type="text" name="content_pillar"
               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white"
               placeholder="z.B. Innovation, Nachhaltigkeit, Teamkultur">
        <button type="button" onclick="this.parentElement.remove()"
                class="px-3 py-2 text-red-400 hover:text-red-300">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
        </button>
    `;
    container.appendChild(div);
}

function addDo() {
    const container = document.getElementById('dos-list');
    const div = document.createElement('div');
    div.className = 'flex gap-2';
    div.innerHTML = `
        <input type="text" name="do_item"
               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
               placeholder="z.B. Erfolge feiern">
        <button type="button" onclick="this.parentElement.remove()"
                class="px-2 py-2 text-red-400 hover:text-red-300">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
        </button>
    `;
    container.appendChild(div);
}

function addDont() {
    const container = document.getElementById('donts-list');
    const div = document.createElement('div');
    div.className = 'flex gap-2';
    div.innerHTML = `
        <input type="text" name="dont_item"
               class="flex-1 input-bg border rounded-lg px-4 py-2 text-white text-sm"
               placeholder="z.B. Konkurrenz kritisieren">
        <button type="button" onclick="this.parentElement.remove()"
                class="px-2 py-2 text-red-400 hover:text-red-300">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
        </button>
    `;
    container.appendChild(div);
}

function buildList(containerId, inputName, values, placeholder, isSmall) {
    const container = document.getElementById(containerId);
    if (!container) return;
    container.innerHTML = '';

    const items = (values && values.length) ? values : [''];
    items.forEach((value) => {
        const div = document.createElement('div');
        div.className = 'flex gap-2';
        const textClass = isSmall ? 'text-sm' : '';
        div.innerHTML = `
            <input type="text" name="${inputName}" value="${value || ''}"
                   class="flex-1 input-bg border rounded-lg px-4 py-2 text-white ${textClass}"
                   placeholder="${placeholder}">
            <button type="button" onclick="this.parentElement.remove()"
                    class="px-2 py-2 text-red-400 hover:text-red-300">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        `;
        container.appendChild(div);
    });
}

function setValue(id, value) {
    const el = document.getElementById(id);
    if (el) el.value = value || '';
}

function showImportOverlay() {
    const overlay = document.getElementById('strategyImportOverlay');
    const wrapper = document.getElementById('strategyFormWrapper');
    if (overlay) overlay.classList.remove('hidden');
    if (wrapper) wrapper.classList.add('hidden');
}

function hideImportOverlay() {
    const overlay = document.getElementById('strategyImportOverlay');
    const wrapper = document.getElementById('strategyFormWrapper');
    if (overlay) overlay.classList.add('hidden');
    if (wrapper) wrapper.classList.remove('hidden');
}

function updateImportProgress(percent, statusText, stepText) {
    const bar = document.getElementById('importProgressBar');
    const status = document.getElementById('importStatusText');
    const step = document.getElementById('importStepText');
    if (bar) bar.style.width = `${percent}%`;
    if (status && statusText) status.textContent = statusText;
    if (step && stepText) step.textContent = stepText;
}

function showImportModal(title, body) {
    const modal = document.getElementById('strategyImportModal');
    const titleEl = document.getElementById('strategyImportModalTitle');
    const bodyEl = document.getElementById('strategyImportModalBody');
    if (titleEl) titleEl.textContent = title;
    if (bodyEl) bodyEl.textContent = body;
    if (modal) modal.classList.remove('hidden');
}

function hideImportModal() {
    const modal = document.getElementById('strategyImportModal');
    if (modal) modal.classList.add('hidden');
}

async function importStrategy(file) {
    const btn = document.getElementById('strategyImportBtn');
    if (!file) return;

    btn.disabled = true;
    btn.classList.add('opacity-50', 'cursor-not-allowed');
    showImportOverlay();
    updateImportProgress(15, 'PDF wird verarbeitet…', 'Text wird extrahiert');

    try {
        const steps = [
            { percent: 35, status: 'Dokument wird analysiert…', step: 'Inhalte werden strukturiert' },
            { percent: 60, status: 'Strategie wird aufgebaut…', step: 'Felder werden zugeordnet' },
            { percent: 85, status: 'Format wird finalisiert…', step: 'Qualitätscheck läuft' }
        ];
        let stepIndex = 0;
        const stepTimer = setInterval(() => {
            if (stepIndex >= steps.length) {
                clearInterval(stepTimer);
                return;
            }
            const step = steps[stepIndex];
            updateImportProgress(step.percent, step.status, step.step);
            stepIndex += 1;
        }, 900);

        const formData = new FormData();
        formData.append('file', file);
        const response = await fetch('/company/strategy/import', {
            method: 'POST',
            body: formData
        });
        const data = await response.json();
        if (!response.ok || !data.success) {
            const message = data.detail || data.error || 'Import fehlgeschlagen.';
            updateImportProgress(100, 'Import fehlgeschlagen', 'Bitte erneut versuchen.');
            showImportModal('Import fehlgeschlagen', message);
            return;
        }

        const strategy = data.strategy || {};
        setValue('mission', strategy.mission);
        setValue('vision', strategy.vision);
        setValue('brand_voice', strategy.brand_voice);
        setValue('tone_guidelines', strategy.tone_guidelines);
        setValue('target_audience', strategy.target_audience);

        buildList('content-pillars', 'content_pillar', strategy.content_pillars, 'z.B. Innovation, Nachhaltigkeit, Teamkultur', false);
        buildList('dos-list', 'do_item', strategy.dos, 'z.B. Erfolge feiern', true);
        buildList('donts-list', 'dont_item', strategy.donts, 'z.B. Konkurrenz kritisieren', true);

        updateImportProgress(100, 'Import abgeschlossen', 'Bitte prüfen und speichern.');
        showImportModal('Unternehmensstrategie aktualisiert', 'Bitte prüfen und speichern.');
    } catch (err) {
        updateImportProgress(100, 'Import fehlgeschlagen', 'Bitte erneut versuchen.');
        showImportModal('Import fehlgeschlagen', 'Bitte erneut versuchen.');
    } finally {
        btn.disabled = false;
        btn.classList.remove('opacity-50', 'cursor-not-allowed');
        hideImportOverlay();
    }
}

const importBtn = document.getElementById('strategyImportBtn');
const importInput = document.getElementById('strategyImportInput');
if (importBtn && importInput) {
    importBtn.addEventListener('click', () => importInput.click());
    importInput.addEventListener('change', () => {
        const file = importInput.files && importInput.files[0];
        if (file) importStrategy(file);
        importInput.value = '';
    });
}

const modalClose = document.getElementById('strategyImportModalClose');
if (modalClose) modalClose.addEventListener('click', hideImportModal);
</script>
{% endblock %}
