{% extends "base.html" %}

{% block title %}Search - PyST{% endblock %}

{% block page_header %}
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
    <div>
        <h1>Search Results</h1>
        <p style="color: var(--text-secondary)">Found {{ results|length }} results for "{{ query }}"</p>
    </div>
    <div class="flex items-center space-x-2 text-sm" style="color: var(--text-secondary)">
        <i class="fas fa-info-circle"></i>
        <span>Press <kbd class="px-1.5 py-0.5 text-xs font-semibold border rounded" style="color: var(--text-secondary); background-color: var(--nav-bg); border-color: var(--border-color)">Esc</kbd> to clear search</span>
    </div>
</div>
{% endblock %}

{% block content %}
<div class="space-y-6">
    {% if query %}
    <div class="card p-4 sm:p-6">
        {% if results %}
        <div class="space-y-4">
            {% for result in results %}
            <div class="border rounded-lg p-3 sm:p-4 hover:border-primary hover:shadow-md transition-all duration-200 group" style="border-color: var(--border-color); background-color: var(--header-bg)">
                <div class="flex flex-col sm:grid sm:grid-cols-12 gap-3 sm:gap-4">
                    <div class="sm:col-span-7">
                        <a href="/web/concept/{{ result.id_ }}" class="block hover:no-underline">
                            <h3 class="text-lg font-medium text-primary group-hover:text-primary-hover transition-colors duration-200">
                                {{ result.label }}
                            </h3>
                            <div class="mt-1 text-sm group-hover:text-primary transition-colors duration-200" style="color: var(--text-secondary)">
                                <i class="fas fa-link mr-1"></i>
                                <span class="font-mono text-xs break-all">{{ result.id_ }}</span>
                            </div>
                        </a>
                    </div>
                    <div class="sm:col-span-4">
                        {% if result.highlight %}
                            {% set highlight_text = result.highlight | striptags %}
                            {% if highlight_text != result.label %}
                            <div class="prose prose-sm max-w-none">
                                <p class="group-hover:text-primary transition-colors duration-200" style="color: var(--text-color)">{{ result.highlight | safe }}</p>
                            </div>
                            {% endif %}
                        {% endif %}
                        <div id="concept-info-{{ loop.index }}" class="text-sm mt-2 group-hover:text-primary transition-colors duration-200" style="color: var(--text-secondary)">
                            <i class="fas fa-spinner fa-spin mr-2"></i>Loading concept details...
                        </div>
                    </div>
                    <div class="sm:col-span-1 flex items-center justify-end">
                        <a href="/web/concept/{{ result.id_ }}" class="group-hover:text-primary group-hover:translate-x-1 transition-all duration-200" style="color: var(--text-tertiary)">
                            <i class="fas fa-chevron-right text-xl"></i>
                        </a>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="text-center py-8 sm:py-12">
            <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 rounded-full mb-4" style="background-color: var(--nav-bg)">
                <i class="fas fa-search text-xl sm:text-2xl" style="color: var(--text-tertiary)"></i>
            </div>
            <h3 class="text-lg font-medium mb-2" style="color: var(--text-color)">No results found</h3>
            <p class="max-w-md mx-auto px-4 sm:px-0" style="color: var(--text-secondary)">
                We couldn't find any concepts matching "{{ query }}". Try adjusting your search terms or try a different query.
            </p>
        </div>
        {% endif %}
    </div>
    {% else %}
    <div class="text-center py-8 sm:py-12">
        <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 rounded-full mb-4" style="background-color: var(--nav-bg)">
            <i class="fas fa-search text-xl sm:text-2xl" style="color: var(--text-tertiary)"></i>
        </div>
        <h3 class="text-lg font-medium mb-2" style="color: var(--text-color)">Start searching</h3>
        <p class="max-w-md mx-auto px-4 sm:px-0" style="color: var(--text-secondary)">
            Enter a search term above to find concepts in the taxonomy. You can use semantic search to find related concepts.
        </p>
    </div>
    {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Fetch concept details for all results
    document.querySelectorAll('[id^="concept-info-"]').forEach(element => {
        const conceptLink = element.closest('.border').querySelector('a');
        const iri = conceptLink.href.split('/web/concept/')[1];
        fetchConceptDetails(iri, element.id);
    });

    // Handle escape key to clear search
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const searchInput = document.querySelector('input[name="query"]');
            if (searchInput) {
                searchInput.value = '';
                searchInput.focus();
            }
        }
    });

    // Fetch concept details
    async function fetchConceptDetails(iri, elementId) {
        try {
            const response = await fetch(`{{ concept_api_url }}?iri=${encodeURIComponent(iri)}`);
            const concept = await response.json();

            const infoDiv = document.getElementById(elementId);
            if (concept) {
                const schemes = concept['http://www.w3.org/2004/02/skos/core#inScheme'] || [];
                const definition = concept['http://www.w3.org/2004/02/skos/core#definition']?.find(d => d['@language'] === 'en')?.['@value'];

                infoDiv.innerHTML = `
                    <div class="space-y-2">
                        ${schemes.length > 0 ? `
                            <div class="flex items-center">
                                <i class="fas fa-layer-group mr-2" style="color: var(--text-tertiary)"></i>
                                <div class="flex flex-wrap gap-1">
                                    ${schemes.map(scheme => `
                                        <a href="/web/concept_scheme/${scheme['@id']}" class="text-primary hover:text-primary-hover text-xs">
                                            ${scheme['@id'].split('/').pop()}
                                        </a>
                                    `).join(', ')}
                                </div>
                            </div>
                        ` : ''}
                        ${definition ? `
                            <div class="flex items-start">
                                <i class="fas fa-info-circle mr-2 mt-0.5" style="color: var(--text-tertiary)"></i>
                                <span class="text-xs" style="color: var(--text-secondary)">${definition}</span>
                            </div>
                        ` : ''}
                    </div>
                `;
            } else {
                infoDiv.innerHTML = '<span class="text-red-500 text-xs">Failed to load concept details</span>';
            }
        } catch (error) {
            console.error('Error fetching concept details:', error);
            document.getElementById(elementId).innerHTML = '<span class="text-red-500 text-xs">Failed to load concept details</span>';
        }
    }
});
</script>
{% endblock %}
