{% extends "base.html" %}

{% block title %}Dashboard — {{ 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>Coffee Dashboard</h1>
    <p>Welcome back{% if user.name %}, {{ user.name }}{% endif %}! Global coffee market data from USDA PSD.</p>
  </div>

  <!-- Key Metric Cards -->
  <div class="grid-4 mb-8">
    <div class="metric-card">
      <div class="metric-label">Global Production (latest year)</div>
      <div class="metric-value">{{ "{:,.0f}".format(latest.get("production", 0)) }}</div>
      <div class="metric-sub">1,000 60-kg bags</div>
    </div>

    <div class="metric-card">
      <div class="metric-label">Stock-to-Use Ratio</div>
      <div class="metric-value">
        {% if stu_trend %}
        {{ "{:.1f}".format(stu_trend[-1].get("stock_to_use_ratio_pct", 0)) }}%
        {% else %}
        --
        {% endif %}
      </div>
      <div class="metric-sub">Ending stocks / consumption</div>
    </div>

    <div class="metric-card">
      <div class="metric-label">Trade Balance</div>
      <div class="metric-value">{{ "{:,.0f}".format(latest.get("exports", 0) - latest.get("imports", 0)) }}</div>
      <div class="metric-sub">Exports minus imports</div>
    </div>

    <div class="metric-card">
      <div class="metric-label">Your Plan</div>
      <div class="metric-value">{{ plan | title }}</div>
      <div class="metric-sub">
        {% if plan == "free" %}
        <a href="{{ url_for('billing.pricing') }}">Upgrade for full history</a>
        {% else %}
        {{ stats.api_calls }} API calls (30d)
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Global Supply/Demand Time Series -->
  <div class="chart-container mb-8">
    <h2 class="text-xl mb-1">Global Supply &amp; Demand</h2>
    {% if plan == "free" %}
    <div class="plan-gate mb-4">Showing last 5 years. <a href="{{ url_for('billing.pricing') }}">Upgrade</a> for full 18+ year history.</div>
    {% endif %}
    <canvas id="supplyDemandChart"></canvas>
  </div>

  <!-- Stock-to-Use Ratio -->
  <div class="chart-container mb-8">
    <h2 class="text-xl mb-4">Stock-to-Use Ratio Trend</h2>
    <canvas id="stuChart"></canvas>
  </div>

  <!-- Two-column: Top Producers + YoY Table -->
  <div class="grid-2 mb-8">
    <div class="chart-container">
      <h2 class="text-xl mb-4">Top Producing Countries</h2>
      <canvas id="topProducersChart"></canvas>
    </div>

    <div class="card">
      <h2 class="text-xl mb-4">Year-over-Year Production Change</h2>
      <div class="overflow-x-auto">
        <table class="table">
          <thead>
            <tr>
              <th>Country</th>
              <th class="text-right">Production</th>
              <th class="text-right">YoY %</th>
            </tr>
          </thead>
          <tbody>
            {% for row in yoy %}
            <tr>
              <td>{{ row.country_name }}</td>
              <td class="text-right">{{ "{:,.0f}".format(row.production) }}</td>
              <td class="text-right {% if row.production_yoy_pct and row.production_yoy_pct > 0 %}text-bean-green{% elif row.production_yoy_pct and row.production_yoy_pct < 0 %}text-danger{% endif %}">
                {% if row.production_yoy_pct is not none %}
                {{ "{:+.1f}%".format(row.production_yoy_pct) }}
                {% else %}
                --
                {% endif %}
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- CSV Export (plan-gated) -->
  {% if plan != "free" %}
  <div class="mb-8">
    <a href="{{ url_for('api.commodity_metrics_csv', code=711100) }}" class="btn-outline">Export CSV</a>
  </div>
  {% else %}
  <div class="plan-gate mb-8">CSV export available on Trader and Analyst plans. <a href="{{ url_for('billing.pricing') }}">Upgrade</a></div>
  {% endif %}

  <!-- Quick Actions -->
  <div class="grid-3">
    <a href="{{ url_for('dashboard.countries') }}" class="btn-outline text-center">Country Comparison</a>
    <a href="{{ url_for('dashboard.settings') }}" class="btn-outline text-center">Settings</a>
    <a href="{{ url_for('dashboard.settings') }}#api-keys" class="btn-outline text-center">API Keys</a>
  </div>
</main>
{% endblock %}

{% block scripts %}
<script>
// Brand chart colors
const CHART_COLORS = {
  copper: '#B45309',
  roast: '#4A2C1A',
  beanGreen: '#15803D',
  forest: '#064E3B',
  stone: '#78716C',
  espresso: '#2C1810',
  warning: '#D97706',
  danger: '#EF4444',
  parchment: '#E8DFD5',
  latte: '#F5F0EB',
};
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.js defaults
Chart.defaults.font.family = "'DM Sans', sans-serif";
Chart.defaults.color = CHART_COLORS.stone;
Chart.defaults.borderColor = CHART_COLORS.parchment;

// -- Supply/Demand Chart --
const tsData = {{ time_series | tojson }};
if (tsData.length > 0) {
  new Chart(document.getElementById('supplyDemandChart'), {
    type: 'line',
    data: {
      labels: tsData.map(r => r.market_year),
      datasets: [
        {label: 'Production', data: tsData.map(r => r.production), borderColor: CHART_PALETTE[0], tension: 0.3},
        {label: 'Exports', data: tsData.map(r => r.exports), borderColor: CHART_PALETTE[1], tension: 0.3},
        {label: 'Imports', data: tsData.map(r => r.imports), borderColor: CHART_PALETTE[2], tension: 0.3},
        {label: 'Ending Stocks', data: tsData.map(r => r.ending_stocks), borderColor: CHART_PALETTE[3], tension: 0.3},
        {label: 'Total Distribution', data: tsData.map(r => r.total_distribution), borderColor: CHART_PALETTE[4], tension: 0.3},
      ]
    },
    options: {
      responsive: true,
      plugins: {legend: {position: 'bottom'}},
      scales: {y: {beginAtZero: false}}
    }
  });
}

// -- Stock-to-Use Chart --
const stuData = {{ stu_trend | tojson }};
if (stuData.length > 0) {
  new Chart(document.getElementById('stuChart'), {
    type: 'line',
    data: {
      labels: stuData.map(r => r.market_year),
      datasets: [{
        label: 'Stock-to-Use Ratio (%)',
        data: stuData.map(r => r.stock_to_use_ratio_pct),
        borderColor: CHART_COLORS.copper,
        backgroundColor: 'rgba(180, 83, 9, 0.08)',
        fill: true,
        tension: 0.3
      }]
    },
    options: {
      responsive: true,
      plugins: {legend: {display: false}},
      scales: {y: {beginAtZero: false}}
    }
  });
}

// -- Top Producers Horizontal Bar --
const topData = {{ top_producers | tojson }};
if (topData.length > 0) {
  new Chart(document.getElementById('topProducersChart'), {
    type: 'bar',
    data: {
      labels: topData.map(r => r.country_name),
      datasets: [{
        label: 'Production',
        data: topData.map(r => r.production),
        backgroundColor: CHART_COLORS.copper
      }]
    },
    options: {
      indexAxis: 'y',
      responsive: true,
      plugins: {legend: {display: false}},
      scales: {x: {beginAtZero: true}}
    }
  });
}
</script>
{% endblock %}
