{% extends "base.html" %}

{% block title %}Country Comparison — {{ config.APP_NAME }}{% endblock %}

{% block head %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
{% endblock %}

{% block content %}
<main class="container-page py-8">
  <!-- Page Header -->
  <div class="page-header">
    <h1>Country Comparison</h1>
    <p>Compare coffee metrics across producing and consuming countries.</p>
  </div>

  <!-- Filters -->
  <div class="card mb-8">
    <form id="country-form" method="get" action="{{ url_for('dashboard.countries') }}">
      <div class="grid-2">
        <div>
          <label for="metric" class="form-label">Metric</label>
          <select name="metric" id="metric" class="form-input" onchange="this.form.submit()">
            {% for m in ["Production", "Exports", "Imports", "Ending_Stocks"] %}
            <option value="{{ m }}" {{ "selected" if metric == m }}>{{ m | replace("_", " ") }}</option>
            {% endfor %}
          </select>
        </div>
        <div>
          <label for="country" class="form-label">Countries (select up to 10)</label>
          <select name="country" id="country" class="form-input" multiple size="8" onchange="this.form.submit()">
            {% for c in all_countries %}
            <option value="{{ c.country_code }}" {{ "selected" if c.country_code in selected_codes }}>
              {{ c.country_name }}
            </option>
            {% endfor %}
          </select>
        </div>
      </div>
    </form>
  </div>

  <!-- Chart -->
  {% if comparison_data %}
  <div class="chart-container mb-8">
    <canvas id="comparisonChart"></canvas>
  </div>
  {% else %}
  <div class="plan-gate mb-8">
    Select countries above to see the comparison chart.
  </div>
  {% endif %}

  <a href="{{ url_for('dashboard.index') }}" class="btn-outline">Back to Dashboard</a>
</main>
{% endblock %}

{% block scripts %}
<script>
const CHART_COLORS = {
  copper: '#B45309',
  roast: '#4A2C1A',
  beanGreen: '#15803D',
  forest: '#064E3B',
  stone: '#78716C',
  espresso: '#2C1810',
  warning: '#D97706',
  danger: '#EF4444',
  parchment: '#E8DFD5',
};
const CHART_PALETTE = [
  CHART_COLORS.copper,
  CHART_COLORS.beanGreen,
  CHART_COLORS.roast,
  CHART_COLORS.forest,
  CHART_COLORS.stone,
  CHART_COLORS.warning,
  CHART_COLORS.danger,
  CHART_COLORS.espresso,
];

Chart.defaults.font.family = "'DM Sans', sans-serif";
Chart.defaults.color = CHART_COLORS.stone;
Chart.defaults.borderColor = CHART_COLORS.parchment;

const rawData = {{ comparison_data | tojson }};
const metric = {{ metric | tojson }};

if (rawData.length > 0) {
  const byCountry = {};
  for (const row of rawData) {
    if (!byCountry[row.country_name]) byCountry[row.country_name] = [];
    byCountry[row.country_name].push(row);
  }

  const allYears = [...new Set(rawData.map(r => r.market_year))].sort();

  const datasets = Object.entries(byCountry).map(([name, rows], i) => {
    const yearMap = Object.fromEntries(rows.map(r => [r.market_year, r[metric]]));
    return {
      label: name,
      data: allYears.map(y => yearMap[y] ?? null),
      borderColor: CHART_PALETTE[i % CHART_PALETTE.length],
      tension: 0.3,
      spanGaps: true
    };
  });

  new Chart(document.getElementById('comparisonChart'), {
    type: 'line',
    data: { labels: allYears, datasets },
    options: {
      responsive: true,
      plugins: {
        legend: { position: 'bottom' },
        title: { display: true, text: metric.replace(/_/g, ' ') + ' by Country' }
      },
      scales: { y: { beginAtZero: false } }
    }
  });
}
</script>
{% endblock %}
