        {% from "components/_tabs.html" import tabs_intro %}
        <header class="page-heading"><p class="eyebrow">BOLSA INTERESTELAR</p><h1>Mercado galáctico</h1><p>Publica ofertas persistentes o acepta intercambios de otros imperios. Las IA comparan escasez y valor antes de comprar; los mundos-granja venden alimento de forma regular.</p></header>
        <div data-tab-scope="market" data-tab-auto>
        {{ tabs_intro('market', 'Apartados del mercado', 'Separa precios, publicación, reservas, ofertas e historial de operaciones.') }}
        <section class="metric-grid" aria-label="Resumen del mercado">
          <article><span>Ofertas abiertas</span><strong>{{ market_orders|length }}</strong><small>humanas y de IA</small></article>
          <article><span>Operaciones históricas</span><strong>{{ market_completed }}</strong><small>en este universo</small></article>
          <article><span>Créditos imperiales</span><strong>{{ empire.credits|number }}</strong><small>obtenidos mediante rutas</small></article>
          <article><span>Cooperativas agrícolas</span><strong>{{ farm_rival_count }}</strong><small>proveedores pacíficos</small></article>
        </section>
        <section class="panel" aria-labelledby="market-analyzer-title">
          <p class="eyebrow">ANALIZADOR COMPARABLE</p>
          <h2 id="market-analyzer-title">Valor normalizado de las ofertas</h2>
          <p>La valoración compara cada intercambio con el promedio histórico del mismo par de recursos; si todavía no existe historial, declara y usa una equivalencia base. También comprueba tus reservas actuales.</p>
          <form method="get" action="{{ url_for('game_view', section='market') }}" class="report-filter-form">
            <label>Recurso ofrecido<select name="market_offer"><option value="">Todos</option>{% for key, label in MARKET_RESOURCES.items() %}<option value="{{ key }}" {% if market_analysis_filters.offer == key %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></label>
            <label>Valoración<select name="market_rating"><option value="">Todas</option>{% for label in ['excepcional','favorable','justa','desfavorable','muy desfavorable'] %}<option value="{{ label }}" {% if market_analysis_filters.rating == label %}selected{% endif %}>{{ label|capitalize }}</option>{% endfor %}</select></label>
            <label>Distancia máxima<input name="market_distance" type="number" min="0" max="10000" value="{{ market_analysis_filters.distance if market_analysis_filters.distance is not none else '' }}"></label>
            <label class="check-row"><input name="market_affordable" type="checkbox" value="1" {% if market_analysis_filters.affordable %}checked{% endif %}> Solo ofertas que puedo pagar</label>
            <button class="button" type="submit">Analizar</button>
          </form>
          {% if market_analysis %}<div class="table-wrap"><table><caption>{{ market_analysis|length }} ofertas comparadas por ratio, referencia, reservas y distancia.</caption><thead><tr><th scope="col">Oferta</th><th scope="col">Ratio declarado</th><th scope="col">Referencia</th><th scope="col">Valoración</th><th scope="col">Reservas y distancia</th></tr></thead><tbody>{% for item in market_analysis %}<tr><th scope="row">{{ item.row.seller_name }}: {{ item.row.offer_amount|round(1) }} {{ MARKET_RESOURCES[item.row.offer_resource] }} por {{ item.row.request_amount|round(1) }} {{ MARKET_RESOURCES[item.row.request_resource] }}</th><td>{{ item.normalized_ratio|round(4) }}</td><td>{{ item.baseline|round(4) }} · {{ item.basis }}</td><td>{{ item.label|capitalize }} · índice {{ item.relative|round(2) }}</td><td>{{ 'Puedes pagarla' if item.can_afford else 'Reservas insuficientes' }} · distancia {{ item.distance }}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="empty-state">Ninguna oferta coincide con los filtros.</p>{% endif %}
        </section>
        <div class="dashboard-grid">
          <section class="panel" aria-labelledby="publish-order-title">
            <p class="eyebrow">NUEVA OFERTA</p><h2 id="publish-order-title">Publicar intercambio desde {{ planet.name }}</h2>
            <p>Lo ofrecido queda en depósito y se devuelve si cancelas o caduca la oferta.</p>
            <form method="post" action="{{ url_for('market_create_action') }}" class="stacked-form"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
              <label>Recurso que entregas<select name="offer_resource">{% for key, label in MARKET_RESOURCES.items() %}<option value="{{ key }}">{{ label }} — disponible {{ market_balances[key]|round(1) }}</option>{% endfor %}</select></label>
              <label>Cantidad que entregas<input name="offer_amount" type="number" min="1" max="1000000000" step="0.1" value="1000" required></label>
              <label>Recurso que solicitas<select name="request_resource">{% for key, label in MARKET_RESOURCES.items() %}<option value="{{ key }}" {% if key == 'crystal' %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></label>
              <label>Cantidad que solicitas<input name="request_amount" type="number" min="1" max="1000000000" step="0.1" value="650" required></label>
              <button class="button button-primary" type="submit">Publicar oferta</button>
            </form>
          </section>
          <section class="panel" aria-labelledby="market-reserves-title"><p class="eyebrow">CAPACIDAD DE COMPRA</p><h2 id="market-reserves-title">Reservas utilizables</h2><dl class="settings-list">{% for key, label in MARKET_RESOURCES.items() %}<div><dt>{{ label }}</dt><dd>{{ market_balances[key]|round(1) }}</dd></div>{% endfor %}</dl></section>
        </div>
        <section aria-labelledby="open-market-title"><h2 id="open-market-title" class="section-title">Ofertas abiertas</h2>{% if market_orders %}<div class="table-wrap"><table><caption>Intercambios disponibles. Aceptar una oferta transfiere ambos depósitos inmediatamente.</caption><thead><tr><th scope="col">Vendedor</th><th scope="col">Entrega</th><th scope="col">Solicita</th><th scope="col">Procedencia</th><th scope="col">Acción</th></tr></thead><tbody>{% for order in market_orders %}<tr><th scope="row">{{ order.seller_name }}{% if order.empire_id == empire.id %} (tu oferta){% endif %}</th><td>{{ order.offer_amount|round(1) }} {{ MARKET_RESOURCES[order.offer_resource] }}</td><td>{{ order.request_amount|round(1) }} {{ MARKET_RESOURCES[order.request_resource] }}</td><td>{{ 'Jugador' if order.is_human else 'Cooperativa agrícola' if order.is_farm_world else 'IA ' ~ AI_STYLES[order.ai_style] }}</td><td>{% if order.empire_id == empire.id %}<form method="post" action="{{ url_for('market_cancel_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="order_id" value="{{ order.id }}"><button class="button button-danger" type="submit">Retirar y recuperar depósito</button></form>{% else %}<form method="post" action="{{ url_for('market_accept_action') }}"><input type="hidden" name="csrf_token" value="{{ csrf_token() }}"><input type="hidden" name="order_id" value="{{ order.id }}"><button class="button" type="submit">Aceptar intercambio</button></form>{% endif %}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="empty-state">Todavía no hay ofertas. Publica la primera o espera a que una IA reúna excedentes.</p>{% endif %}</section>
        {% if market_history %}<section aria-labelledby="market-history-title"><h2 id="market-history-title" class="section-title">Tus operaciones recientes</h2><ol class="activity-list">{% for order in market_history %}<li><div><strong>{{ order.seller_name }} → {{ order.buyer_name }}</strong><span>{{ order.offer_amount|round(1) }} {{ MARKET_RESOURCES[order.offer_resource] }} por {{ order.request_amount|round(1) }} {{ MARKET_RESOURCES[order.request_resource] }}</span></div><time datetime="{{ order.filled_at|date_iso }}">{{ order.filled_at|date_label }}</time></li>{% endfor %}</ol></section>{% endif %}
        </div>
