{% from "components/_tabs.html" import tabs_intro %}
<header class="page-heading"><p class="eyebrow">OPERACIONES ENCUBIERTAS</p><h1>Redes de espionaje</h1><p>La infiltración, el calor y la confianza de cada informe se muestran con texto. Ninguna certeza depende solo del color.</p></header>
<div data-tab-scope="intelligence" data-tab-auto>
{{ tabs_intro('intelligence', 'Apartados de espionaje', 'Accede directamente a redes, agentes, operaciones y resultados conocidos.') }}

<section class="panel" aria-labelledby="counterintelligence-title" data-tab-panel data-tab-id="inteligencia-defensa" data-tab-label="Contrainteligencia">
  <p class="eyebrow">DEFENSA INFORMATIVA</p>
  <h2 id="counterintelligence-title">Postura de contrainteligencia</h2>
  <p>Actual: <strong>{{ counterintelligence_catalog.get(counterintelligence_posture.posture if counterintelligence_posture else 'balanced').name }}</strong>. Los señuelos nunca se presentan al observador como datos exactos confirmados: reducen confianza y obligan a mostrar intervalos.</p>
  <form method="post" action="{{ url_for('counterintelligence_posture_action') }}" class="stacked-form">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
    <label>Postura
      <select name="posture">{% for key, posture in counterintelligence_catalog.items() %}<option value="{{ key }}" {% if (counterintelligence_posture.posture if counterintelligence_posture else 'balanced') == key %}selected{% endif %}>{{ posture.name }} — {{ posture.description }} — coste {{ posture.cost }} créditos</option>{% endfor %}</select>
    </label>
    <button class="button button-primary" type="submit">Aplicar postura y pagar reorganización</button>
  </form>
</section>

<section class="panel panel-wide" aria-labelledby="intelligence-archive-title" data-tab-panel data-tab-id="inteligencia-informes" data-tab-label="Informes contrastados">
  <p class="eyebrow">CONFIANZA POR CATEGORÍA</p>
  <h2 id="intelligence-archive-title">Archivo de observaciones</h2>
  <p>Confirmado significa al menos 85 % de confianza; probable, entre 60 y 84 %; incierto, menos de 60 %. Las cifras no confirmadas se muestran como intervalos.</p>
  {% if intelligence_archive %}
  <form method="get" action="{{ url_for('game_view', section='intelligence') }}" class="inline-form">
    <label>Informe anterior<select name="compare_from">{% for report in intelligence_archive %}<option value="{{ report.row.id }}">{{ report.row.target_name }} · {{ report.row.observed_at|date_label }} · {{ report.row.confidence }} %</option>{% endfor %}</select></label>
    <label>Informe posterior<select name="compare_to">{% for report in intelligence_archive %}<option value="{{ report.row.id }}">{{ report.row.target_name }} · {{ report.row.observed_at|date_label }} · {{ report.row.confidence }} %</option>{% endfor %}</select></label>
    <button class="button" type="submit">Comparar dos informes del mismo objetivo</button>
  </form>
  {% if intelligence_comparison %}
    <section class="notice" aria-labelledby="intelligence-comparison-title" tabindex="-1"><h3 id="intelligence-comparison-title">Cambios en {{ intelligence_comparison.target }}</h3><p>Variación de confianza global: {{ '%+d'|format(intelligence_comparison.confidence_delta) }} puntos. La comparación conserva los intervalos de cada observación y no revela los valores internos.</p>{% if intelligence_comparison.changes %}<ul>{% for category in intelligence_comparison.changes %}<li><strong>{{ category.category }}</strong><ul>{% for change in category.changes %}<li>{{ change.key }}: {% if change.before is mapping %}entre {{ change.before.min }} y {{ change.before.max }}{% elif change.before is not none %}{{ change.before }} confirmado{% else %}sin dato{% endif %} ({{ change.before_label }}) → {% if change.after is mapping %}entre {{ change.after.min }} y {{ change.after.max }}{% elif change.after is not none %}{{ change.after }} confirmado{% else %}sin dato{% endif %} ({{ change.after_label }})</li>{% endfor %}</ul></li>{% endfor %}</ul>{% else %}<p>No se observaron diferencias numéricas visibles.</p>{% endif %}</section>
  {% endif %}
  <div class="card-grid">
    {% for report in intelligence_archive %}
    <article class="entity-card">
      <h3>{{ report.row.target_name }} [{{ report.row.galaxy }}:{{ report.row.system }}:{{ report.row.position }}]</h3>
      <p><time datetime="{{ report.row.observed_at|date_iso }}">{{ report.row.observed_at|date_label }}</time>. Confianza global {{ report.row.confidence }} %.</p>
      {% if report.row.possibly_false %}<p class="notice notice-warning"><strong>Posibles señuelos.</strong> Ningún valor incierto debe interpretarse como una cifra exacta.</p>{% endif %}
      {% for category, details in report.estimates.items() %}
        <h4>{{ category }}: {{ details.label }}, {{ details.confidence }} %</h4>
        {% if details['values'] %}<ul>{% for key, value in details['values'].items() %}<li>{{ key }}: {% if value is mapping %}entre {{ value.min }} y {{ value.max }}{% else %}{{ value }} confirmado{% endif %}</li>{% endfor %}</ul>{% else %}<p>Sin datos observables.</p>{% endif %}
      {% endfor %}
    </article>
    {% endfor %}
  </div>
  {% else %}<p class="empty-state">Aún no hay informes de sondas para contrastar.</p>{% endif %}
</section>

<section class="panel" aria-labelledby="network-create-title"><h2 id="network-create-title">Establecer red</h2>{% if spy_targets %}<form method="post" action="{{ url_for('spy_network_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Objetivo <select name="target_empire_id">{% for target in spy_targets %}<option value="{{ target.id }}">{{ target.name }} · {{ target.score|number }} puntos</option>{% endfor %}</select></label><button class="button" type="submit">Establecer por 5 de influencia</button></form>{% else %}<p>Ya existe una red para cada rival disponible.</p>{% endif %}</section>

<section class="panel" aria-labelledby="agents-title"><h2 id="agents-title">Agentes</h2><form method="post" action="{{ url_for('spy_agent_action') }}" class="form-grid"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Nombre <input name="name" maxlength="40" required></label><label>Especialidad <select name="specialty"><option value="infiltration">Infiltración</option><option value="technology">Tecnología</option><option value="sabotage">Sabotaje</option><option value="counterintelligence">Contrainteligencia</option><option value="diplomacy">Diplomacia</option></select></label><button class="button" type="submit">Reclutar por 500 créditos</button></form>{% if agents %}<ul>{% for agent in agents %}<li>{{ agent.name }}: {{ agent.specialty }}, nivel {{ agent.level }}, estado {{ agent.status }}{% if agent.target_name %}, destinado en {{ agent.target_name }}{% endif %}.</li>{% endfor %}</ul>{% endif %}</section>

<section class="panel" aria-labelledby="networks-title"><h2 id="networks-title">Redes activas</h2>{% if spy_networks %}<div class="card-grid">{% for network in spy_networks %}<article class="entity-card"><h3>{{ network.target_name }}</h3><dl><div><dt>Infiltración</dt><dd>{{ network.infiltration|round(1) }} de 100</dd></div><div><dt>Calor</dt><dd>{{ network.heat|round(1) }} de 100</dd></div><div><dt>Contrainteligencia estimada</dt><dd>{{ network.counterintelligence|round(1) }}</dd></div></dl><form method="post" action="{{ url_for('spy_operation_action') }}" class="stacked-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="target_empire_id" value="{{ network.target_empire_id }}"><label>Agente disponible <select name="agent_id" required>{% for agent in agents if agent.status == 'available' %}<option value="{{ agent.id }}">{{ agent.name }} · nivel {{ agent.level }}</option>{% endfor %}</select></label><label>Operación <select name="operation_key">{% for key, operation in SPY_OPERATIONS.items() %}<option value="{{ key }}">{{ operation.name }} · infiltración {{ operation.infiltration }}</option>{% endfor %}</select></label><button class="button" type="submit">Preparar operación</button></form></article>{% endfor %}</div>{% else %}<p>No hay redes activas.</p>{% endif %}</section>

<section class="panel" aria-labelledby="operations-title"><h2 id="operations-title">Operaciones e información</h2>{% if covert_operations %}<ol>{% for operation in covert_operations %}<li><strong>{{ SPY_OPERATIONS[operation.operation_key].name }}</strong> contra {{ operation.target_name }}; agente {{ operation.agent_name or 'no disponible' }}; estado {{ operation.status }}. {% if operation.result_text %}{{ operation.result_text }} Fiabilidad declarada: {{ operation.confidence }} %.{% else %}Conclusión prevista {{ operation.completes_at|date_label }}.{% endif %}</li>{% endfor %}</ol>{% else %}<p>No hay operaciones.</p>{% endif %}{% if spy_assets %}<h3>Activos</h3><ul>{% for asset in spy_assets %}<li>{{ asset.name }} en {{ asset.target_name }}: {{ asset.asset_type }}, fiabilidad {{ asset.reliability }} %, {{ 'expuesto' if asset.exposed else 'oculto' }}.</li>{% endfor %}</ul>{% endif %}</section>
</div>
