// Settings tab — manage clients, therapists, and matching settings.

function SettingsTab({ clients, therapists, slotThreshold, onSetClients, onSetTherapists, onSetThreshold }) {
  const { LOCATIONS } = window.FS_DATA;

  const editClient = (idx, patch) => {
    const next = clients.map((c, i) => i === idx ? { ...c, ...patch } : c);
    onSetClients(next);
  };
  const editTherapist = (idx, patch) => {
    const next = therapists.map((t, i) => i === idx ? { ...t, ...patch } : t);
    onSetTherapists(next);
  };
  const delClient = (idx) => {
    if (!confirm(`Remove ${clients[idx].name}?`)) return;
    onSetClients(clients.filter((_, i) => i !== idx));
  };
  const delTherapist = (idx) => {
    if (!confirm(`Remove ${therapists[idx].name}?`)) return;
    onSetTherapists(therapists.filter((_, i) => i !== idx));
  };
  const addClient = () => {
    const n = clients.length + 1;
    const id = "c" + String(Date.now()).slice(-5);
    onSetClients([...clients, { id, name: `New client ${n}`, short: "New1", loc: ["clinic"] }]);
  };
  const addTherapist = () => {
    const n = therapists.length + 1;
    const id = "t" + String(Date.now()).slice(-5);
    onSetTherapists([...therapists, { id, name: `New therapist ${n}`, short: "NT", loc: ["clinic"], title: "BT" }]);
  };

  const locToString = (loc) => Array.isArray(loc) ? loc.join(', ') : (loc || '');
  const parseLocInput = (val) => val.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);

  return (
    <div>
      <div className="settings-section" style={{marginBottom: 14, maxWidth: 720}}>
        <h3>Matching settings</h3>
        <div className="settings-field">
          <label>Minimum sessions per slot to count toward "slot utilization"</label>
          <div style={{display: 'flex', alignItems: 'center', gap: 12}}>
            <div className="num-stepper">
              <button onClick={() => onSetThreshold(Math.max(1, slotThreshold - 1))}>−</button>
              <input type="text" readOnly value={slotThreshold} />
              <button onClick={() => onSetThreshold(Math.min(10, slotThreshold + 1))}>+</button>
            </div>
            <span style={{fontSize: 12, color: 'var(--ink-500)'}}>
              A slot must have at least {slotThreshold} matched session{slotThreshold > 1 ? 's' : ''} to count.
            </span>
          </div>
          <div className="field-hint">
            Slot utilization measures how many of the 15 weekly slots are "doing work." Set higher if you want slot utilization to reflect only well-utilized time blocks; set to 1 to count any non-empty slot.
          </div>
        </div>
      </div>

      <div className="settings-grid">
        <div className="settings-section">
          <h3>
            <span>Clients <span style={{color: 'var(--ink-500)', fontWeight: 500}}>· {clients.length}</span></span>
          </h3>
          <div className="roster-row roster-header">
            <span>Name</span><span>Init.</span><span>Location</span><span></span><span></span>
          </div>
          {clients.map((c, i) => (
            <div className="roster-row" key={c.id}>
              <input value={c.name} onChange={e => editClient(i, { name: e.target.value })} />
              <input value={c.short} maxLength={4} onChange={e => editClient(i, { short: e.target.value.toUpperCase() })} />
              <input value={locToString(c.loc)} placeholder="clinic, east" title="Comma-separated: east, west, clinic, ucis"
                onChange={e => editClient(i, { loc: parseLocInput(e.target.value) })} style={{fontSize: 11}} />
              <span></span>
              <button className="icon-del" onClick={() => delClient(i)} title="Remove">✕</button>
            </div>
          ))}
          <button className="settings-add" onClick={addClient}>+ Add client</button>
        </div>

        <div className="settings-section">
          <h3>
            <span>Therapists <span style={{color: 'var(--ink-500)', fontWeight: 500}}>· {therapists.length}</span></span>
          </h3>
          <div className="roster-row roster-header">
            <span>Name</span><span>Init.</span><span>Location</span><span>Title</span><span></span>
          </div>
          {therapists.map((t, i) => (
            <div className="roster-row" key={t.id}>
              <input value={t.name} onChange={e => editTherapist(i, { name: e.target.value })} />
              <input value={t.short} maxLength={3} onChange={e => editTherapist(i, { short: e.target.value.toUpperCase() })} />
              <input value={locToString(t.loc)} placeholder="clinic, west" title="Comma-separated: east, west, clinic, ucis"
                onChange={e => editTherapist(i, { loc: parseLocInput(e.target.value) })} style={{fontSize: 11}} />
              <select value={t.title} onChange={e => editTherapist(i, { title: e.target.value })}>
                {['BT','LBA','LABA','BCBA'].map(x => <option key={x} value={x}>{x}</option>)}
              </select>
              <button className="icon-del" onClick={() => delTherapist(i)} title="Remove">✕</button>
            </div>
          ))}
          <button className="settings-add" onClick={addTherapist}>+ Add therapist</button>
        </div>
      </div>
    </div>
  );
}

window.SettingsTab = SettingsTab;
