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

  var refSortCol = 'entity';
  var refSortAsc = true;

  // ============================================================
  // REFERRALS TAB
  // ============================================================
  function initReferrals() {
    var entities = {};
    D.allApps.forEach(function(a) {
      a.charges.forEach(function(c) {
        if (c.charge) entities[c.charge] = true;
      });
    });
    var $sel = $('#ref-filter-entity');
    Object.keys(entities).sort().forEach(function(e) {
      $sel.append('<option value="' + e + '">' + e + '</option>');
    });

    // Populate experiment type dropdown from all apps that have referrals
    var expTypes = {};
    D.allApps.forEach(function(a) {
      if (a.experimentType && a.charges.some(function(c) { return !!c.charge; })) {
        expTypes[a.experimentType] = true;
      }
    });
    var $expSel = $('#ref-filter-exp-type');
    Object.keys(expTypes).sort().forEach(function(t) {
      $expSel.append('<option value="' + t + '">' + t + '</option>');
    });

    $sel.on('change', updateReferrals);
    $('#ref-filter-status').on('change', updateReferrals);
    $('#ref-filter-exp-type').on('change', updateReferrals);
    $('#btn-reset-ref-filters').on('click', function() {
      $('#ref-filter-entity').val('');
      $('#ref-filter-status').val('');
      $('#ref-filter-exp-type').val('');
      updateReferrals();
    });

    $('#ref-table thead th[data-sort]').on('click', function() {
      var sortKey = $(this).data('sort');
      if (refSortCol === sortKey) { refSortAsc = !refSortAsc; }
      else { refSortCol = sortKey; refSortAsc = true; }
      updateReferrals();
    });

    $('#btn-export-referrals').on('click', exportReferralsCSV);

    updateReferrals();
  }

  function getReferralRows() {
    var entityFilter = $('#ref-filter-entity').val();
    var statusFilter = $('#ref-filter-status').val();
    var expTypeFilter = $('#ref-filter-exp-type').val();
    var now = new Date();
    var rows = [];

    D.allApps.forEach(function(a) {
      if (expTypeFilter && a.experimentType !== expTypeFilter) return;
      a.charges.forEach(function(c) {
        if (!c.charge) return;
        var isOpen = c.openDate && !c.closeDate;
        var isClosed = c.openDate && c.closeDate;
        if (entityFilter && c.charge !== entityFilter) return;
        if (statusFilter === 'open' && !isOpen) return;
        if (statusFilter === 'closed' && !isClosed) return;

        rows.push({
          entity: c.charge,
          filenumber: a.fileNumber,
          callsign: a.callsign || '—',
          applicant: a.name,
          experimentType: a.experimentType || '—',
          openDate: c.openDate,
          closeDate: c.closeDate,
          age: c.openDate ? (c.closeDate ? H.daysBetween(c.openDate, c.closeDate) : H.daysBetween(c.openDate, now)) : 0,
          isOpen: isOpen,
          applicationUrl: a.applicationUrl,
          exhibitsUrl: a.exhibitsUrl,
          correspondenceUrl: a.correspondenceUrl
        });
      });
    });

    rows.sort(function(a, b) {
      var va, vb;
      if (refSortCol === 'openDate' || refSortCol === 'closeDate') {
        va = a[refSortCol] ? a[refSortCol].getTime() : 0;
        vb = b[refSortCol] ? b[refSortCol].getTime() : 0;
      } else if (refSortCol === 'age') {
        va = a.age; vb = b.age;
      } else {
        va = (a[refSortCol] || '').toLowerCase();
        vb = (b[refSortCol] || '').toLowerCase();
      }
      if (va < vb) return refSortAsc ? -1 : 1;
      if (va > vb) return refSortAsc ? 1 : -1;
      return 0;
    });

    return rows;
  }

  function updateReferrals() {
    var rows = getReferralRows();
    var $tbody = $('#ref-table-body');
    $tbody.empty();

    rows.forEach(function(r) {
      var statusBadge = r.isOpen
        ? '<span class="badge-status badge-open">Open</span>'
        : '<span class="badge-status badge-closed">Closed</span>';
      var fnCell = r.applicationUrl
        ? '<a href="' + r.applicationUrl + '" target="_blank" style="font-weight:600;color:#13418A">' + r.filenumber + '</a>'
        : '<span style="font-weight:600;color:#13418A">' + r.filenumber + '</span>';
      var attParts = [];
      if (r.exhibitsUrl) attParts.push('<a href="' + r.exhibitsUrl + '" target="_blank">Exhibits</a>');
      if (r.correspondenceUrl) attParts.push('<a href="' + r.correspondenceUrl + '" target="_blank">Emails</a>');
      var attCell = attParts.length ? attParts.join(' / ') : '--';
      $tbody.append(
        '<tr>' +
          '<td>' + r.entity + '</td>' +
          '<td>' + fnCell + '</td>' +
          '<td>' + r.callsign + '</td>' +
          '<td>' + r.applicant + '</td>' +
          '<td>' + r.experimentType + '</td>' +
          '<td>' + H.formatDate(r.openDate) + '</td>' +
          '<td>' + H.formatDate(r.closeDate) + '</td>' +
          '<td>' + r.age + '</td>' +
          '<td>' + statusBadge + '</td>' +
          '<td style="white-space:nowrap;font-size:0.85rem">' + attCell + '</td>' +
        '</tr>'
      );
    });

    // Summary cards by entity
    var entityCounts = {};
    D.allApps.forEach(function(a) {
      a.charges.forEach(function(c) {
        if (!c.charge) return;
        if (!entityCounts[c.charge]) entityCounts[c.charge] = { open: 0, closed: 0 };
        if (c.openDate && !c.closeDate) entityCounts[c.charge].open++;
        else if (c.openDate && c.closeDate) entityCounts[c.charge].closed++;
      });
    });

    var $cards = $('#ref-summary-cards');
    $cards.empty();
    Object.keys(entityCounts).sort().forEach(function(entity) {
      var ec = entityCounts[entity];
      $cards.append(
        '<div style="background:#fff;border:1px solid #ddd;border-radius:4px;padding:10px;margin-bottom:8px">' +
          '<div style="font-weight:700;font-size:0.9rem;color:#13428b;margin-bottom:4px">' + entity + '</div>' +
          '<div style="display:flex;gap:12px;font-size:0.85rem">' +
            '<span><span style="color:#ffbe2e;font-weight:700">' + ec.open + '</span> open</span>' +
            '<span><span style="color:#2e8540;font-weight:700">' + ec.closed + '</span> closed</span>' +
          '</div>' +
        '</div>'
      );
    });

    // Update sort icons
    $('#ref-table thead th[data-sort]').each(function() {
      var $th = $(this);
      var col = $th.data('sort');
      var $icon = $th.find('i');
      if (col === refSortCol) {
        $icon.attr('class', refSortAsc ? 'fa fa-sort-asc' : 'fa fa-sort-desc');
      } else {
        $icon.attr('class', 'fa fa-sort');
      }
    });
  }

  function exportReferralsCSV() {
    var rows = getReferralRows();
    var lines = ['Entity,File Number,Callsign,Applicant,Experiment Type,Open Date,Close Date,Age (days),Status,Application URL,Exhibits URL,Correspondence URL'];
    rows.forEach(function(r) {
      lines.push([
        '"' + r.entity + '"',
        '"' + r.filenumber + '"',
        '"' + (r.callsign === '—' ? '' : r.callsign) + '"',
        '"' + r.applicant + '"',
        '"' + (r.experimentType === '—' ? '' : r.experimentType) + '"',
        r.openDate ? H.formatDate(r.openDate) : '',
        r.closeDate ? H.formatDate(r.closeDate) : '',
        r.age,
        r.isOpen ? 'Open' : 'Closed',
        '"' + (r.applicationUrl || '') + '"',
        '"' + (r.exhibitsUrl || '') + '"',
        '"' + (r.correspondenceUrl || '') + '"'
      ].join(','));
    });
    var blob = new Blob([lines.join('\n')], { type: 'text/csv' });
    var url = URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.href = url;
    a.download = 'referrals-' + new Date().toISOString().slice(0, 10) + '.csv';
    a.click();
    URL.revokeObjectURL(url);
  }

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