// Therapist → Client pairings tab. Read-only priority view; add/remove clients per therapist.

const { useState: useStateTP } = React;

function TherapistPairingsTab({ pairings, onAdd, onRemove }) {
  const [selectedTherapist, setSelectedTherapist] = useStateTP(window.FS_DATA.THERAPISTS[0].id);
  const [pickerOpen, setPickerOpen] = useStateTP(false);

  const therapist = window.FS_DATA.getTherapist(selectedTherapist);
  const clients = window.FS_DATA.CLIENTS;
  const therapists = window.FS_DATA.THERAPISTS;

  // For each client, find the priority rank of the selected therapist (1-based), or -1.
  const pairedEntries = clients
    .map(c => {
      const idx = (pairings[c.id] || []).indexOf(selectedTherapist);
      return idx === -1 ? null : { client: c, priority: idx + 1 };
    })
    .filter(Boolean);

  const pairedClientIds = pairedEntries.map(e => e.client.id);

  const handleRemove = (cid) => {
    const idx = (pairings[cid] || []).indexOf(selectedTherapist);
    if (idx !== -1) onRemove(cid, idx);
  };

  return (
    <div className="panel" style={{padding: '24px 28px 32px'}}>
      <div className="panel-head" style={{alignItems: 'flex-start'}}>
        <div>
          <div className="panel-eyebrow">Pairings</div>
          <h3 className="panel-title" style={{marginTop: 4}}>Which clients each therapist serves</h3>
          <div className="muted" style={{fontSize: 13, marginTop: 6, maxWidth: 560}}>
            Add clients to a therapist's roster. Priority rank shown is read-only — reorder from the
            Client → Therapist tab. Adding a client places this therapist last in that client's priority list.
          </div>
        </div>
      </div>

      <div className="pairings-grid">
        {/* Left: therapist list */}
        <div>
          <div className="panel-eyebrow" style={{padding: '0 10px', marginBottom: 8}}>Therapists</div>
          <div className="client-list">
            {therapists.map(t => {
              const clientCount = clients.filter(c => (pairings[c.id] || []).includes(t.id)).length;
              return (
                <div
                  key={t.id}
                  className={`client-row ${t.id === selectedTherapist ? 'selected' : ''}`}
                  onClick={() => setSelectedTherapist(t.id)}
                >
                  <window.Avatar id={t.id} short={t.short} size={28} />
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 13, fontWeight: 600}}>{t.name}</div>
                    <div style={{fontSize: 11, color: 'var(--ink-500)', marginTop: 1}}>
                      <window.LocChip loc={t.loc} small />
                      <span style={{marginLeft: 6}}>{t.title}</span>
                      <span style={{marginLeft: 6}}>{clientCount} client{clientCount !== 1 ? 's' : ''}</span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Right: clients for selected therapist */}
        <div>
          <div className="panel-eyebrow" style={{padding: '0 10px', marginBottom: 8}}>
            Clients — {therapist.name}
          </div>
          <div className="priority-list">
            {pairedEntries.length === 0 && (
              <div className="empty-state" style={{padding: '20px 14px'}}>No clients assigned yet</div>
            )}
            {pairedEntries.map(({ client: c, priority }) => {
              const tLocs = Array.isArray(therapist.loc) ? therapist.loc : [therapist.loc];
              const cLocs = Array.isArray(c.loc) ? c.loc : [c.loc];
              const isCrossLoc = !cLocs.some(l => tLocs.includes(l));
              return (
                <div key={c.id} className="priority-row">
                  <div
                    className="priority-num"
                    title={`Rank ${priority} in ${c.name}'s therapist list`}
                    style={{background: 'var(--ink-400)'}}
                  >
                    {priority}
                  </div>
                  <window.Avatar id={c.id} short={c.short} size={28} />
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 14, fontWeight: 600}}>{c.name}</div>
                    <div style={{fontSize: 11, color: 'var(--ink-500)', marginTop: 1, display: 'flex', alignItems: 'center', gap: 6}}>
                      <window.LocChip loc={c.loc} small />
                      {isCrossLoc && (
                        <span style={{color: 'var(--accent-coral)', fontWeight: 600}}>
                          ⚠ Different location — won't be matched
                        </span>
                      )}
                    </div>
                  </div>
                  <span style={{fontSize: 10, color: 'var(--ink-400)', whiteSpace: 'nowrap'}}>
                    priority #{priority}
                  </span>
                  <button
                    className="priority-icon-btn"
                    onClick={() => handleRemove(c.id)}
                    title="Remove"
                    style={{color: 'var(--accent-coral)'}}
                  >✕</button>
                </div>
              );
            })}
            <button className="priority-add" onClick={() => setPickerOpen(true)}>
              + Add a client
            </button>
          </div>
        </div>
      </div>

      {pickerOpen && (
        <window.PickerModal
          title={`Add a client for ${therapist.name}`}
          hint={`${therapist.name} is at ${(Array.isArray(therapist.loc) ? therapist.loc : [therapist.loc]).map(l => window.FS_DATA.getLoc(l)?.label || l).join(' / ')}. This therapist will be added as the last priority for the selected client.`}
          items={clients}
          excludeIds={pairedClientIds}
          onPick={(cid) => { onAdd(cid, selectedTherapist); }}
          onClose={() => setPickerOpen(false)}
        />
      )}
    </div>
  );
}

window.TherapistPairingsTab = TherapistPairingsTab;
