{% extends "base.html" %}
{% set active_page = "gaps" %}

{% block title %}{{ gap.topic }} — Gap Explorer{% endblock %}

{% block extra_head %}
<style>
    .draft-output {
        max-height: 70vh;
        overflow-y: auto;
    }
    .draft-output::-webkit-scrollbar { width: 6px; }
    .draft-output::-webkit-scrollbar-track { background: #0f172a; }
    .draft-output::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; }
    .generating-spinner {
        display: inline-block;
        width: 1rem;
        height: 1rem;
        border: 2px solid rgba(255,255,255,0.3);
        border-top-color: white;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
</style>
{% endblock %}

{% block content %}
<!-- Breadcrumb -->
<nav class="mb-6 text-sm">
    <a href="/gaps" class="text-blue-400 hover:text-blue-300 transition">Gap Explorer</a>
    <span class="text-slate-600 mx-2">/</span>
    <span class="text-slate-400">{{ gap.topic }}</span>
</nav>

<!-- Gap header -->
<div class="bg-slate-900 rounded-xl border
    {% if gap.severity == 'critical' %}border-red-500/40
    {% elif gap.severity == 'high' %}border-orange-500/30
    {% elif gap.severity == 'medium' %}border-yellow-500/20
    {% else %}border-slate-800{% endif %}
    p-6 mb-6">

    <div class="flex items-start justify-between gap-4 mb-4">
        <h1 class="text-2xl font-bold text-white">{{ gap.topic }}</h1>
        <span class="px-3 py-1 rounded-full text-xs font-bold whitespace-nowrap
            {% if gap.severity == 'critical' %}bg-red-500/20 text-red-400 ring-1 ring-red-500/30
            {% elif gap.severity == 'high' %}bg-orange-500/20 text-orange-400 ring-1 ring-orange-500/30
            {% elif gap.severity == 'medium' %}bg-yellow-500/20 text-yellow-400 ring-1 ring-yellow-500/30
            {% else %}bg-green-500/20 text-green-400 ring-1 ring-green-500/30{% endif %}">
            {{ gap.severity | upper }}
        </span>
    </div>

    {% if gap.category %}
    <span class="inline-block px-2.5 py-0.5 rounded text-xs bg-slate-800 text-slate-400 mb-4 font-medium">{{ gap.category }}</span>
    {% endif %}

    <div class="space-y-4">
        <div>
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Description</h3>
            <p class="text-sm text-slate-300 leading-relaxed">{{ gap.description }}</p>
        </div>

        {% if gap.evidence %}
        <div class="bg-slate-800/50 rounded-lg p-4">
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Evidence</h3>
            <p class="text-sm text-slate-400 leading-relaxed">{{ gap.evidence }}</p>
        </div>
        {% endif %}
    </div>

    <!-- Links -->
    <div class="mt-4 pt-4 border-t border-slate-800/50 flex flex-wrap gap-3">
        <a href="/drafts?q={{ gap.topic | urlencode }}" class="inline-flex items-center gap-1.5 text-xs text-blue-400/70 hover:text-blue-400 transition">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            Search related drafts
        </a>
        {% if gap.category %}
        <span class="text-slate-700">|</span>
        <a href="/drafts?cat={{ gap.category | urlencode }}" class="inline-flex items-center gap-1.5 text-xs text-blue-400/70 hover:text-blue-400 transition">
            <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
            Browse {{ gap.category }} drafts
        </a>
        {% endif %}
    </div>
</div>

<!-- Draft Generation Section -->
<div class="bg-slate-900 rounded-xl border border-slate-800 p-6">
    <div class="flex items-center justify-between mb-4">
        <div>
            <h2 class="text-lg font-semibold text-white">Generate Internet-Draft</h2>
            <p class="text-xs text-slate-500 mt-1">Use AI to generate a full Internet-Draft addressing this gap</p>
        </div>
        <button id="generateBtn" onclick="generateDraft({{ gap.id }})"
            class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-500 disabled:bg-slate-700 disabled:text-slate-500 text-white text-sm font-medium rounded-lg transition">
            <svg id="genIcon" 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="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
            <span id="genText">Generate Draft</span>
        </button>
    </div>

    <!-- Status area -->
    <div id="genStatus" class="hidden mb-4 p-3 rounded-lg bg-blue-500/10 border border-blue-500/20">
        <div class="flex items-center gap-2 text-sm text-blue-400">
            <span class="generating-spinner"></span>
            <span id="statusText">Generating draft... This may take 1-2 minutes.</span>
        </div>
    </div>

    <!-- Error area -->
    <div id="genError" class="hidden mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
        <p class="text-sm text-red-400" id="errorText"></p>
    </div>

    <!-- Generated draft output -->
    <div id="draftOutput" class="hidden">
        <div class="flex items-center justify-between mb-3">
            <h3 class="text-sm font-semibold text-slate-300">Generated Draft</h3>
            <button onclick="downloadDraft()" class="inline-flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium rounded-lg transition">
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                Download .txt
            </button>
        </div>
        <div class="draft-output bg-slate-950 rounded-lg border border-slate-800 p-4">
            <pre id="draftText" class="text-xs text-slate-300 font-mono leading-relaxed whitespace-pre-wrap"></pre>
        </div>
    </div>

    <!-- Hint to demo -->
    <div id="demoHint" class="mt-4 text-xs text-slate-600">
        Want to see what generated drafts look like without waiting?
        <a href="/gaps/demo" class="text-blue-500 hover:text-blue-400 transition">View the demo page</a>
        with {{ generated_drafts | length }} pre-generated examples.
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
let generatedText = '';
let generatedFilename = '';

function generateDraft(gapId) {
    const btn = document.getElementById('generateBtn');
    const genIcon = document.getElementById('genIcon');
    const genText = document.getElementById('genText');
    const status = document.getElementById('genStatus');
    const error = document.getElementById('genError');
    const output = document.getElementById('draftOutput');
    const hint = document.getElementById('demoHint');

    // Disable button, show spinner
    btn.disabled = true;
    genIcon.innerHTML = '';
    genIcon.classList.add('generating-spinner');
    genText.textContent = 'Generating...';
    status.classList.remove('hidden');
    error.classList.add('hidden');
    output.classList.add('hidden');
    hint.classList.add('hidden');

    fetch(`/gaps/${gapId}/generate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
    })
    .then(r => r.json())
    .then(data => {
        status.classList.add('hidden');
        if (data.error) {
            error.classList.remove('hidden');
            document.getElementById('errorText').textContent = data.error;
            btn.disabled = false;
            genIcon.classList.remove('generating-spinner');
            genIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>';
            genText.textContent = 'Retry';
        } else {
            generatedText = data.text;
            generatedFilename = data.filename || 'generated-draft.txt';
            document.getElementById('draftText').textContent = data.text;
            output.classList.remove('hidden');
            genIcon.classList.remove('generating-spinner');
            genIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>';
            genText.textContent = 'Done';
        }
    })
    .catch(err => {
        status.classList.add('hidden');
        error.classList.remove('hidden');
        document.getElementById('errorText').textContent = 'Network error: ' + err.message;
        btn.disabled = false;
        genIcon.classList.remove('generating-spinner');
        genIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>';
        genText.textContent = 'Retry';
    });
}

function downloadDraft() {
    if (!generatedText) return;
    const blob = new Blob([generatedText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = generatedFilename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}
</script>
{% endblock %}
