{% set sorted_metrics = metrics | dictsort %}
{% set ns = namespace(percentile_keys=[]) %}
{% if percentiles %}
  {% set ns.percentile_keys = percentiles %}
{% elif sorted_metrics %}
  {% set reference_percentiles = sorted_metrics[0][1].percentiles.keys() | list %}
  {% set ns.percentile_keys = reference_percentiles %}
{% endif %}

{% if sorted_metrics %}
  <table class="metrics-table">
    <thead>
      <tr>
        <th scope="col">Metric</th>
        <th scope="col">Mean</th>
        {% for percentile in ns.percentile_keys %}
          {% set percentile_label = '%g' % percentile %}
          <th scope="col">P{{ percentile_label }}</th>
        {% endfor %}
        <th scope="col">Std Dev</th>
      </tr>
    </thead>
    <tbody>
      {% for metric_name, summary in sorted_metrics %}
        <tr>
          <th scope="row">{{ metric_name | replace('_', ' ') | title }}</th>
          <td>{{ summary.mean | format_metric(metric_name, currency) }}</td>
          {% for percentile in ns.percentile_keys %}
            {% set percentile_key = '%g' % percentile %}
            {% set percentile_value = summary.percentiles.get(percentile_key) %}
            <td>
              {% if percentile_value is not none %}
                {{ percentile_value | format_metric(metric_name, currency) }}
              {% else %}
                —
              {% endif %}
            </td>
          {% endfor %}
          <td>{{ summary.std_dev | format_metric(metric_name, currency) }}</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
{% else %}
  <p class="muted">Monte Carlo metrics are unavailable.</p>
{% endif %}
