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

{% block title %}{{ proposal.title }} — Proposals{% endblock %}

{% block content %}
<!-- Breadcrumb -->
<nav class="mb-6 text-sm">
    <a href="/proposals" class="text-blue-400 hover:text-blue-300 transition">Proposals</a>
    <span class="text-slate-600 mx-2">/</span>
    <span class="text-slate-400">{{ proposal.title }}</span>
</nav>

<!-- Header -->
<div class="bg-slate-900 rounded-xl border border-slate-800 p-6 mb-6">
    <div class="flex items-start justify-between gap-4 mb-4">
        <h1 class="text-2xl font-bold text-white">{{ proposal.title }}</h1>
        <span class="px-3 py-1 rounded-full text-xs font-bold whitespace-nowrap
            {% if proposal.status == 'idea' %}bg-purple-500/20 text-purple-400 ring-1 ring-purple-500/30
            {% elif proposal.status == 'outline' %}bg-blue-500/20 text-blue-400 ring-1 ring-blue-500/30
            {% elif proposal.status == 'draft' %}bg-yellow-500/20 text-yellow-400 ring-1 ring-yellow-500/30
            {% elif proposal.status == 'submitted' %}bg-green-500/20 text-green-400 ring-1 ring-green-500/30
            {% elif proposal.status == 'merged' %}bg-emerald-500/20 text-emerald-400 ring-1 ring-emerald-500/30
            {% else %}bg-slate-600/20 text-slate-500 ring-1 ring-slate-600/30{% endif %}">
            {{ proposal.status | upper }}
        </span>
    </div>

    {% if proposal.description %}
    <p class="text-sm text-slate-300 leading-relaxed mb-4">{{ proposal.description }}</p>
    {% endif %}

    <!-- Metadata grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
        {% if proposal.intended_wg %}
        <div>
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">Working Group</h3>
            <p class="text-sm text-slate-300">{{ proposal.intended_wg }}</p>
        </div>
        {% endif %}
        {% if proposal.draft_name %}
        <div>
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">Draft Name</h3>
            <p class="text-sm text-slate-300 font-mono text-xs">{{ proposal.draft_name }}</p>
        </div>
        {% endif %}
        {% if proposal.source_paper %}
        <div>
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">Source Paper</h3>
            {% if proposal.source_url %}
            <a href="{{ proposal.source_url }}" target="_blank" class="text-sm text-blue-400 hover:text-blue-300 transition">{{ proposal.source_paper }}</a>
            {% else %}
            <p class="text-sm text-slate-300">{{ proposal.source_paper }}</p>
            {% endif %}
        </div>
        {% endif %}
        <div>
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-1">Dates</h3>
            <p class="text-xs text-slate-400">Created: {{ proposal.created_at[:10] if proposal.created_at else 'N/A' }}</p>
            <p class="text-xs text-slate-400">Updated: {{ proposal.updated_at[:10] if proposal.updated_at else 'N/A' }}</p>
        </div>
    </div>

    <!-- Actions -->
    <div class="flex items-center gap-3 pt-4 border-t border-slate-800/50">
        <a href="/proposals/{{ proposal.id }}/edit" class="inline-flex items-center gap-2 px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white text-sm font-medium rounded-lg transition">
            <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
            Edit
        </a>
        <form method="POST" action="/proposals/{{ proposal.id }}/delete" onsubmit="return confirm('Delete this proposal? This cannot be undone.');" class="inline">
            <button type="submit" class="inline-flex items-center gap-2 px-4 py-2 bg-red-900/30 hover:bg-red-900/50 text-red-400 text-sm font-medium rounded-lg transition ring-1 ring-red-500/20">
                <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                Delete
            </button>
        </form>
    </div>
</div>

<!-- Linked Gaps -->
{% if proposal.gaps %}
<div class="bg-slate-900 rounded-xl border border-slate-800 p-6 mb-6">
    <h2 class="text-lg font-semibold text-white mb-4">Linked Gaps ({{ proposal.gaps | length }})</h2>
    <div class="space-y-3">
        {% for gap in proposal.gaps %}
        <a href="/gaps/{{ gap.id }}" class="block bg-slate-800/50 rounded-lg border
            {% if gap.severity == 'critical' %}border-red-500/30 hover:border-red-500/50
            {% elif gap.severity == 'high' %}border-orange-500/20 hover:border-orange-500/40
            {% elif gap.severity == 'medium' %}border-yellow-500/15 hover:border-yellow-500/30
            {% else %}border-slate-700 hover:border-slate-600{% endif %}
            p-4 transition group">
            <div class="flex items-center justify-between gap-3">
                <div>
                    <h3 class="text-sm font-semibold text-white group-hover:text-blue-400 transition">{{ gap.topic }}</h3>
                    <p class="text-xs text-slate-400 mt-1">{{ gap.description[:120] }}{% if gap.description | length > 120 %}...{% endif %}</p>
                </div>
                <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold whitespace-nowrap shrink-0
                    {% if gap.severity == 'critical' %}bg-red-500/20 text-red-400
                    {% elif gap.severity == 'high' %}bg-orange-500/20 text-orange-400
                    {% elif gap.severity == 'medium' %}bg-yellow-500/20 text-yellow-400
                    {% else %}bg-green-500/20 text-green-400{% endif %}">
                    {{ gap.severity | upper }}
                </span>
            </div>
        </a>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Content -->
{% if proposal.content_md %}
<div class="bg-slate-900 rounded-xl border border-slate-800 p-6 mb-6">
    <h2 class="text-lg font-semibold text-white mb-4">Content</h2>
    <div class="bg-slate-950 rounded-lg border border-slate-800 p-4">
        <pre class="text-sm text-slate-300 font-mono leading-relaxed whitespace-pre-wrap">{{ proposal.content_md }}</pre>
    </div>
</div>
{% endif %}

<!-- Generate Internet-Draft -->
<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 IETF Internet-Draft from this proposal{% if proposal.gaps %} and its {{ proposal.gaps | length }} linked gap{{ 's' if proposal.gaps | length != 1 }}{% endif %}</p>
        </div>
        <button id="generateBtn" onclick="generateDraft({{ proposal.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="inline-block w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></span>
            <span>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="max-h-[70vh] overflow-y-auto 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>
</div>
{% endblock %}

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

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

    btn.disabled = true;
    genText.textContent = 'Generating...';
    status.classList.remove('hidden');
    error.classList.add('hidden');
    output.classList.add('hidden');

    fetch(`/proposals/${proposalId}/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;
            genText.textContent = 'Retry';
        } else {
            generatedText = data.text;
            generatedFilename = data.filename || 'generated-draft.txt';
            document.getElementById('draftText').textContent = data.text;
            output.classList.remove('hidden');
            genText.textContent = 'Done';
        }
    })
    .catch(err => {
        status.classList.add('hidden');
        error.classList.remove('hidden');
        document.getElementById('errorText').textContent = 'Network error: ' + err.message;
        btn.disabled = false;
        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 %}
