// Shared UI components: WeekStrip, PersonPicker, LocChip, Avatar.

const { useState, useRef, useEffect, useMemo } = React;
const { DAYS, SLOTS, WEEKS, LOCATIONS, CLIENTS, THERAPISTS } = window.FS_DATA;

function LocChip({ loc, small }) {
  const locs = Array.isArray(loc) ? loc : (loc ? [loc] : []);
  return (
    <>
      {locs.map(lid => {
        const l = window.FS_DATA.getLoc(lid);
        if (!l) return null;
        return (
          <span key={lid} className={`loc-chip loc-${lid}`} style={small ? {fontSize: 10, padding: '2px 6px'} : {}}>
            {l.short}
          </span>
        );
      })}
    </>
  );
}

// Deterministic avatar color from id
function avatarHue(id) {
  let h = 0;
  for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) % 360;
  return h;
}
function Avatar({ id, short, size = 32, accent }) {
  const hue = avatarHue(id);
  const bg = accent || `hsl(${hue}, 32%, 42%)`;
  return (
    <span className="person-avatar" style={{
      width: size, height: size,
      background: bg,
      fontSize: size <= 22 ? 9 : size <= 28 ? 11 : 13,
    }}>
      {short}
    </span>
  );
}

function WeekStrip({ value, onChange, sparks }) {
  return (
    <div className="weekstrip" role="tablist" aria-label="Week">
      {WEEKS.map(w => {
        const active = value === w.id;
        const fill = sparks ? Math.round((sparks[w.id] || 0) * 100) : 0;
        return (
          <button
            key={w.id}
            className={`weekpill ${active ? 'active' : ''}`}
            onClick={() => onChange(w.id)}
            role="tab"
            aria-selected={active}
          >
            <div className="wp-month">{w.month}</div>
            <div className="wp-day">{w.day}</div>
            <div className="wp-spark" title={`${fill}% slot utilization`}>
              <div className="wp-spark-fill" style={{ width: `${fill}%` }} />
            </div>
          </button>
        );
      })}
    </div>
  );
}

function PersonPicker({ kind, value, onChange }) {
  const list = kind === 'client' ? CLIENTS : THERAPISTS;
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    function handler(e) {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    }
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const selected = list.find(p => p.id === value) || list[0];

  return (
    <div className="person-dropdown" ref={ref} onClick={() => setOpen(o => !o)}>
      <Avatar id={selected.id} short={selected.short} />
      <div className="person-info">
        <div className="person-name">{selected.name}</div>
        <div className="person-meta">
          <LocChip loc={selected.loc} small />
          {selected.title && <span style={{marginLeft: 6, color: 'var(--ink-500)'}}>{selected.title}</span>}
        </div>
      </div>
      <span className="person-chev">▾</span>
      {open && (
        <div className="person-menu" onClick={e => e.stopPropagation()}>
          {list.map(p => (
            <div
              key={p.id}
              className={`person-menu-item ${p.id === value ? 'selected' : ''}`}
              onClick={() => { onChange(p.id); setOpen(false); }}
            >
              <Avatar id={p.id} short={p.short} size={28} />
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 13, fontWeight: 600}}>{p.name}</div>
                <div style={{fontSize: 11, color: 'var(--ink-500)', marginTop: 1}}>
                  <LocChip loc={p.loc} small />
                  {p.title && <span style={{marginLeft: 6}}>{p.title}</span>}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Reusable picker modal — used to add therapists to a client's pairings.
function PickerModal({ title, items, excludeIds, onPick, onClose, hint }) {
  const [q, setQ] = useState('');
  const filtered = items.filter(i =>
    !excludeIds.includes(i.id) &&
    (q === '' || i.name.toLowerCase().includes(q.toLowerCase()))
  );
  return (
    <div className="picker-backdrop" onClick={onClose}>
      <div className="picker" onClick={e => e.stopPropagation()}>
        <h3 className="picker-title">{title}</h3>
        {hint && <div style={{fontSize: 12, color: 'var(--ink-500)'}}>{hint}</div>}
        <input
          className="picker-search"
          placeholder="Search…"
          value={q}
          onChange={e => setQ(e.target.value)}
          autoFocus
        />
        <div className="picker-list">
          {filtered.length === 0 && <div className="empty-state" style={{padding: 20}}>No results</div>}
          {filtered.map(i => (
            <div
              key={i.id}
              className="person-menu-item"
              onClick={() => { onPick(i.id); onClose(); }}
            >
              <Avatar id={i.id} short={i.short} size={28} />
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 13, fontWeight: 600}}>{i.name}</div>
                <div style={{fontSize: 11, color: 'var(--ink-500)', marginTop: 1}}>
                  <LocChip loc={i.loc} small />
                  {i.title && <span style={{marginLeft: 6}}>{i.title}</span>}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// Compact pair chip used in schedule cells & locked view.
function PairChip({ clientId, therapistId, unmatched, onClick }) {
  const c = window.FS_DATA.getClient(clientId);
  const t = therapistId ? window.FS_DATA.getTherapist(therapistId) : null;
  return (
    <div
      className={`sched-pair ${unmatched ? 'unmatched' : ''}`}
      onClick={onClick}
      title={
        unmatched
          ? `${c.name} — no therapist matched. Click for negotiation suggestions.`
          : `${c.name} with ${t.name}`
      }
      style={{ cursor: 'pointer' }}
    >
      <span style={{fontWeight: 700}}>{c.short}</span>
      <span className="pair-arrow">+</span>
      <span style={{fontWeight: unmatched ? 700 : 600}}>{t ? t.short : '?'}</span>
    </div>
  );
}

Object.assign(window, {
  LocChip, Avatar, WeekStrip, PersonPicker, PickerModal, PairChip,
});
