// src/features/admin/ui/admin-leads-filters.jsx
//
// Status filters for the "By search" price-list view (admin-leads-campaigns.jsx).
// Two independent toggles declutter the teacher lists:
//   - Hide opted-out & dead — drop the finished leads (a teacher who opted out,
//     or one you removed with "Mark dead") so only live prospects remain.
//   - Only not delivered    — keep ONLY teachers whose opener bounced (numbers
//     that can't receive texts — usually landlines), i.e. the call-them list.
// The two compose. window.LEADS_FILTER is the pure predicate layer (no React);
// window.LeadsFilterBar is the chip UI. Both read the same teacher shape the
// campaigns view renders: { leadState, deliveryStatus, ... }.
//
// Styling: reuses TF_TONE (admin-teacher-finder.jsx). MUST load AFTER
// admin-teacher-finder.jsx (for TF_TONE) and BEFORE admin-leads-campaigns.jsx
// (which uses both window globals defined here).

// Delivery statuses that mean "the text never reached them" — kept in sync with
// cmpDeliveryView() in admin-leads-campaigns.jsx.
const LEADS_NOT_DELIVERED = ['undelivered', 'failed', 'rejected', 'invalid', 'undeliverable'];
// Lead states that mean "done — hide by default": a teacher who opted out, or
// one removed by hand via "Mark dead".
const LEADS_CLOSED_STATES = ['opted_out', 'dead'];

window.LEADS_FILTER = {
  defaults() { return { hideClosed: false, notDeliveredOnly: false }; },

  isActive(f) { return !!(f && (f.hideClosed || f.notDeliveredOnly)); },

  // Does ONE teacher row survive the active filters?
  matchTeacher(t, f) {
    if (!f) return true;
    if (f.hideClosed && LEADS_CLOSED_STATES.includes(t.leadState)) return false;
    if (f.notDeliveredOnly &&
        !LEADS_NOT_DELIVERED.includes(String(t.deliveryStatus || '').toLowerCase())) return false;
    return true;
  },

  // Campaigns with each group's teachers filtered. When a filter is active, a
  // search left with zero matching teachers is dropped entirely (no empty
  // groups to scroll past). With no filter active the input is returned as-is.
  apply(campaigns, f) {
    if (!this.isActive(f)) return campaigns || [];
    return (campaigns || [])
      .map(c => ({ ...c, teachers: (c.teachers || []).filter(t => this.matchTeacher(t, f)) }))
      .filter(c => (c.teachers || []).length > 0);
  },

  // { shown, all } teacher counts across every search, for the bar's summary.
  counts(campaigns, f) {
    let shown = 0, all = 0;
    (campaigns || []).forEach(c => (c.teachers || []).forEach(t => {
      all += 1;
      if (this.matchTeacher(t, f)) shown += 1;
    }));
    return { shown, all };
  },
};

const LeadsFilterBar = ({ filters, onChange, campaigns }) => {
  const f = filters || window.LEADS_FILTER.defaults();
  const active = window.LEADS_FILTER.isActive(f);
  const { shown, all } = window.LEADS_FILTER.counts(campaigns, f);

  const chip = (key, label) => {
    const on = !!f[key];
    return (
      <button
        type="button"
        onClick={() => onChange({ ...f, [key]: !on })}
        aria-pressed={on}
        style={{
          background: on ? 'oklch(55% 0.13 250)' : 'transparent',
          color: on ? '#fff' : TF_TONE.muted,
          border: `1px solid ${on ? 'oklch(55% 0.13 250)' : TF_TONE.border}`,
          borderRadius: 999, padding: '5px 12px', fontSize: 12, fontWeight: 700,
          cursor: 'pointer', fontFamily: "'Plus Jakarta Sans', sans-serif", whiteSpace: 'nowrap',
        }}
      >{on ? '✓ ' : ''}{label}</button>
    );
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', margin: '2px 0 14px' }}>
      <span style={{ fontSize: 10, fontWeight: 700, color: TF_TONE.muted, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Filter</span>
      {chip('hideClosed', 'Hide opted-out & dead')}
      {chip('notDeliveredOnly', 'Only not delivered — to call')}
      {active && (
        <span style={{ fontSize: 12, color: TF_TONE.muted }}>
          Showing <strong style={{ color: TF_TONE.text }}>{shown}</strong> of {all}
        </span>
      )}
      {active && (
        <button
          type="button"
          onClick={() => onChange(window.LEADS_FILTER.defaults())}
          style={{
            background: 'transparent', border: 'none', color: 'oklch(55% 0.13 250)',
            fontSize: 12, fontWeight: 700, cursor: 'pointer', textDecoration: 'underline',
            fontFamily: "'Plus Jakarta Sans', sans-serif", padding: '2px 4px',
          }}
        >Clear</button>
      )}
    </div>
  );
};

window.LeadsFilterBar = LeadsFilterBar;
