        {% from "components/_tabs.html" import tabs_intro %}
        <header class="page-heading"><p class="eyebrow">SENADO INTERESTELAR</p><h1>Diplomacia</h1><p>Negocia pactos comerciales, acuerdos de no agresión y tratados de paz. Cada personalidad de IA valora las propuestas de forma distinta.</p></header>
        <div data-tab-scope="diplomacy" data-tab-auto>
        {{ tabs_intro('diplomacy', 'Apartados de diplomacia', 'Separa alianzas, proyectos, guerras y relaciones bilaterales para reducir el recorrido de la pantalla.') }}
        {% set status_names = {'neutral':'Neutral','trade':'Pacto comercial','non_aggression':'No agresión','war':'Guerra','alliance':'Alianza'} %}
        {% if alliance_invitations %}<section class="panel" aria-labelledby="alliance-invitations-title"><p class="eyebrow">PROPUESTAS RECIBIDAS</p><h2 id="alliance-invitations-title">Invitaciones de alianza</h2><div class="stacked-actions">{% for invitation in alliance_invitations %}<article class="notice"><h3>{{ invitation.name }} [{{ invitation.tag }}]</h3><p>{{ invitation.inviter_name }} propone que tu imperio se incorpore.</p><form method="post" action="{{ url_for('alliance_respond_action') }}" class="button-row"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="invitation_id" value="{{ invitation.id }}"><button class="button button-primary" name="response" value="accept" type="submit">Aceptar invitación</button><button class="button" name="response" value="reject" type="submit">Rechazar</button></form></article>{% endfor %}</div></section>{% endif %}
        {% if alliance %}
          <section class="panel" aria-labelledby="alliance-title"><div class="panel-heading"><div><p class="eyebrow">ALIANZA ACTUAL</p><h2 id="alliance-title">{{ alliance.name }} [{{ alliance.tag }}]</h2></div><span>Rango: {{ {'leader':'Liderazgo','officer':'Oficial','member':'Miembro'}[alliance.rank] }}</span></div><p>{{ alliance.description or 'Alianza dedicada a la defensa, el comercio y la cooperación.' }}</p><div class="table-wrap"><table><caption>Miembros actuales de la alianza.</caption><thead><tr><th scope="col">Imperio</th><th scope="col">Comandante</th><th scope="col">Tipo</th><th scope="col">Rango</th><th scope="col">Puntos</th></tr></thead><tbody>{% for member in alliance_members %}<tr><th scope="row">{{ member.name }}{% if member.empire_id == empire.id %} (tú){% endif %}</th><td>{{ member.commander }}</td><td>{{ 'Humano' if member.is_human else 'Mundo-granja' if member.is_farm_world else 'IA ' ~ AI_STYLES[member.ai_style] }}</td><td>{{ member.rank }}</td><td>{{ member.score|number }}</td></tr>{% endfor %}</tbody></table></div>{% if alliance.rank in ['leader','officer'] %}<form method="post" action="{{ url_for('alliance_invite_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Invitar imperio<select name="rival_id">{% for relation in relations %}{% if relation.rival_id not in allied_empire_ids and relation.status != 'war' %}<option value="{{ relation.rival_id }}">{{ relation.rival_name }} — confianza {{ relation.trust }}</option>{% endif %}{% endfor %}</select></label><button class="button" type="submit">Enviar invitación</button></form>{% endif %}<form method="post" action="{{ url_for('alliance_leave_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><button class="button button-danger" type="submit">Abandonar alianza</button></form></section>
        {% else %}
          <section class="panel" aria-labelledby="found-alliance-title"><p class="eyebrow">COOPERACIÓN MULTILATERAL</p><h2 id="found-alliance-title">Fundar una alianza</h2><p>Después podrás invitar IA, mundos-granja y futuros socios. Los miembros no pueden atacarse, obtienen confianza compartida y cuentan como socios comerciales.</p><form method="post" action="{{ url_for('alliance_create_action') }}" class="stacked-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Nombre<input name="name" maxlength="48" value="Alianza del Horizonte" required></label><label>Sigla, 2 a 6 caracteres<input name="tag" minlength="2" maxlength="6" value="ADH" required></label><label>Declaración<textarea name="description" maxlength="240" rows="3">Defensa mutua, comercio justo y exploración compartida.</textarea></label><button class="button button-primary" type="submit">Fundar alianza</button></form></section>
        {% endif %}
        {% if alliance %}
        <section class="panel" aria-labelledby="alliance-development-title">
          <p class="eyebrow">COOPERACIÓN PERSISTENTE</p><h2 id="alliance-development-title">Doctrina, tesorería e infraestructura</h2>
          <p>Doctrina actual: <strong>{{ alliance.doctrine }}</strong>. Las aportaciones salen de reservas reales y quedan registradas en una tesorería común.</p>
          {% if alliance_depot_status %}<dl class="settings-list"><div><dt>Miembros que aún sostienen mundos</dt><dd>{{ alliance_depot_status.active_member_count }} de {{ alliance_depot_status.members|length }}</dd></div><div><dt>Niveles de Depósito de alianza activos</dt><dd>{{ alliance_depot_status.depot_levels }}</dd></div><div><dt>Capacidad de infraestructura</dt><dd>{{ alliance_depot_status.used_capacity }} de {{ alliance_depot_status.capacity }} niveles</dd></div><div><dt>Capacidad libre</dt><dd>{{ alliance_depot_status.available_capacity }} niveles</dd></div></dl><p>Los miembros derrotados o que abandonan dejan de aportar capacidad automáticamente. Cada nivel operativo consume 25 créditos de tesorería por hora.</p>{% endif %}
          {% if alliance_treasury %}<dl class="settings-list"><div><dt>Créditos</dt><dd>{{ alliance_treasury.credits|number }}</dd></div><div><dt>Metal</dt><dd>{{ alliance_treasury.metal|number }}</dd></div><div><dt>Cristal</dt><dd>{{ alliance_treasury.crystal|number }}</dd></div><div><dt>Deuterio</dt><dd>{{ alliance_treasury.deuterium|number }}</dd></div><div><dt>Alimento</dt><dd>{{ alliance_treasury.food|number }}</dd></div></dl>{% endif %}
          <div class="card-grid">{% for project in alliance_projects %}{% set definition = ALLIANCE_PROJECTS[project.project_key] %}<article class="tech-card"><div class="card-copy"><h3>{{ definition.name }} · nivel {{ project.level }}</h3><p><strong>Estado:</strong> {{ 'Operativo' if project.operational else 'Inactivo por capacidad o mantenimiento' }}.</p><p>{{ definition.description }} {{ definition.effect }}</p><p>Progreso: {{ project.progress|number }} de {{ project.target|number }}. Mantenimiento al nivel actual: {{ project.level * 25 }} créditos por hora.</p><progress value="{{ project.progress }}" max="{{ project.target }}">{{ (project.progress/project.target*100)|round }} %</progress></div><form method="post" action="{{ url_for('alliance_project_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="project_key" value="{{ project.project_key }}"><label>Recurso<select name="resource"><option value="credits">Créditos</option><option value="metal">Metal</option><option value="crystal">Cristal</option><option value="deuterium">Deuterio</option><option value="food">Alimento</option></select></label><label>Cantidad<input name="amount" type="number" min="1" max="1000000" value="1000"></label><button class="button" type="submit">Aportar recursos reales</button></form></article>{% endfor %}</div>
        </section>
        <section class="panel" aria-labelledby="alliance-assignments-title"><h2 id="alliance-assignments-title">Encargos a miembros de IA</h2>
          <form method="post" action="{{ url_for('alliance_assignment_action') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><label>Miembro<select name="assignee_id">{% for member in alliance_members %}{% if not member.is_human %}<option value="{{ member.empire_id }}">{{ member.name }}</option>{% endif %}{% endfor %}</select></label><label>Tarea<select name="assignment_key">{% for key, values in ALLIANCE_ASSIGNMENTS.items() %}<option value="{{ key }}">{{ values[0] }} · {{ values[1]|duration }}</option>{% endfor %}</select></label><button class="button" type="submit">Solicitar por 4 de influencia</button></form>
          {% if alliance_assignments %}<ol class="activity-list">{% for assignment in alliance_assignments %}<li><div><strong>{{ assignment.assignee_name }} · {{ ALLIANCE_ASSIGNMENTS[assignment.assignment_key][0] }}</strong><span>{{ assignment.result_text or 'Encargo en ejecución' }}</span></div><span>{{ assignment.status }}{% if assignment.status == 'active' %} · <time class="countdown" data-end="{{ assignment.completes_at }}">{{ (assignment.completes_at-now)|duration }}</time>{% endif %}</span></li>{% endfor %}</ol>{% endif %}
        </section>
        <section class="panel" aria-labelledby="alliance-wars-title"><h2 id="alliance-wars-title">Guerras puntuadas e historial</h2>
          {% if alliance_wars %}<div class="table-wrap"><table><caption>Conflictos de tu alianza, con protección explícita del bando más débil.</caption><thead><tr><th scope="col">Bandos</th><th scope="col">Objetivo</th><th scope="col">Marcador</th><th scope="col">Estado y protección</th><th scope="col">Acción</th></tr></thead><tbody>{% for war in alliance_wars %}<tr><th scope="row">{{ war.alliance_a_name }} contra {{ war.alliance_b_name }}</th><td>{{ war.objective }}</td><td>{{ war.score_a|round(1) }} a {{ war.score_b|round(1) }}</td><td>{{ war.status }}{% if war.protection_side %}; protección para alianza {{ war.protection_side }}{% endif %}</td><td>{% if war.status == 'active' %}<form method="post" action="{{ url_for('alliance_mediate_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="war_id" value="{{ war.id }}"><button class="button" type="submit">Mediar por 15 de influencia</button></form>{% else %}Conservado en el historial{% endif %}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="empty-state">La alianza no participa en ninguna guerra puntuada.</p>{% endif %}
        </section>
        {% if alliance_history %}<section class="panel" aria-labelledby="alliance-history-title"><h2 id="alliance-history-title">Memoria de la alianza</h2><ol class="activity-list">{% for entry in alliance_history %}<li><div><strong>{{ entry.title }}</strong><span>{{ entry.detail }}</span></div><span>{{ entry.kind }} · <time datetime="{{ entry.created_at|date_iso }}">{{ entry.created_at|date_label }}</time></span></li>{% endfor %}</ol></section>{% endif %}
        {% endif %}
        <section aria-labelledby="civilizations-title"><h2 id="civilizations-title" class="section-title">Civilizaciones conocidas</h2><div class="diplomacy-grid">{% for relation in relations %}<article class="diplomacy-card">
          <header><span class="faction-dot large" style="--faction-color:{{ relation.color }}" aria-hidden="true"></span><div><h3>{{ relation.rival_name }}</h3><p>{{ relation.commander }} · IA {{ AI_STYLES[relation.ai_style] }} · objetivo: {{ AI_GOALS[relation.ai_goal] }}</p></div><span class="relation-status status-{{ relation.status }}">{{ status_names[relation.status] }}</span></header>
          <dl class="farm-stats"><div><dt>Confianza</dt><dd>{{ relation.trust }}</dd></div><div><dt>Puntuación</dt><dd>{{ relation.score|number }}</dd></div></dl>
          {% if assistance_profile.consequence_forecasts %}
          <details class="notice">
            <summary>Previsión antes de enviar la propuesta</summary>
            <p>Un pacto comercial puede aumentar ingresos y confianza. La no agresión reduce ataques de la IA. Romper acuerdos reduce la confianza.</p>
            <p><strong>Declarar la guerra:</strong> reduce la confianza en 35 puntos, habilita ataques e invasiones y puede reforzar a la facción militar y activar sanciones galácticas.</p>
          </details>
          {% endif %}
          <form method="post" action="{{ url_for('diplomacy_action_route') }}" class="inline-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="rival_id" value="{{ relation.rival_id }}"><label>Acción diplomática<select name="diplomatic_action">{% if relation.status == 'war' %}<option value="peace">Proponer la paz</option>{% else %}<option value="trade">Proponer pacto comercial</option><option value="non_aggression">Proponer no agresión</option><option value="war">Declarar la guerra</option>{% if relation.status != 'neutral' %}<option value="break">Romper acuerdos</option>{% endif %}{% endif %}</select></label><button class="button" type="submit">Enviar propuesta</button></form>
        </article>{% endfor %}</div></section>
        </div>
