        {% from "components/_tabs.html" import tabs_intro %}
        <header class="page-heading"><p class="eyebrow">ARCHIVO IMPERIAL</p><h1>Informes</h1><p>Busca, filtra, marca y archiva resultados sin perder la memoria de tu universo.</p></header>
        <div data-tab-scope="messages">
        {{ tabs_intro('messages', 'Apartados de informes', 'Separa la búsqueda, la automatización y los resultados sin retirar ninguna herramienta.') }}
        <div class="button-row"><a class="button" href="{{ url_for('general_report_export_action', format_name='md') }}">Descargar informe general Markdown</a><a class="button" href="{{ url_for('general_report_export_action', format_name='bbcode') }}">Descargar informe general para foros</a><a class="button" href="{{ url_for('general_report_export_action', format_name='json') }}">Descargar informe general JSON</a></div>
        <section class="panel" aria-labelledby="report-filters-title" data-tab-panel data-tab-id="informes-busqueda" data-tab-label="Buscar y filtrar"><p class="eyebrow">BANDEJA ORGANIZABLE</p><h2 id="report-filters-title">Buscar y filtrar informes</h2><form method="get" action="{{ url_for('game_view', section='messages') }}" class="report-filter-form"><label for="report-search">Texto<input id="report-search" name="q" type="search" value="{{ report_filters.q }}" placeholder="Asunto o contenido"></label><label for="report-view">Colección<select id="report-view" name="view"><option value="inbox" {% if report_filters.view == 'inbox' %}selected{% endif %}>Bandeja</option><option value="starred" {% if report_filters.view == 'starred' %}selected{% endif %}>Favoritos</option><option value="archived" {% if report_filters.view == 'archived' %}selected{% endif %}>Archivo</option></select></label><label for="report-category">Categoría<select id="report-category" name="category"><option value="">Todas</option>{% for category in message_categories %}<option value="{{ category.category }}" {% if report_filters.category == category.category %}selected{% endif %}>{{ category.category }} ({{ category.n }})</option>{% endfor %}</select></label><label class="check-row"><input type="checkbox" name="group" value="1" {% if report_filters.group %}checked{% endif %}> Agrupar conversaciones por batalla, objetivo, expedición o crisis</label><button class="button" type="submit">Aplicar filtros</button><a class="button button-secondary" href="{{ url_for('game_view', section='messages') }}">Limpiar</a></form><p role="status">{{ messages|length }} {{ 'conversación mostrada' if report_filters.group and messages|length == 1 else 'conversaciones mostradas' if report_filters.group else 'informe mostrado' if messages|length == 1 else 'informes mostrados' }}.</p></section>
        <section class="panel" aria-labelledby="advanced-report-tools-title" data-tab-panel data-tab-id="informes-reglas" data-tab-label="Reglas y conservación"><p class="eyebrow">AUTOMATIZACIÓN Y CONSERVACIÓN</p><h2 id="advanced-report-tools-title">Reglas, búsquedas y retención</h2>
          <div class="dashboard-grid">
            <form method="post" action="{{ url_for('report_rule_action') }}" class="stacked-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><h3>Nueva regla</h3><label>Nombre<input name="name" maxlength="60" required></label><label>Categoría opcional<input name="category" maxlength="40"></label><label>Texto que debe contener<input name="contains_text" maxlength="80"></label><label>Acción<select name="rule_action">{% for key, label in MESSAGE_RULE_ACTIONS.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label><label>Etiqueta, si corresponde<input name="label" maxlength="40"></label><button class="button button-primary" type="submit">Guardar regla</button></form>
            <form method="post" action="{{ url_for('report_search_save_action') }}" class="stacked-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><h3>Guardar búsqueda actual</h3><label>Nombre<input name="name" maxlength="60" required></label><input type="hidden" name="query" value="{{ report_filters.q }}"><input type="hidden" name="category" value="{{ report_filters.category }}"><input type="hidden" name="view_mode" value="{{ report_filters.view }}"><p>Texto: {{ report_filters.q or 'cualquiera' }}; categoría: {{ report_filters.category or 'todas' }}; colección: {{ report_filters.view }}.</p><button class="button" type="submit">Guardar búsqueda</button></form>
          </div>
          {% if saved_report_searches %}<nav aria-label="Búsquedas guardadas"><ul>{% for search in saved_report_searches %}<li><a href="{{ url_for('game_view', section='messages', q=search.query_text, category=search.category, view=search.view_mode) }}">{{ search.name }}</a></li>{% endfor %}</ul></nav>{% endif %}
          {% if message_rules %}<div class="table-wrap"><table><caption>Reglas aplicadas en orden de creación a cada informe nuevo.</caption><thead><tr><th scope="col">Regla</th><th scope="col">Condición</th><th scope="col">Acción</th><th scope="col">Estado</th></tr></thead><tbody>{% for rule in message_rules %}<tr><th scope="row">{{ rule.name }}</th><td>{{ rule.category or 'cualquier categoría' }}{% if rule.contains_text %}; contiene «{{ rule.contains_text }}»{% endif %}</td><td>{{ MESSAGE_RULE_ACTIONS[rule.action] }}{% if rule.label %}: {{ rule.label }}{% endif %}</td><td><form method="post" action="{{ url_for('report_rule_toggle_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="rule_id" value="{{ rule.id }}"><button class="button" type="submit">{{ 'Desactivar' if rule.enabled else 'Activar' }}; ahora {{ 'activa' if rule.enabled else 'inactiva' }}</button></form></td></tr>{% endfor %}</tbody></table></div>{% endif %}
          <div class="dashboard-grid"><form method="post" action="{{ url_for('report_retention_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Días de retención<input name="retention_days" type="number" min="30" max="3650" value="{{ report_retention.retention_days }}"></label><button class="button" type="submit">Guardar retención</button></form><form method="post" action="{{ url_for('report_cleanup_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="button button-danger" type="submit">Crear copia y limpiar informes vencidos</button></form></div>
        </section>
        {% if messages %}<section aria-labelledby="received-reports-title" data-tab-panel data-tab-id="informes-resultados" data-tab-label="Resultados"><h2 id="received-reports-title" class="section-title">Resultados</h2>
          <form id="reports-export-form" method="post" action="{{ url_for('report_export_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Formato<select name="format"><option value="md">Markdown</option><option value="csv">CSV</option><option value="json">JSON</option></select></label><button class="button" type="submit">Exportar informes seleccionados</button></form>
          <ol class="message-list">{% for message in messages %}{% set combat = combat_reports.get(message.id) %}<li><article><header><span class="report-category">{{ message.category }}{% if message.starred %} · Favorito{% endif %}{% if message_labels.get(message.id) %} · {{ message_labels[message.id] }}{% endif %}{% if report_filters.group %} · {{ message.thread_count }} informes en esta conversación{% endif %}</span><h3>{{ message.subject }}</h3><time datetime="{{ message.created_at|date_iso }}">{{ message.created_at|date_label }}</time></header><label class="check-row"><input form="reports-export-form" type="checkbox" name="message_ids" value="{{ message.id }}"> Seleccionar este informe para exportarlo</label><p>{{ message.body }}</p>{% if combat %}{% set rounds = combat.rounds_json|from_json %}{% set losses = combat.losses_json|from_json %}{% set factors = combat.factors_json|from_json %}{% set loot = combat.loot_json|from_json %}{% set debris = combat.debris_json|from_json %}<details><summary>Mostrar informe de combate detallado por rondas</summary><p><strong>{{ combat.result }}</strong> en {{ combat.coordinates }}. Pérdidas totales: atacante {{ losses.attacker.total }}, defensor {{ losses.defender.total }}. Botín: {{ loot.metal }} metal, {{ loot.crystal }} cristal y {{ loot.deuterium }} deuterio. Escombros: {{ debris.metal }} metal, {{ debris.crystal }} cristal y {{ debris.get('deuterium',0) }} deuterio.</p><div class="button-row"><a class="button" href="{{ url_for('battle_report_export_action', report_id=combat.id, format_name='bbcode') }}">Descargar batalla para foros</a><a class="button" href="{{ url_for('battle_report_export_action', report_id=combat.id, format_name='md') }}">Descargar batalla Markdown</a><a class="button" href="{{ url_for('battle_report_export_action', report_id=combat.id, format_name='json') }}">Descargar datos de la batalla</a></div><div class="table-wrap"><table><caption>Rondas de combate</caption><thead><tr><th scope="col">Ronda</th><th scope="col">Daño atacante</th><th scope="col">Daño defensor</th><th scope="col">Absorción atacante</th><th scope="col">Absorción defensora</th><th scope="col">Supervivientes</th><th scope="col">Bajas por clase</th></tr></thead><tbody>{% for round in rounds %}<tr><th scope="row">{{ round.round }}</th><td>{{ round.attacker_damage|number }}</td><td>{{ round.defender_damage|number }}</td><td>{{ round.attacker_absorbed|number }}</td><td>{{ round.defender_absorbed|number }}</td><td>{{ round.attacker_survivors }} atacantes; {{ round.defender_survivors }} defensores</td><td>Atacante: {% for key, amount in round.attacker_losses.items() %}{{ key }} {{ amount }}{% if not loop.last %}, {% endif %}{% else %}ninguna{% endfor %}. Defensor: {% for key, amount in round.defender_losses.items() %}{{ key }} {{ amount }}{% if not loop.last %}, {% endif %}{% else %}ninguna{% endfor %}.</td></tr>{% endfor %}</tbody></table></div><h4>Tres factores decisivos</h4><ol>{% for factor in factors %}<li><strong>{{ factor.name }}:</strong> atacante {{ factor.attacker }}; defensor {{ factor.defender }}.</li>{% endfor %}</ol></details>{% endif %}<form method="post" action="{{ url_for('message_manage_action') }}" class="button-row"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="message_id" value="{{ message.id }}"><button class="button" name="action" value="toggle_star" type="submit">{{ 'Quitar de favoritos' if message.starred else 'Añadir a favoritos' }}</button>{% if message.archived %}<button class="button" name="action" value="restore" type="submit">Restaurar a la bandeja</button>{% else %}<button class="button button-secondary" name="action" value="archive" type="submit">Archivar</button>{% endif %}</form></article></li>{% endfor %}</ol></section>{% else %}<section class="panel" data-tab-panel data-tab-id="informes-resultados" data-tab-label="Resultados" aria-labelledby="received-reports-title"><h2 id="received-reports-title">Resultados</h2><p class="empty-state">No hay informes que coincidan con los filtros.</p></section>{% endif %}
        </div>
