(function($) {
  'use strict';
  var D = window.ElsDash;
  var H = D.helpers;
  var CONFIG = D.CONFIG;

  D.renewalCharts = {};

  // ============================================================
  // RENEWALS TAB
  // ============================================================
  function updateRenewals() {
    var renewals = D.allApps.filter(function(a) { return a.renewalTimeliness; });
    var timely = renewals.filter(function(a) { return a.renewalTimeliness.toLowerCase() === 'timely'; });
    var late = renewals.filter(function(a) { return a.renewalTimeliness.toLowerCase() !== 'timely'; });

    $('#ren-total').text(renewals.length);
    $('#ren-timely').text(timely.length);
    $('#ren-late').text(late.length);
    $('#ren-rate').text(renewals.length ? Math.round(timely.length / renewals.length * 100) + '%' : '—');

    // Pie chart
    if (D.renewalCharts.pie) D.renewalCharts.pie.destroy();
    D.renewalCharts.pie = new Chart(document.getElementById('chart-renewal-pie'), {
      type: 'doughnut',
      data: {
        labels: ['Timely', 'Late'],
        datasets: [{ data: [timely.length, late.length], backgroundColor: ['#2e8540', '#ff253a'] }]
      },
      options: { responsive: true, maintainAspectRatio: false }
    });

    // Days histogram
    var dayBuckets = { '<-30': 0, '-30 to -1': 0, '0 to 30': 0, '31 to 90': 0, '90+': 0 };
    var bucketColors = ['#2e8540', '#4aa564', '#ffbe2e', '#ff253a', '#981b1e'];
    renewals.forEach(function(a) {
      var d = a.renewalDays;
      if (d === null) return;
      if (d < -30) dayBuckets['<-30']++;
      else if (d < 0) dayBuckets['-30 to -1']++;
      else if (d <= 30) dayBuckets['0 to 30']++;
      else if (d <= 90) dayBuckets['31 to 90']++;
      else dayBuckets['90+']++;
    });

    if (D.renewalCharts.days) D.renewalCharts.days.destroy();
    D.renewalCharts.days = new Chart(document.getElementById('chart-renewal-days'), {
      type: 'bar',
      data: {
        labels: Object.keys(dayBuckets),
        datasets: [{ label: 'Applications', data: Object.keys(dayBuckets).map(function(k) { return dayBuckets[k]; }), backgroundColor: bucketColors, borderRadius: 3 }]
      },
      options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } }, x: { title: { display: true, text: 'Days (negative = early)' } } } }
    });

    // Table
    var $tbody = $('#renewal-table-body');
    $tbody.empty();
    renewals.forEach(function(a) {
      var isTimely = a.renewalTimeliness.toLowerCase() === 'timely';
      $tbody.append(
        '<tr>' +
          '<td style="font-weight:600;color:#13418A">' + H.appLabel(a) + '</td>' +
          '<td>' + a.name + '</td>' +
          '<td><span class="badge-status ' + H.statusBadgeClass(a.status) + '">' + a.status + '</span></td>' +
          '<td><span class="badge-status ' + (isTimely ? 'badge-granted' : 'badge-denied') + '">' + a.renewalTimeliness + '</span></td>' +
          '<td>' + (a.renewalDays !== null ? a.renewalDays : '—') + '</td>' +
        '</tr>'
      );
    });

    if (!renewals.length) {
      $tbody.append('<tr><td colspan="5" style="text-align:center;color:#888;padding:20px">No renewal data available. Add <code>renewal_timeliness</code> and <code>renewal_days</code> columns to your data export.</td></tr>');
    }
  }

  D.updateRenewals = updateRenewals;
})(jQuery);
