/* ============================================================
   UNSTOPPABLES — Clients (roster redesign)
   Minimal people-first list · lenses by Form Category ·
   search + filters · opens the sectioned Client Dossier
   Exports: ClientsPage
   ============================================================ */

const ROSTER_STATUS_TONE = { Active: 'leaf', Monitoring: 'gold', Waitlist: 'blue', Closed: 'plum' };
const ROSTER_CAT_TONE = { 'Food': 'gold', 'Settlement': 'blue', 'Domestic Violence': 'plum' };

function ClientsPage({ role, push, params = {}, requestAdmin, openPage }) {
  const D = window.TRELLIS_DATA;
  const S = window.TRELLIS_SCHEMA;

  // re-derive when the live Firestore subscription updates
  const [dataTick, setDataTick] = React.useState(0);
  React.useEffect(() => {
    const bump = () => setDataTick(t => t + 1);
    document.addEventListener('ehcw:data:clients', bump);
    document.addEventListener('ehcw:data:visits', bump);
    return () => { document.removeEventListener('ehcw:data:clients', bump); document.removeEventListener('ehcw:data:visits', bump); };
  }, []);

  // derive the redesigned record (category, real caseworker, completeness)
  const roster = React.useMemo(() => D.clients.map(c => {
    const rec = S.recordFor(c);
    return {
      ...c,
      displayName: `${c.firstName}${c.lastName ? ' ' + c.lastName[0] + '.' : ''}`,
      category: rec.formCategory,
      caseworker: rec.caseworker,
      staff: S.EHCW_STAFF.find(s => s.name === rec.caseworker),
      location: (rec.city && !/\d/.test(rec.city) ? rec.city : '') || rec.foodLocation || rec.seniorLocation || '—',
      pct: S.completeness(rec),
      totalVisits: rec.totalVisits, lastVisit: rec.lastVisitDate
    };
  }), [dataTick]);

  const [lens, setLens] = React.useState(params.lens || 'All');
  const [q, setQ] = React.useState('');
  const [fCw, setFCw] = React.useState(params.caseworker || '');
  const [fStatus, setFStatus] = React.useState('');
  const [fLoc, setFLoc] = React.useState('');
  const [open, setOpen] = React.useState(null);
  React.useEffect(() => { if (params.caseworker) setFCw(params.caseworker); }, [params.caseworker]);

  const LENSES = ['All', 'Food', 'Settlement', 'Domestic Violence', 'Needs category'];
  const filtered = roster.filter(c => {
    if (lens === 'Needs category' && c.category) return false;
    if (lens !== 'All' && lens !== 'Needs category' && c.category !== lens) return false;
    if (role !== 'admin' && false) return false; // caseworker sees all in prototype demo subset
    if (q) {
      const hay = (c.displayName + ' ' + c.id + ' ' + c.firstName).toLowerCase();
      if (!hay.includes(q.toLowerCase())) return false;
    }
    if (fCw && c.caseworker !== fCw) return false;
    if (fStatus && c.status !== fStatus) return false;
    if (fLoc && c.location !== fLoc) return false;
    return true;
  });

  const needsCat = roster.filter(c => !c.category).length;
  const selStyle = {
    padding: '9px 12px', borderRadius: 11, border: '1px solid var(--hairline-strong)',
    background: 'var(--glass-input)', fontSize: 12.5, fontWeight: 600, outline: 'none', appearance: 'none', color: 'var(--ink)'
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 14, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', fontWeight: 700, letterSpacing: '-0.025em' }}>Clients</h1>
          <p className="t-soft" style={{ margin: '6px 0 0', fontSize: 14.5 }}>{roster.length} records · expands only what you need — never a flat table.</p>
        </div>
        <button onClick={() => openPage && openPage('checkin', { flow: 'new' })} style={{
          display: 'inline-flex', alignItems: 'center', gap: 8, padding: '12px 20px', borderRadius: 14,
          fontSize: 13.5, fontWeight: 700, fontFamily: 'var(--font-display)',
          background: 'var(--accent)', color: 'var(--accent-ink)', boxShadow: 'var(--shadow-card)', minHeight: 44
        }}><Icon name="plus" size={15} stroke={2.4} /> New Client</button>
      </div>

      {/* lenses */}
      <div className="glass" style={{ display: 'flex', borderRadius: 16, padding: 5, width: 'fit-content', gap: 4, flexWrap: 'wrap', maxWidth: '100%' }}>
        {LENSES.map(l => {
          const on = lens === l;
          const label = l === 'Needs category' ? `Needs category (${needsCat})` : l;
          return (
            <button key={l} onClick={() => setLens(l)} style={{
              padding: '9px 16px', borderRadius: 12, fontSize: 13, fontWeight: 700, minHeight: 40,
              background: on ? (l === 'Needs category' ? 'var(--coral)' : 'var(--accent)') : 'transparent',
              color: on ? (l === 'Needs category' ? 'white' : 'var(--accent-ink)') : l === 'Needs category' && needsCat ? 'var(--coral)' : 'var(--ink-soft)',
              transition: 'all .2s'
            }}>{label}</button>
          );
        })}
      </div>

      {/* search + filters */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 200, maxWidth: 360 }}>
          <Icon name="search" size={15} node={false} style={{ position: 'absolute', left: 13, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-faint)' }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search name or Client ID…" style={{
            width: '100%', padding: '11px 14px 11px 38px', borderRadius: 13, border: '1px solid var(--hairline-strong)',
            background: 'var(--glass-input)', fontSize: 13.5, outline: 'none', boxSizing: 'border-box'
          }} />
        </div>
        <select value={fCw} onChange={e => setFCw(e.target.value)} style={selStyle}>
          <option value="">All caseworkers</option>
          {S.EHCW_STAFF.map(s => <option key={s.name} value={s.name}>{s.name}</option>)}
        </select>
        <select value={fStatus} onChange={e => setFStatus(e.target.value)} style={selStyle}>
          <option value="">All statuses</option>
          {['Active', 'Monitoring', 'Waitlist', 'Closed'].map(s => <option key={s} value={s}>{s}</option>)}
        </select>
        <select value={fLoc} onChange={e => setFLoc(e.target.value)} style={selStyle}>
          <option value="">All locations</option>
          {S.LOCATIONS.map(l => <option key={l} value={l}>{l}</option>)}
        </select>
        <span className="t-faint mono" style={{ fontSize: 12, marginLeft: 'auto' }}>{filtered.length} shown · of {roster.length} records</span>
      </div>

      {/* roster */}
      <div className="glass" style={{ borderRadius: 'var(--radius-l)', overflow: 'hidden', boxShadow: 'var(--shadow-card)' }}>
        {filtered.length === 0 && (
          <div style={{ padding: '40px 20px', textAlign: 'center' }} className="t-faint">No clients match — adjust the lens or filters.</div>
        )}
        {filtered.map((c, i) => (
          <button key={c.id} onClick={() => setOpen(c)} style={{
            display: 'flex', alignItems: 'center', gap: 14, width: '100%', textAlign: 'left',
            padding: '13px 18px', borderTop: i === 0 ? 'none' : '1px solid var(--hairline)',
            transition: 'background .15s', minHeight: 64
          }}
            onMouseEnter={e => e.currentTarget.style.background = 'var(--hover)'}
            onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            <Avatar initials={c.initials} hue={parseInt(c.id.slice(3), 10) % 360} size={38} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 14.5, fontWeight: 700, whiteSpace: 'nowrap' }}>{c.displayName}</span>
                <span className="mono t-faint" style={{ fontSize: 12 }}>{c.id}</span>
                {c.category ? (
                  <Badge tone={ROSTER_CAT_TONE[c.category]}>{c.category}</Badge>
                ) : (
                  <Badge tone="coral"><Icon name="spark" size={10} node={false} /> Set category</Badge>
                )}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 4 }}>
                {c.caseworker ? (
                  <React.Fragment>
                    <StaffAvatar staff={c.staff || { name: c.caseworker, initials: c.caseworker.split(' ').map(w => w[0]).join('').slice(0, 2) }} size={18} />
                    <span className="t-soft" style={{ fontSize: 12, fontWeight: 600 }}>{c.caseworker}</span>
                  </React.Fragment>
                ) : (
                  <span className="t-faint" style={{ fontSize: 11.5, fontWeight: 600, fontStyle: 'italic' }}>Unassigned — open record to assign</span>
                )}
                <span className="t-faint" style={{ fontSize: 11.5 }}>· {c.location}</span>
              </div>
            </div>
            <div className="trellis-roster-meta" style={{ display: 'flex', alignItems: 'center', gap: 14, flexShrink: 0 }}>
              <div style={{ textAlign: 'right' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, background: c.status === 'Active' ? 'var(--leaf)' : c.status === 'Waitlist' ? 'var(--blue)' : c.status === 'Monitoring' ? 'var(--gold-deep)' : 'var(--ink-faint)' }}></span>
                  <span style={{ fontSize: 12, fontWeight: 700 }}>{c.status}</span>
                </div>
                <div className="t-faint mono" style={{ fontSize: 11, marginTop: 3 }}>{c.totalVisits} visits · {c.lastVisit}</div>
              </div>
              <CompletenessRing pct={c.pct} size={36} />
              <Icon name="chevR" size={15} stroke={2.2} style={{ color: 'var(--ink-faint)' }} />
            </div>
          </button>
        ))}
      </div>

      <style>{`@media (max-width: 640px) { .trellis-roster-meta > div:first-child { display: none; } }`}</style>

      {open && <ClientDossier key={open.id} client={open} role={role} onClose={() => setOpen(null)} push={push} requestAdmin={requestAdmin} />}
    </div>
  );
}

Object.assign(window, { ClientsPage });
