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

  var drilldownMap = null;
  var RESULTS_PAGE_SIZE = 50;

  // ============================================================
  // DRILLDOWN
  // ============================================================
  function initDrilldown() {
    $('#btn-drilldown-search').on('click', doSearch);
    $('#drilldown-search').on('keypress', function(e) {
      if (e.which === 13) doSearch();
    });
  }

  function doSearch() {
    var query = $('#drilldown-search').val().trim().toLowerCase();
    if (!query) return;

    var results = D.allApps.filter(function(app) {
      if (app.name.toLowerCase().indexOf(query) !== -1) return true;
      if (app.fileNumber.toLowerCase().indexOf(query) !== -1) return true;
      if (app.callsign && app.callsign.toLowerCase().indexOf(query) !== -1) return true;
      return false;
    });

    results.sort(function(a, b) {
      if (!a.receiptDate) return 1;
      if (!b.receiptDate) return -1;
      return b.receiptDate - a.receiptDate;
    });

    renderResultsList(results);
  }

  function renderResultsList(results) {
    var $list = $('#drilldown-results');
    $list.empty();

    if (!results.length) {
      $list.html('<div style="padding:20px;color:#888;text-align:center"><i class="fa fa-frown-o fa-2x"></i><p style="margin-top:10px">No applications found.</p></div>');
      return;
    }

    var shown = 0;

    function appendPage() {
      var end = Math.min(shown + RESULTS_PAGE_SIZE, results.length);
      for (var idx = shown; idx < end; idx++) {
        (function(app, i) {
          var badgeClass = H.statusBadgeClass(app.status);
          var $card = $('<div class="result-card" data-index="' + i + '">' +
            '<div class="file-number">' + H.appLabel(app) + ' <span class="badge-status ' + badgeClass + '">' + app.status + '</span></div>' +
            '<div class="applicant-name">' + app.name + '</div>' +
            '<div class="receipt-info">Received: ' + H.formatDate(app.receiptDate) + '</div>' +
            '</div>');
          $card.on('click', function() {
            $list.find('.result-card').removeClass('active');
            $(this).addClass('active');
            showAppDetail(app);
          });
          $list.append($card);
        })(results[idx], idx);
      }
      shown = end;
      $list.find('.show-more-btn').remove();
      if (shown < results.length) {
        var remaining = results.length - shown;
        var $more = $('<div class="show-more-btn" style="padding:10px;text-align:center;cursor:pointer;color:#13418A;font-weight:600;border-top:1px solid #ddd"><i class="fa fa-plus-circle"></i> Show more (' + remaining + ' remaining)</div>');
        $more.on('click', function() { appendPage(); });
        $list.append($more);
      }
    }

    appendPage();
    $list.find('.result-card:first').click();
  }

  // ============================================================
  // DETAIL PANEL
  // ============================================================
  function showAppDetail(app) {
    var $detail = $('#drilldown-detail');
    $detail.empty();

    // === FLAG BUTTON ===
    var flags = D.getFlags();
    var ak = H.appKey(app);
    var isFlagged = !!flags[ak];
    var $flagBtn = $('<button id="flag-btn" style="float:right;border:2px solid #13418A;border-radius:3px;padding:6px 14px;font-size:0.8rem;font-weight:600;cursor:pointer;background:' + (isFlagged ? '#ff253a' : '#fff') + ';color:' + (isFlagged ? '#fff' : '#13418A') + ';border-color:' + (isFlagged ? '#ff253a' : '#13418A') + '">' +
      '<i class="fa ' + (isFlagged ? 'fa-flag' : 'fa-flag-o') + '"></i> <span class="flag-label">' + (isFlagged ? 'Flagged' : 'Flag') + '</span></button>');
    $flagBtn.on('click', function() { D.toggleFlag(ak); });
    $detail.append($flagBtn);

    // === TIMELINE (fork-join) ===
    var decisionColor = H.statusColor(app.status);
    var decisionLabel = !H.isPending(app.status) ? app.status : app.status;
    var decisionDate = !H.isPending(app.status) ? app.statusDate : null;

    var $timeline = $('<div class="timeline-container">' +
      '<h5><i class="fa fa-clock-o"></i> Application Timeline &mdash; ' + H.appLabel(app) + '</h5>' +
      '<div class="tl-flow"></div></div>');
    var $flow = $timeline.find('.tl-flow');

    // Received node
    $flow.append(
      '<div class="tl-node">' +
        '<div class="tl-dot" style="color:' + CONFIG.COLORS.PRIMARY + ';background:' + CONFIG.COLORS.PRIMARY + '"></div>' +
        '<div class="tl-node-label">Received</div>' +
        '<div class="tl-node-date">' + H.formatDate(app.receiptDate) + '</div>' +
      '</div>' +
      '<div class="tl-connector"><div class="tl-connector-line"></div></div>'
    );

    // Branches (charges as parallel forks)
    if (app.charges.length > 0) {
      var $branches = $('<div class="tl-branches"></div>');

      app.charges.forEach(function(c) {
        var isClosed = !!c.closeDate;
        var barClass = isClosed ? 'tl-branch-closed' : 'tl-branch-open';
        var statusIcon = isClosed ? '<i class="fa fa-check-circle" style="color:#2e8540"></i>' : '<i class="fa fa-clock-o" style="color:#ffbe2e"></i>';
        var dateStr = H.formatDate(c.openDate) + ' → ' + (isClosed ? H.formatDate(c.closeDate) : 'Pending');

        $branches.append(
          '<div class="tl-branch">' +
            '<div class="tl-branch-line-left"></div>' +
            '<div class="tl-branch-bar ' + barClass + '">' +
              '<span class="tl-charge-name">' + statusIcon + ' ' + c.charge + '</span>' +
              '<span class="tl-charge-dates">' + dateStr + '</span>' +
            '</div>' +
            '<div class="tl-branch-line-right"></div>' +
          '</div>'
        );
      });

      $flow.append($branches);
    } else {
      $flow.append('<div class="tl-no-charges">No referrals</div>');
    }

    // Decision node
    var decNodeBg = !H.isPending(app.status) ? decisionColor : '#fff';
    var decNodeBorder = decisionColor;
    $flow.append(
      '<div class="tl-connector"><div class="tl-connector-line"></div></div>' +
      '<div class="tl-node">' +
        '<div class="tl-dot" style="color:' + decNodeBorder + ';background:' + decNodeBg + '"></div>' +
        '<div class="tl-node-label">' + decisionLabel + '</div>' +
        '<div class="tl-node-date">' + H.formatDate(decisionDate) + '</div>' +
      '</div>'
    );

    $detail.append($timeline);

    // === REFERRALS TABLE (deduplicated charges) ===
    var $tableWrap = $('<div class="chart-panel"><h5><i class="fa fa-table"></i> Referrals</h5></div>');
    var $table = $('<table class="detail-table"><thead><tr>' +
      '<th data-col="charge">Charge <i class="fa fa-sort"></i></th>' +
      '<th data-col="open">Open Date <i class="fa fa-sort"></i></th>' +
      '<th data-col="close">Close Date <i class="fa fa-sort"></i></th>' +
      '<th data-col="status">Status</th>' +
      '</tr></thead><tbody></tbody></table>');

    var tableRows = [];
    app.charges.forEach(function(c) {
      var chargeStatus, badgeCls;
      if (c.closeDate) { chargeStatus = 'CLOSED'; badgeCls = 'badge-closed'; }
      else if (c.openDate) { chargeStatus = 'OPEN'; badgeCls = 'badge-open'; }
      else { chargeStatus = 'PENDING'; badgeCls = 'badge-pending'; }

      tableRows.push({
        charge: c.charge || '—',
        openDate: c.openDate,
        closeDate: c.closeDate,
        openStr: H.formatDate(c.openDate),
        closeStr: H.formatDate(c.closeDate),
        statusHtml: '<span class="badge-status ' + badgeCls + '">' + chargeStatus + '</span>',
        sortVals: { charge: c.charge, open: c.openDate ? c.openDate.getTime() : 0, close: c.closeDate ? c.closeDate.getTime() : 0 }
      });
    });

    function renderTableRows(rows) {
      var $tbody = $table.find('tbody');
      $tbody.empty();
      rows.forEach(function(r) {
        $tbody.append('<tr><td>' + r.charge + '</td><td>' + r.openStr + '</td><td>' + r.closeStr + '</td><td>' + r.statusHtml + '</td></tr>');
      });
    }

    renderTableRows(tableRows);

    var sortDir = {};
    $table.find('th[data-col]').on('click', function() {
      var c = $(this).data('col');
      sortDir[c] = !sortDir[c];
      tableRows.sort(function(a, b) {
        var va = a.sortVals[c] || a[c] || '';
        var vb = b.sortVals[c] || b[c] || '';
        if (va < vb) return sortDir[c] ? -1 : 1;
        if (va > vb) return sortDir[c] ? 1 : -1;
        return 0;
      });
      renderTableRows(tableRows);
    });

    $tableWrap.append($table);
    $detail.append($tableWrap);

    // === EXTERNAL LINKS ===
    var links = [];
    if (app.applicationUrl) links.push('<a href="' + app.applicationUrl + '" target="_blank" class="btn btn-sm" style="border:1px solid #13418A;color:#13418A;margin-right:6px"><i class="fa fa-external-link"></i> Application</a>');
    if (app.exhibitsUrl) links.push('<a href="' + app.exhibitsUrl + '" target="_blank" class="btn btn-sm" style="border:1px solid #e86e00;color:#e86e00;margin-right:6px"><i class="fa fa-paperclip"></i> Exhibits</a>');
    if (app.correspondenceUrl) links.push('<a href="' + app.correspondenceUrl + '" target="_blank" class="btn btn-sm" style="border:1px solid #2e8540;color:#2e8540;margin-right:6px"><i class="fa fa-envelope-o"></i> Correspondence</a>');
    if (links.length) {
      $detail.append('<div style="margin:10px 0 15px">' + links.join('') + '</div>');
    }

    // === FREQUENCIES ===
    if (app.frequencies.length) {
      var freqHtml = '<div class="chart-panel"><h5><i class="fa fa-signal"></i> Frequencies</h5><div style="font-size:0.95rem">';
      app.frequencies.forEach(function(f) {
        freqHtml += '<span style="display:inline-block;background:#e8f0fe;color:#13418A;border-radius:3px;padding:3px 10px;margin:0 6px 6px 0;font-weight:600">' + H.formatFreq(f.lo, f.hi) + '</span>';
      });
      freqHtml += '</div></div>';
      $detail.append(freqHtml);
    }

    // === MINI MAP ===
    var hasCoords = app.fixedCoords.length > 0 || app.mobileCoords.length > 0;
    if (hasCoords) {
      var $mapPanel = $('<div class="chart-panel"><h5><i class="fa fa-map"></i> Location</h5><div id="drilldown-map"></div></div>');
      $detail.append($mapPanel);

      setTimeout(function() {
        if (drilldownMap) { drilldownMap.remove(); drilldownMap = null; }
        drilldownMap = L.map('drilldown-map').setView([39.8283, -98.5795], 4);
        L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
          attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/">CARTO</a>',
          maxZoom: 19,
          subdomains: 'abcd'
        }).addTo(drilldownMap);

        var bounds = [];

        app.fixedCoords.forEach(function(c) {
          L.marker([c.lat, c.lon], {
            icon: L.divIcon({
              className: '',
              html: '<i class="fa fa-map-marker" style="font-size:24px;color:' + CONFIG.COLORS.PRIMARY + '"></i>',
              iconSize: [24, 24],
              iconAnchor: [12, 24]
            })
          }).addTo(drilldownMap);
          bounds.push([c.lat, c.lon]);
        });

        app.mobileCoords.forEach(function(c) {
          L.circle([c.lat, c.lon], {
            radius: c.radius,
            color: '#e86e00',
            fillColor: '#ffbe2e',
            fillOpacity: 0.25,
            weight: 2
          }).addTo(drilldownMap);
          bounds.push([c.lat, c.lon]);
        });

        if (bounds.length) drilldownMap.fitBounds(bounds, { padding: [30, 30] });

        setTimeout(function() { drilldownMap.invalidateSize(); }, 200);
      }, 100);
    }
  }

  D.initDrilldown = initDrilldown;
  D.showAppDetail = showAppDetail;
})(jQuery);
