{% extends "base.html" %}

{% block title %}Search {% if current_project == all_projects_value %}All Projects{% else %}{{ current_project|display_name }}{% endif %} - CodeContext{% endblock %}

{% block content %}
<div class="search-page">
    <h1>Search {% if current_project == all_projects_value %}All Projects{% elif current_project %}{{ current_project|display_name }}{% else %}Memories{% endif %}</h1>

    <form id="search-form" class="search-form" method="GET" action="/search">
        <input type="hidden" name="project" value="{{ current_project }}">
        <input type="hidden" name="type" id="type-input" value="{{ selected_types|join(',') }}">
        <input type="hidden" name="file" id="file-input" value="{{ file_filter }}">
        <input type="hidden" name="sort" id="sort-input" value="{{ sort_order }}">
        <input type="text"
               name="q"
               id="search-query"
               value="{{ query }}"
               placeholder="Search for memories (e.g., 'datetime bug', 'authentication')"
               class="search-input"
               autofocus>
        <button type="submit" class="search-button">Search</button>
    </form>

    {% if query %}
    <!-- Filter Bar -->
    <div class="filter-bar">
        <div class="filter-group">
            <label>Type:</label>
            <div class="filter-chips">
                <button type="button" class="filter-chip{% if 'bugfix' in selected_types %} active{% endif %}" data-value="bugfix">bugfix</button>
                <button type="button" class="filter-chip{% if 'feature' in selected_types %} active{% endif %}" data-value="feature">feature</button>
                <button type="button" class="filter-chip{% if 'discovery' in selected_types %} active{% endif %}" data-value="discovery">discovery</button>
                <button type="button" class="filter-chip{% if 'decision' in selected_types %} active{% endif %}" data-value="decision">decision</button>
                <button type="button" class="filter-chip{% if 'refactor' in selected_types %} active{% endif %}" data-value="refactor">refactor</button>
                <button type="button" class="filter-chip{% if 'optimization' in selected_types %} active{% endif %}" data-value="optimization">optimization</button>
                <button type="button" class="filter-chip{% if 'gotcha' in selected_types %} active{% endif %}" data-value="gotcha">gotcha</button>
            </div>
        </div>

        <div class="filter-group file-filter">
            <label for="file-filter">File:</label>
            <input type="text"
                   id="file-filter"
                   value="{{ file_filter }}"
                   placeholder="Filter by file..."
                   list="file-suggestions"
                   autocomplete="off">
            <datalist id="file-suggestions"></datalist>
            <button type="button" id="clear-file-filter" class="btn-clear" title="Clear filter" {% if not file_filter %}style="display: none;"{% endif %}>×</button>
        </div>

        <div class="filter-group">
            <label for="sort-select">Sort:</label>
            <select id="sort-select" class="sort-dropdown">
                <option value="relevance"{% if sort_order == 'relevance' %} selected{% endif %}>Relevance</option>
                <option value="newest"{% if sort_order == 'newest' %} selected{% endif %}>Newest First</option>
                <option value="oldest"{% if sort_order == 'oldest' %} selected{% endif %}>Oldest First</option>
            </select>
        </div>

        <button type="button" id="clear-filters" class="btn-clear" title="Clear all filters">×</button>

        <span id="filter-status" class="filter-status{% if selected_types or file_filter %} active{% endif %}">
            {% if selected_types or file_filter %}
                Filtering by {% if selected_types %}{{ selected_types|length }} type{% if selected_types|length > 1 %}s{% endif %}{% endif %}{% if selected_types and file_filter %}, {% endif %}{% if file_filter %}file{% endif %}
            {% endif %}
        </span>
    </div>

    <div class="search-meta">
        <p>Found <strong>{{ results|length }}</strong> results for "<strong>{{ query }}</strong>"
           in <strong>{{ search_time }}ms</strong>
           {% if selected_types %}
           <span class="filter-note">(filtered)</span>
           {% endif %}
        </p>
    </div>

    {% if results %}
    <div class="search-results">
        {% for r in results %}
        <div class="memory-card type-{{ r.type }}">
            <div class="memory-card-header">
                <span class="type-badge">{{ r.type }}</span>
                {% if current_project == all_projects_value %}
                <span class="project-tag">{{ r.project|display_name }}</span>
                {% endif %}
                <span class="relevance-badge {% if r.relevance_pct >= 50 %}good{% elif r.relevance_pct >= 30 %}ok{% else %}low{% endif %}">
                    {{ r.relevance_pct|round|int }}% match
                </span>
                {% if r.created_at %}
                <span class="memory-date" data-utc-time="{{ r.created_at }}">{{ r.formatted_date }}</span>
                {% endif %}
            </div>
            <div class="memory-card-body">
                <h3 class="memory-card-title">{{ r.title }}</h3>
                <p class="memory-card-fact">{{ r.fact }}</p>
            </div>
            {% if r.files %}
            <div class="memory-card-footer">
                <div class="memory-card-footer-label">Related Files</div>
                <div class="memory-card-files">
                    {% for f in r.files %}
                    <code class="clickable-file" data-file="{{ f }}">{{ f }}</code>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div class="empty-state">
        <p>No results found{% if selected_types %}. Try removing some filters or{% else %}. Try{% endif %} a different search term.</p>
    </div>
    {% endif %}
    {% else %}
    <div class="search-tips">
        <h3>Search Tips</h3>
        <ul>
            <li>Use natural language: "how to fix datetime errors"</li>
            <li>Search by type: "bugfix authentication"</li>
            <li>Search by file: "jwt.py"</li>
        </ul>
    </div>
    {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('search-form');
    const typeInput = document.getElementById('type-input');
    const fileInput = document.getElementById('file-input');
    const sortInput = document.getElementById('sort-input');
    const sortSelect = document.getElementById('sort-select');
    const clearBtn = document.getElementById('clear-filters');
    const filterStatus = document.getElementById('filter-status');
    const filterChips = document.querySelectorAll('.filter-chip');
    const searchQuery = document.getElementById('search-query');

    // File filter elements
    const fileFilter = document.getElementById('file-filter');
    const clearFileBtn = document.getElementById('clear-file-filter');
    let fileFilterTimeout = null;
    const project = '{{ current_project }}';

    // Helper: Get currently selected types from chips
    function getSelectedTypes() {
        const selected = [];
        filterChips.forEach(chip => {
            if (chip.classList.contains('active')) {
                selected.push(chip.dataset.value);
            }
        });
        return selected;
    }

    // Helper: Update the hidden inputs and status
    function updateFilterInputs() {
        const types = getSelectedTypes();
        const file = fileFilter?.value?.trim() || '';

        typeInput.value = types.join(',');
        if (fileInput) fileInput.value = file;

        // Update filter status
        const hasTypes = types.length > 0;
        const hasFile = file.length > 0;

        if (hasTypes || hasFile) {
            const parts = [];
            if (hasTypes) {
                parts.push(`${types.length} type${types.length > 1 ? 's' : ''}`);
            }
            if (hasFile) {
                parts.push('file');
            }
            filterStatus.textContent = `Filtering by ${parts.join(', ')}`;
            filterStatus.classList.add('active');
        } else {
            filterStatus.textContent = '';
            filterStatus.classList.remove('active');
        }

        // Update clear file button visibility
        if (clearFileBtn) clearFileBtn.style.display = hasFile ? 'flex' : 'none';
    }

    // Handle chip clicks
    filterChips.forEach(chip => {
        chip.addEventListener('click', function() {
            this.classList.toggle('active');
            updateFilterInputs();
            // Only submit if there's a query
            if (searchQuery.value.trim()) {
                form.submit();
            }
        });
    });

    // Handle file filter input (debounced)
    if (fileFilter) {
        fileFilter.addEventListener('input', (e) => {
            clearTimeout(fileFilterTimeout);
            fileFilterTimeout = setTimeout(() => {
                updateFilterInputs();
                if (searchQuery.value.trim()) {
                    form.submit();
                }
            }, 500);  // Debounce 500ms for search page (longer than dashboard)
        });
    }

    // Handle clear file filter
    if (clearFileBtn) {
        clearFileBtn.addEventListener('click', () => {
            fileFilter.value = '';
            updateFilterInputs();
            if (searchQuery.value.trim()) {
                form.submit();
            }
        });
    }

    // Handle sort dropdown change
    sortSelect.addEventListener('change', function() {
        sortInput.value = this.value;
        // Only submit if there's a query
        if (searchQuery.value.trim()) {
            form.submit();
        }
    });

    // Handle clear all filters button
    clearBtn.addEventListener('click', function() {
        // Clear all filter chips
        filterChips.forEach(chip => chip.classList.remove('active'));
        typeInput.value = '';

        // Clear file filter
        if (fileFilter) fileFilter.value = '';
        if (fileInput) fileInput.value = '';

        // Reset sort to relevance
        sortSelect.value = 'relevance';
        sortInput.value = 'relevance';

        // Update status
        filterStatus.textContent = '';
        filterStatus.classList.remove('active');
        if (clearFileBtn) clearFileBtn.style.display = 'none';

        // Only submit if there's a query
        if (searchQuery.value.trim()) {
            form.submit();
        }
    });

    // Handle clickable file tags
    document.querySelectorAll('.clickable-file').forEach(el => {
        el.addEventListener('click', () => {
            const file = el.dataset.file;
            if (fileFilter) {
                fileFilter.value = file;
                updateFilterInputs();
                form.submit();
            }
        });
    });

    // Load file suggestions
    async function loadFileSuggestions() {
        try {
            const response = await fetch(`/api/files?project=${encodeURIComponent(project)}`);
            const data = await response.json();
            const datalist = document.getElementById('file-suggestions');
            if (datalist) {
                datalist.innerHTML = data.files.map(f => `<option value="${f}">`).join('');
            }
        } catch (e) {
            console.error('Failed to load file suggestions:', e);
        }
    }

    loadFileSuggestions();
});
</script>
{% endblock %}
