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

  // ============================================================
  // TRANSFERS / ASSIGNMENTS TAB
  // ============================================================
  function updateTransfers() {
    var transferApps = D.allApps.filter(function(a) {
      var fn = (a.fileNumber || '').toUpperCase();
      return fn.indexOf('TU') !== -1 || fn.indexOf('AU') !== -1;
    });

    $('#transfer-count-badge').text(transferApps.length + ' application' + (transferApps.length !== 1 ? 's' : ''));

    if (transferApps.length === 0) {
      $('#transfers-empty').show();
      $('#transfers-list').empty();
      return;
    }
    $('#transfers-empty').hide();

    var pendingApps = transferApps.filter(function(a) { return H.isPending(a.status); });
    var completedApps = transferApps.filter(function(a) { return !H.isPending(a.status); });

    function groupByName(apps) {
      var groups = {};
      apps.forEach(function(a) {
        var name = a.name || '(Unknown Applicant)';
        if (!groups[name]) groups[name] = [];
        groups[name].push(a);
      });
      return groups;
    }

    function renderSection(apps, sectionId, sectionTitle, sectionColor, startIdx) {
      if (apps.length === 0) return '<div style="color:#888;padding:10px;font-style:italic">No ' + sectionTitle.toLowerCase() + '.</div>';
      var groups = groupByName(apps);
      var sortedNames = Object.keys(groups).sort();
      var html = '<div class="panel-group" id="' + sectionId + '">';

      sortedNames.forEach(function(name, idx) {
        var gapps = groups[name];
        var tuCount = 0, auCount = 0;
        gapps.forEach(function(a) {
          var fn = (a.fileNumber || '').toUpperCase();
          if (fn.indexOf('TU') !== -1) tuCount++;
          if (fn.indexOf('AU') !== -1) auCount++;
        });
        var badges = '';
        if (tuCount) badges += '<span class="badge" style="background:#13418A;margin-left:6px">' + tuCount + ' Transfer' + (tuCount !== 1 ? 's' : '') + '</span>';
        if (auCount) badges += '<span class="badge" style="background:#2e8540;margin-left:6px">' + auCount + ' Assignment' + (auCount !== 1 ? 's' : '') + '</span>';

        var gid = sectionId + '-group-' + (startIdx + idx);
        html += '<div class="panel panel-default" style="border-radius:4px;margin-bottom:6px">';
        html += '<div class="panel-heading" style="cursor:pointer;padding:10px 15px" data-toggle="collapse" data-parent="#' + sectionId + '" data-target="#' + gid + '">';
        html += '<h4 class="panel-title" style="margin:0;font-size:0.95rem;font-weight:600">';
        html += '<i class="fa fa-chevron-right" style="margin-right:8px;font-size:0.8rem;transition:transform .2s"></i>';
        html += name + badges;
        html += '</h4></div>';
        html += '<div id="' + gid + '" class="panel-collapse collapse">';
        html += '<div class="panel-body" style="padding:0">';
        html += '<table class="table table-condensed table-hover" style="margin:0;font-size:0.95rem">';
        html += '<thead><tr style="background:#f5f5f5"><th>File Number</th><th>Callsign</th><th>Type</th><th>Status</th><th>Filed</th></tr></thead><tbody>';

        gapps.forEach(function(a) {
          var fn = (a.fileNumber || '').toUpperCase();
          var type = fn.indexOf('TU') !== -1 ? 'Transfer' : 'Assignment';
          var statusClass = H.statusBadgeClass(a.status);
          html += '<tr class="transfer-app-row" data-file="' + H.appKey(a) + '" style="cursor:pointer">';
          html += '<td><strong>' + a.fileNumber + '</strong></td>';
          html += '<td>' + (a.callsign || '—') + '</td>';
          html += '<td><span class="label ' + (type === 'Transfer' ? 'label-primary' : 'label-success') + '">' + type + '</span></td>';
          html += '<td><span class="label ' + statusClass + '">' + a.status + '</span></td>';
          html += '<td>' + (a.receiptDate ? H.formatDate(a.receiptDate) : '—') + '</td>';
          html += '</tr>';
        });

        html += '</tbody></table></div></div></div>';
      });

      html += '</div>';
      return html;
    }

    var html = '';
    html += '<h5 style="color:#13418A;font-weight:700;margin:15px 0 10px;border-bottom:2px solid #13418A;padding-bottom:6px"><i class="fa fa-clock-o"></i> Pending (' + pendingApps.length + ')</h5>';
    html += renderSection(pendingApps, 'transfer-pending', 'pending transfers or assignments', '#13418A', 0);
    html += '<h5 style="color:#2e8540;font-weight:700;margin:25px 0 10px;border-bottom:2px solid #2e8540;padding-bottom:6px"><i class="fa fa-check-circle"></i> Completed (' + completedApps.length + ')</h5>';
    html += renderSection(completedApps, 'transfer-completed', 'completed transfers or assignments', '#2e8540', 1000);

    $('#transfers-list').html(html);

    $('#transfers-list .panel-group').on('show.bs.collapse', function(e) {
      $(e.target).prev('.panel-heading').find('.fa-chevron-right').css('transform', 'rotate(90deg)');
    }).on('hide.bs.collapse', function(e) {
      $(e.target).prev('.panel-heading').find('.fa-chevron-right').css('transform', 'rotate(0deg)');
    });

    $('.transfer-app-row').on('click', function() {
      var key = $(this).data('file');
      var app = D.allApps.filter(function(a) { return H.appKey(a) === key; })[0];
      if (app) {
        $('a[href="#drilldown"]').tab('show');
        D.showAppDetail(app);
      }
    });
  }

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