{% extends "base.html" %}
{% block title %}Поиск — TG Agent{% endblock %}
{% block content %}
<h1>Поиск по постам</h1>

<form method="get" action="/search" data-busy>
    <div class="mb-3">
        <label for="q" class="form-label">Запрос</label>
        <input type="text" class="form-control" id="q" name="q" value="{{ q }}" placeholder="Введите поисковый запрос" autofocus>
    </div>

    <div class="row g-3 mb-3">
        <div class="col-12 col-sm-6 col-md-3">
            <label for="channel-select" class="form-label">Канал</label>
            <select name="channel_id" id="channel-select" class="form-select">
                <option value="">Все каналы</option>
                {% for ch in channels %}
                <option value="{{ ch.channel_id }}" {{ 'selected' if channel_id == ch.channel_id else '' }}>
                    {{ ch.title or ch.username or ch.channel_id }}
                </option>
                {% endfor %}
            </select>
        </div>
        <div class="col-6 col-sm-6 col-md-3">
            <label for="date-from" class="form-label">Дата от</label>
            <input type="date" class="form-control" name="date_from" id="date-from" value="{{ date_from }}">
        </div>
        <div class="col-6 col-sm-6 col-md-3">
            <label for="date-to" class="form-label">Дата до</label>
            <input type="date" class="form-control" name="date_to" id="date-to" value="{{ date_to }}">
        </div>
    </div>

    <div class="d-flex align-items-center gap-3 flex-wrap mb-3">
        <div class="form-check form-check-inline" title="Поиск по ранее собранным сообщениям в локальной базе данных">
            <input class="form-check-input" type="radio" name="mode" id="mode-local" value="local" {{ 'checked' if mode == 'local' else '' }}>
            <label class="form-check-label" for="mode-local">Локальная база</label>
        </div>
        <div class="form-check form-check-inline" title="Семантический поиск по локальной базе через embeddings и semantic backend">
            <input class="form-check-input" type="radio" name="mode" id="mode-semantic" value="semantic" {{ 'checked' if mode == 'semantic' else '' }}>
            <label class="form-check-label" for="mode-semantic">Семантический</label>
        </div>
        <div class="form-check form-check-inline" title="Гибридный поиск: объединяет FTS5 и semantic retrieval">
            <input class="form-check-input" type="radio" name="mode" id="mode-hybrid" value="hybrid" {{ 'checked' if mode == 'hybrid' else '' }}>
            <label class="form-check-label" for="mode-hybrid">Гибридный</label>
        </div>
        <div class="form-check form-check-inline" title="Поиск по всем чатам и каналам подключённого аккаунта через Telegram API">
            <input class="form-check-input" type="radio" name="mode" id="mode-my-chats" value="my_chats" {{ 'checked' if mode == 'my_chats' else '' }}>
            <label class="form-check-label" for="mode-my-chats">Мои чаты</label>
        </div>
        <div class="form-check form-check-inline" title="Поиск внутри выбранного канала через Telegram API">
            <input class="form-check-input" type="radio" name="mode" id="mode-channel" value="channel" {{ 'checked' if mode == 'channel' else '' }}>
            <label class="form-check-label" for="mode-channel">В канале</label>
        </div>
        <div class="form-check form-check-inline" title="Глобальный поиск по публичным каналам (требуется Telegram Premium)">
            <input class="form-check-input" type="radio" name="mode" id="mode-telegram" value="telegram" {{ 'checked' if mode == 'telegram' else '' }}>
            <label class="form-check-label" for="mode-telegram">Публичные (Premium)</label>
        </div>
        {% if search_quota and search_quota.remains is not none %}
        <small id="quota-info" class="text-muted">
            Premium-поиск: осталось {{ search_quota.remains }}{% if search_quota.total_daily %} из {{ search_quota.total_daily }}{% endif %} сегодня
        </small>
        {% endif %}
        {% if ai_enabled %}
        <div class="form-check form-check-inline" title="Семантический поиск с помощью LLM по локальной базе">
            <input class="form-check-input" type="radio" name="mode" id="mode-ai" value="ai" {{ 'checked' if mode == 'ai' else '' }}>
            <label class="form-check-label" for="mode-ai">AI-поиск</label>
        </div>
        {% endif %}
        <div class="form-check form-check-inline" id="fts-label" title="Полнотекстовый поиск FTS5 (поддерживает операторы AND, OR, NOT, фразы в кавычках)">
            <input class="form-check-input" type="checkbox" name="is_fts" value="1" id="fts-checkbox" {{ 'checked' if is_fts else '' }}>
            <label class="form-check-label" for="fts-checkbox">FTS5 <span class="hint" data-tooltip="Полнотекстовый поиск с поддержкой операторов: OR, AND, NOT, префикс*, «точная фраза», len&lt;400, len&gt;100">?</span></label>
        </div>
        <button type="submit" class="btn btn-primary ms-auto">Найти</button>
    </div>
</form>

{% if result %}
<hr>

{% if result.error %}
<div class="alert alert-danger">
    <strong>Ошибка:</strong> {{ result.error }}
</div>
{% endif %}

{% if result.ai_summary %}
<div class="card mb-3">
    <div class="card-header fw-semibold">AI-анализ</div>
    <div class="card-body"><p class="mb-0">{{ result.ai_summary }}</p></div>
</div>
{% endif %}

{% if not result.error %}
<p>Найдено: <strong>{{ result.total }}</strong> сообщений по запросу «{{ result.query }}»</p>
{% endif %}

{% if result.messages %}
<!-- Desktop: table -->
<div class="table-responsive d-none d-md-block">
<table class="table table-striped table-hover table-sm">
    <thead>
        <tr>
            <th>Дата</th>
            <th>Канал</th>
            <th>Отправитель</th>
            <th>Медиа</th>
            <th>Текст</th>
            <th>Охват</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        {% for msg in result.messages %}
        <tr>
            <td class="text-nowrap">{{ msg.date|local_dt }}</td>
            <td>{{ msg.channel_title or msg.channel_username or msg.channel_id }}</td>
            <td>{{ msg.sender_name or "—" }}</td>
            <td>{{ msg.media_type or "—" }}</td>
            <td>{{ msg.text[:300] if msg.text else "—" }}{{ "..." if msg.text and msg.text|length > 300 else "" }}</td>
            <td class="text-nowrap text-muted" style="font-size:0.8rem">
                {%- if msg.views is not none %}👁 {{ msg.views }}{% endif %}
                {%- if msg.forwards is not none %} ↗ {{ msg.forwards }}{% endif %}
                {%- if msg.reply_count is not none %} 💬 {{ msg.reply_count }}{% endif %}
                {%- if msg.views is none and msg.forwards is none and msg.reply_count is none %}—{% endif %}
            </td>
            <td>{% if msg.channel_username %}<a href="https://t.me/{{ msg.channel_username }}/{{ msg.message_id }}" target="_blank" rel="noopener" title="Открыть в Telegram">&#8599;</a>{% else %}<a href="https://t.me/c/{{ msg.channel_id }}/{{ msg.message_id }}" target="_blank" rel="noopener" title="Открыть в Telegram">&#8599;</a>{% endif %}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>
</div>

<!-- Mobile: cards -->
<div class="d-md-none mobile-cards">
    {% for msg in result.messages %}
    <div class="card mb-2">
        <div class="card-body">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <strong class="text-truncate">{{ msg.channel_title or msg.channel_username or msg.channel_id }}</strong>
                {% if msg.channel_username %}<a href="https://t.me/{{ msg.channel_username }}/{{ msg.message_id }}" target="_blank" rel="noopener">&#8599;</a>{% else %}<a href="https://t.me/c/{{ msg.channel_id }}/{{ msg.message_id }}" target="_blank" rel="noopener">&#8599;</a>{% endif %}
            </div>
            <small class="text-muted">{{ msg.date|local_dt }}{% if msg.sender_name %} &middot; {{ msg.sender_name }}{% endif %}{% if msg.media_type %} &middot; {{ msg.media_type }}{% endif %}</small>
            <p class="mb-0 mt-1" style="font-size:0.85rem">{{ msg.text[:200] if msg.text else "—" }}{{ "..." if msg.text and msg.text|length > 200 else "" }}</p>
            {%- if msg.views is not none or msg.forwards is not none or msg.reply_count is not none %}
            <small class="text-muted">
                {%- if msg.views is not none %}👁 {{ msg.views }}{% endif %}
                {%- if msg.forwards is not none %} ↗ {{ msg.forwards }}{% endif %}
                {%- if msg.reply_count is not none %} 💬 {{ msg.reply_count }}{% endif %}
            </small>
            {%- endif %}
        </div>
    </div>
    {% endfor %}
</div>

{% if total_pages > 1 %}
<nav>
    <ul class="pagination justify-content-center">
        {% if page > 1 %}
        <li class="page-item"><a class="page-link" href="/search?q={{ q|urlencode }}&channel_id={{ channel_id or '' }}&date_from={{ date_from }}&date_to={{ date_to }}&mode={{ mode }}&is_fts={{ 1 if is_fts else 0 }}&page={{ page - 1 }}">Назад</a></li>
        {% endif %}
        <li class="page-item disabled"><span class="page-link">Страница {{ page }} из {{ total_pages }}</span></li>
        {% if page < total_pages %}
        <li class="page-item"><a class="page-link" href="/search?q={{ q|urlencode }}&channel_id={{ channel_id or '' }}&date_from={{ date_from }}&date_to={{ date_to }}&mode={{ mode }}&is_fts={{ 1 if is_fts else 0 }}&page={{ page + 1 }}">Далее</a></li>
        {% endif %}
    </ul>
</nav>
{% endif %}

{% else %}
<p>Ничего не найдено.</p>
{% endif %}

{% endif %}

<script>
(function() {
    var radios = document.querySelectorAll('input[name="mode"]');
    var channelSelect = document.getElementById('channel-select');
    var dateFrom = document.getElementById('date-from');
    var dateTo = document.getElementById('date-to');
    var ftsLabel = document.getElementById('fts-label');
    var ftsCheckbox = document.getElementById('fts-checkbox');

    function updateState() {
        var mode = document.querySelector('input[name="mode"]:checked').value;
        var usesLocalDb = (mode === 'local' || mode === 'semantic' || mode === 'hybrid');
        var supportsFtsToggle = (mode === 'local' || mode === 'hybrid');
        channelSelect.disabled = !(mode === 'local' || mode === 'semantic' || mode === 'hybrid' || mode === 'channel');
        dateFrom.disabled = !usesLocalDb;
        dateTo.disabled = !usesLocalDb;
        ftsLabel.style.display = supportsFtsToggle ? '' : 'none';
        ftsCheckbox.disabled = !supportsFtsToggle;
    }

    radios.forEach(function(r) {
        r.addEventListener('change', updateState);
    });

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