/* ============================================================
   MUIY 2.0 — Pool screen (donor network)
   ============================================================ */

function PoolCard({ x, store, i, mine }) {
  const { d, v } = x;
  return (
    <div className={'card stagger' + (mine ? ' pool-card--mine' : '')} style={{ padding: '14px 16px', marginBottom: 12, animationDelay: `${i * 35}ms` }}>
      <div className="row" style={{ alignItems: 'flex-start', gap: 13 }}>
        <Avatar name={d.name} size={48} count={TC.donationCount(d)} photoUrl={d.photoUrl} alt={i % 2 === 1} />
        <button onClick={() => store.openModal('donor', { donor: d })} style={{ flex: 1, minWidth: 0, textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}>
          <div className="row" style={{ gap: 7 }}>
            <span className="dname" style={{ fontSize: 16 }}>{d.name}</span>
            <BloodBadge group={d.bloodGroup} />
            {mine && <span className="mine-tag">Your group</span>}
          </div>
          <div className="dmeta muted">{(() => {const l = TC.lastDonation(d);return l ? `Last donated ${TC.relDays(l.date)}d ago` : 'No donations yet';})()} · {TC.donationCount(d)}×</div>
        </button>
      </div>
      <div className="row" style={{ marginTop: 12, gap: 10 }}>
        <div style={{ flex: 1 }}><StatusChip donor={d} /></div>
        <button className="icon-btn call" style={{ width: 38, height: 38 }} onClick={() => {window.location.href = `tel:${d.mobile}`;}} aria-label="Call"><Icon name="phone" size={17} /></button>
        <button className="icon-btn msg" style={{ width: 38, height: 38 }} onClick={() => store.openModal('contact', { donor: d })} aria-label="Message"><Icon name="chat" size={17} /></button>
      </div>
    </div>);

}

function PoolScreen({ store }) {
  const { donors, poolFilter, setPoolFilter } = store;
  const myGroup = store.patient.bloodGroup || null;
  const [search, setSearch] = React.useState('');
  const [triage, setTriage] = React.useState(poolFilter || null);
  const [bg, setBg] = React.useState(null);
  const [sort, setSort] = React.useState('available');
  const [filterOpen, setFilterOpen] = React.useState(false);
  // donor-group visibility: 'mine' = only the patient's own group, 'others' = every other group
  const [groupView, setGroupView] = React.useState('mine');
  React.useEffect(() => {if (poolFilter) {setTriage(poolFilter);setPoolFilter(null);}}, []);

  const active = donors.filter((d) => !d.archived);
  const isMine = (x) => !!myGroup && x.d.bloodGroup === myGroup;
  const mineTotal = active.filter((d) => myGroup && d.bloodGroup === myGroup).length;
  const otherTotal = active.length - mineTotal;
  // The group view is the primary lens: 'mine' shows ONLY the patient's own group,
  // 'others' shows ONLY every other group. They are mutually exclusive — a donor is
  // never visible in both. The view applies whenever the patient has a known group and
  // no explicit single-group filter (bg) is active. Triage tallies, the header summary,
  // search and sorting all flow from the resulting `base`, so everything stays in sync.
  const groupScoped = myGroup && !bg;
  const viewingMine = groupView === 'mine';

  // ── single source of truth ──────────────────────────────────────────────
  // `base` is the donor set after Search + Blood-group filter + the my-group
  // toggle, but BEFORE the triage tile selection. The triage tiles and the
  // header summary count buckets *within* this base, so tiles, header, search
  // and filters always agree. The visible list is `base` narrowed by the
  // currently-selected triage tile, then sorted.
  let base = active.map((d) => ({ d, v: statusVisual(d) }));
  if (search.trim()) {const q = search.toLowerCase();base = base.filter(({ d }) => d.name.toLowerCase().includes(q) || d.mobile.includes(q) || d.bloodGroup.toLowerCase().includes(q));}
  if (bg) base = base.filter((x) => x.d.bloodGroup === bg);
  // strict group separation: mine excludes all other groups; others excludes the patient's group
  if (groupScoped) base = base.filter(viewingMine ? isMine : (x) => !isMine(x));

  const counts = { eligible: 0, soon: 0, waiting: 0, deferred: 0 };
  base.forEach((x) => {counts[x.v.s.status.toLowerCase()]++;});

  let list = triage ? base.filter((x) => x.v.s.status === triage.toUpperCase()) : base.slice();

  const lastDate = (d) => {const l = TC.lastDonation(d);return l ? TC.parse(l.date).getTime() : 0;};
  const statusOrder = { ELIGIBLE: 0, SOON: 1, WAITING: 2, DEFERRED: 3 };
  const byName = (a, b) => a.d.name.localeCompare(b.d.name);
  const sorters = {
    available: (a, b) => statusOrder[a.v.s.status] - statusOrder[b.v.s.status] || (b.v.s.daysRested || 0) - (a.v.s.daysRested || 0),
    most: (a, b) => TC.donationCount(b.d) - TC.donationCount(a.d) || byName(a, b),
    recent: (a, b) => lastDate(b.d) - lastDate(a.d) || byName(a, b),
    group: (a, b) => TC.BLOOD_GROUPS.indexOf(a.d.bloodGroup) - TC.BLOOD_GROUPS.indexOf(b.d.bloodGroup) || byName(a, b)
  };
  // the list is now a single group lens (only-mine or only-others), so it is homogeneous;
  // apply the chosen sort directly with no same-group-first reshuffling or divider needed
  const baseSorter = sorters[sort] || sorters.available;
  list.sort(baseSorter);

  const sortOpts = [
  { k: 'available', l: 'Availability' },
  { k: 'most', l: 'Most donations' },
  { k: 'recent', l: 'Most recent' },
  { k: 'group', l: 'Blood group' }];

  const activeFilters = (bg ? 1 : 0) + (sort !== 'available' ? 1 : 0);
  const sortLabel = (sortOpts.find((o) => o.k === sort) || sortOpts[0]).l;

  const triages = [
  { k: 'eligible', l: 'Eligible', n: counts.eligible, color: 'var(--green)', wash: 'var(--green-wash)', icon: 'checkCircle' },
  { k: 'soon', l: 'Due soon', n: counts.soon, color: 'var(--orange)', wash: 'var(--yellow-wash)', icon: 'clock' },
  { k: 'deferred', l: 'Deferred', n: counts.deferred, color: 'var(--slate)', wash: 'var(--slate-wash)', icon: 'shield' }];

  // context-aware empty message reflecting the active group lens
  const emptyHint = search.trim() || bg || triage ?
    'Try clearing search or filters.' :
    groupScoped && viewingMine ? `No donors in your ${myGroup} group yet.` :
    groupScoped ? 'No donors in other groups yet.' :
    'Add a donor to get started.';


  return (
    <div className="tc-scroll"><div className="tc-page tc-page--top">
      <div className="between" style={{ alignItems: 'flex-start' }}>
        <div>
          <div className="h1">My Donor Pool</div>
          <div className="body" style={{ marginTop: 3, fontSize: 13 }}>{counts.eligible} eligible · {counts.soon} soon · {counts.waiting} waiting</div>
        </div>
        <div className="row" style={{ gap: 6, flex: 'none' }}>
          <SyncBadge store={store} />
          <button className="icon-btn" style={{ width: 44, height: 44 }} onClick={() => store.openModal('exportDonors', {})} aria-label="Export donors as PDF"><Icon name="download" size={20} color="var(--ink-2)" /></button>
          <button className="icon-btn" style={{ width: 44, height: 44 }} onClick={() => store.openModal('editDonor', {})} aria-label="Add donor"><Icon name="plus" size={22} color="var(--orange)" /></button>
        </div>
      </div>

      {/* search + inline filter/sort */}
      <div style={{ marginTop: 16, position: 'relative' }}>
        <div className="card-flat row" style={{ gap: 9, padding: '7px 8px 7px 14px' }}>
          <Icon name="search" size={18} color="var(--ink-3)" />
          <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Search name, number, group…" style={{ flex: 1, minWidth: 0, border: 'none', background: 'none', outline: 'none', fontFamily: 'inherit', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }} />
          {search && <button className="icon-btn" style={{ width: 26, height: 26, flex: 'none' }} onClick={() => setSearch('')} aria-label="Clear search"><Icon name="x" size={14} /></button>}
          <button className="row" onClick={() => setFilterOpen((o) => !o)} aria-label="Filter and sort" style={{ flex: 'none', gap: 6, padding: '7px 11px', borderRadius: 11, border: 'none', cursor: 'pointer', fontFamily: 'inherit', background: filterOpen || activeFilters ? 'var(--orange)' : 'var(--surface-2)', color: filterOpen || activeFilters ? '#fff' : 'var(--ink-2)' }}>
            <Icon name="sort" size={16} color={filterOpen || activeFilters ? '#fff' : 'var(--ink-2)'} />
            <span style={{ fontSize: 12.5, fontWeight: 800 }}>Filter</span>
            {activeFilters > 0 && <span style={{ minWidth: 17, height: 17, borderRadius: 9, background: '#fff', color: 'var(--orange)', fontSize: 11, fontWeight: 800, display: 'grid', placeItems: 'center', padding: '0 4px' }}>{activeFilters}</span>}
          </button>
        </div>

        {filterOpen &&
          <div className="card stagger" style={{ padding: '14px 15px 15px', marginTop: 8 }}>
            <div className="between" style={{ marginBottom: 9 }}>
              <span style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>Sort by</span>
              {activeFilters > 0 && <button onClick={() => {setSort('available');setBg(null);}} style={{ border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 700, color: 'var(--orange)' }}>Reset</button>}
            </div>
            <div className="row" style={{ gap: 7, flexWrap: 'wrap' }}>
              {sortOpts.map((o) => <button key={o.k} className={'chip' + (sort === o.k ? ' on' : '')} onClick={() => setSort(o.k)}>{o.l}</button>)}
            </div>
            <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '15px 0 9px' }}>Blood group</div>
            <div className="row" style={{ gap: 7, flexWrap: 'wrap' }}>
              <button className={'chip' + (!bg ? ' on' : '')} onClick={() => setBg(null)}>All</button>
              {TC.BLOOD_GROUPS.map((g) => <button key={g} className={'chip' + (bg === g ? ' on' : '')} onClick={() => setBg(bg === g ? null : g)}>{g}</button>)}
            </div>
          </div>
          }
      </div>

      {/* active filter summary (when panel collapsed) */}
      {!filterOpen && activeFilters > 0 &&
        <div className="row" style={{ gap: 7, marginTop: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink-3)' }}>Sorted by {sortLabel.toLowerCase()}</span>
          {bg && <span className="chip on" style={{ cursor: 'default' }}>{bg}</span>}
        </div>
        }

      {/* triage tiles */}
      <div className="row" style={{ gap: 10, marginTop: 12 }}>
        {triages.map((t) => {
            const on = triage === t.k;
            return (
              <button key={t.k} className="stat" style={{ flex: 1, padding: '12px 13px', background: on ? t.color : 'var(--surface)', boxShadow: on ? 'var(--sh)' : 'var(--sh-sm)' }} onClick={() => setTriage(on ? null : t.k)}>
              <div className="row" style={{ gap: 7 }}><Icon name={t.icon} size={15} color={on ? '#fff' : t.color} /><span className="num" style={{ fontSize: 20, fontWeight: 800, color: on ? '#fff' : t.color }}>{t.n}</span></div>
              <div className="l" style={{ color: on ? 'rgba(255,255,255,.9)' : 'var(--ink-3)', marginTop: 3 }}>{t.l}</div>
            </button>);

          })}
      </div>

      {/* blood group chips removed — folded into the search Filter panel */}

      {/* donor-group visibility — strict, mutually-exclusive lens (composes with triage + search) */}
      {groupScoped &&
        <div style={{ marginTop: 16 }}>
          <div className="seg" role="tablist" aria-label="Donor group visibility">
            <button role="tab" aria-selected={viewingMine} className={viewingMine ? 'on' : ''} onClick={() => setGroupView('mine')}>
              <span className="gv-label">Your donors only</span>
              <span className="gv-count">{mineTotal}</span>
            </button>
            <button role="tab" aria-selected={!viewingMine} className={!viewingMine ? 'on' : ''} onClick={() => setGroupView('others')}>
              <span className="gv-label">Other groups</span>
              <span className="gv-count">{otherTotal}</span>
            </button>
          </div>
          <div className="gv-sub">{viewingMine ?
            `Showing only your ${myGroup} group — other groups hidden` :
            `Showing every group except ${myGroup} — your group hidden`}</div>
        </div>
        }

      {/* list */}
      <div style={{ marginTop: 16 }}>
        {list.length === 0 ?
          <EmptyState title="No donors match" sub={emptyHint} /> :
          list.map((x, i) =>
            <PoolCard key={x.d.id} x={x} store={store} i={i} mine={isMine(x)} />
          )}
      </div>
    </div></div>);

}

Object.assign(window, { PoolScreen, PoolCard });