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

  // ============================================================
  // FLAGS TAB (localStorage-backed)
  // ============================================================
  var FLAG_KEY = 'fcc_dashboard_flags';

  function getFlags() {
    try { return JSON.parse(localStorage.getItem(FLAG_KEY)) || {}; } catch(e) { return {}; }
  }

  function saveFlags(flags) {
    localStorage.setItem(FLAG_KEY, JSON.stringify(flags));
  }

  function initFlags() {
    updateFlagsTab();
  }

  function toggleFlag(fileNumber) {
    var flags = getFlags();
    if (flags[fileNumber]) {
      delete flags[fileNumber];
    } else {
      flags[fileNumber] = { note: '', created: new Date().toISOString() };
    }
    saveFlags(flags);
    updateFlagsTab();
    updateFlagButton(fileNumber);
  }

  function updateFlagNote(fileNumber, note) {
    var flags = getFlags();
    if (flags[fileNumber]) {
      flags[fileNumber].note = note;
      saveFlags(flags);
    }
  }

  function updateFlagButton(fileNumber) {
    var flags = getFlags();
    var isFlagged = !!flags[fileNumber];
    var $btn = $('#flag-btn');
    if ($btn.length) {
      $btn.find('i').attr('class', isFlagged ? 'fa fa-flag' : 'fa fa-flag-o');
      $btn.find('.flag-label').text(isFlagged ? 'Flagged' : 'Flag');
      if (isFlagged) { $btn.css({ background: '#ff253a', color: '#fff', borderColor: '#ff253a' }); }
      else { $btn.css({ background: '#fff', color: '#13418A', borderColor: '#13418A' }); }
    }
  }

  function updateFlagsTab() {
    var flags = getFlags();
    var activeApps = {};
    D.allApps.forEach(function(a) { activeApps[H.appKey(a)] = a; });

    // Prune flags for apps no longer in data
    var openFlags = {};
    Object.keys(flags).forEach(function(k) {
      if (activeApps[k]) openFlags[k] = flags[k];
    });
    if (Object.keys(openFlags).length !== Object.keys(flags).length) saveFlags(openFlags);

    var keys = Object.keys(openFlags);
    $('#flag-count-badge').text(keys.length + ' open flag' + (keys.length !== 1 ? 's' : ''));

    if (!keys.length) {
      $('#flags-empty').show();
      $('#flags-list').empty();
      return;
    }

    $('#flags-empty').hide();
    var $list = $('#flags-list');
    $list.empty();

    keys.sort(function(a, b) { return (openFlags[b].created || '') < (openFlags[a].created || '') ? -1 : 1; });

    keys.forEach(function(k) {
      var app = activeApps[k];
      var flag = openFlags[k];
      var created = flag.created ? new Date(flag.created).toLocaleDateString() : '';
      var label = H.appLabel(app);
      $list.append(
        '<div class="flag-card" data-fn="' + k + '" style="background:#fff;border:1px solid #ddd;border-left:4px solid #ff253a;border-radius:4px;padding:15px;margin-bottom:10px">' +
          '<div style="display:flex;justify-content:space-between;align-items:flex-start">' +
            '<div>' +
              '<div style="font-weight:700;color:#13418A;font-size:0.95rem">' + label + '</div>' +
              '<div style="font-size:0.95rem;color:#555">' + app.name + '</div>' +
              '<div style="font-size:0.85rem;color:#888">Status: <span class="badge-status ' + H.statusBadgeClass(app.status) + '">' + app.status + '</span> &nbsp; Flagged: ' + created + '</div>' +
            '</div>' +
            '<button class="btn btn-sm flag-remove-btn" data-fn="' + k + '" style="background:#fff;color:#ff253a;border:1px solid #ff253a;border-radius:3px;padding:4px 10px;font-size:0.85rem;cursor:pointer"><i class="fa fa-times"></i> Remove</button>' +
          '</div>' +
          '<div style="margin-top:8px">' +
            '<textarea class="form-control flag-note-input" data-fn="' + k + '" rows="2" placeholder="Add a note..." style="font-size:0.95rem;border:1px solid #ddd;border-radius:3px">' + (flag.note || '') + '</textarea>' +
          '</div>' +
        '</div>'
      );
    });

    $list.off('click', '.flag-remove-btn').on('click', '.flag-remove-btn', function() {
      toggleFlag($(this).data('fn'));
    });
    $list.off('change', '.flag-note-input').on('change', '.flag-note-input', function() {
      updateFlagNote($(this).data('fn'), $(this).val());
    });
  }

  D.initFlags = initFlags;
  D.getFlags = getFlags;
  D.toggleFlag = toggleFlag;
})(jQuery);
