// Schedule preview — live matched grid. Highlights selected person's pills.
// Optional "filter to selected" toggle. Metrics removed (now at bottom).

function SchedulePreview({
  weekIdx,
  schedule,
  highlightId,        // client or therapist id to highlight
  highlightKind,      // 'client' | 'therapist'
  filterMode,
  onToggleFilter,
  onJumpToTherapist,
  onJumpToClient,
}) {
  const { DAYS, SLOTS, WEEKS } = window.FS_DATA;

  const cellClass = (cell) => {
    const m = cell.matched.length;
    const u = cell.unmatched.length;
    if (m + u === 0) return '';
    if (u > 0 && m === 0) return '';
    if (u > 0) return 'partial';
    return 'full';
  };

  const isHighlighted = (m) => {
    if (!highlightId) return false;
    return highlightKind === 'client' ? m.clientId === highlightId : m.therapistId === highlightId;
  };

  return (
    <div className="panel">
      <div className="panel-head">
        <div>
          <div className="panel-eyebrow">Live schedule</div>
          <h3 className="panel-title" style={{marginTop: 2}}>
            Week of {WEEKS[weekIdx].month} {WEEKS[weekIdx].day}
          </h3>
        </div>
        <label className={`filter-toggle ${filterMode ? 'on' : ''}`}>
          <input
            type="checkbox"
            checked={!!filterMode}
            onChange={(e) => onToggleFilter(e.target.checked)}
          />
          Just show selected {highlightKind}
        </label>
      </div>

      <div className="avail-grid">
        <div></div>
        {DAYS.map(d => (<div key={d.id} className="avail-head">{d.label}</div>))}
        {SLOTS.map((slot, sIdx) => (
          <React.Fragment key={slot.id}>
            <div className="avail-slot-label">
              <span>{slot.label}</span>
              <span className="slot-time">{slot.time}</span>
            </div>
            {DAYS.map(d => {
              const cell = schedule[d.id][sIdx];
              const filteredMatched = filterMode
                ? cell.matched.filter(m => isHighlighted(m))
                : cell.matched;
              const filteredUnmatched = filterMode
                ? (highlightKind === 'client' ? cell.unmatched.filter(c => c === highlightId) : [])
                : cell.unmatched;
              const showEmpty = filteredMatched.length === 0 && filteredUnmatched.length === 0;
              return (
                <div key={d.id + sIdx} className={`sched-cell ${cellClass(cell)}`}>
                  {showEmpty && <div className="sched-empty">—</div>}
                  {filteredMatched.map(m => {
                    const hl = isHighlighted(m);
                    return (
                      <PairChipL
                        key={m.clientId}
                        clientId={m.clientId}
                        therapistId={m.therapistId}
                        highlight={hl}
                        dimmed={highlightId && !hl && !filterMode}
                        onClick={() => onJumpToTherapist(m.therapistId)}
                      />
                    );
                  })}
                  {filteredUnmatched.map(cid => {
                    const hl = highlightKind === 'client' && cid === highlightId;
                    return (
                      <PairChipL
                        key={'u' + cid}
                        clientId={cid}
                        therapistId={null}
                        unmatched
                        highlight={hl}
                        dimmed={highlightId && !hl && !filterMode}
                        onClick={() => onJumpToClient(cid)}
                      />
                    );
                  })}
                </div>
              );
            })}
          </React.Fragment>
        ))}
      </div>
      <div className="legend-row">
        <span className="legend-item"><span className="legend-swatch empty"></span>No sessions</span>
        <span className="legend-item"><span className="legend-swatch partial"></span>Partially matched</span>
        <span className="legend-item"><span className="legend-swatch full"></span>Fully matched</span>
        <span className="legend-item"><span className="legend-pill">AP+AR</span>Client + therapist pair</span>
        <span className="legend-item"><span className="legend-pill unmatched">AP+?</span>Client unmatched</span>
        {highlightId && <span className="legend-item"><span className="legend-pill highlight">AP+AR</span>Selected {highlightKind}</span>}
      </div>
    </div>
  );
}

function PairChipL({ clientId, therapistId, unmatched, highlight, dimmed, onClick }) {
  const c = window.FS_DATA.getClient(clientId);
  const t = therapistId ? window.FS_DATA.getTherapist(therapistId) : null;
  const cls = `sched-pair ${unmatched ? 'unmatched' : ''} ${highlight ? 'highlight' : ''} ${dimmed ? 'dimmed' : ''}`;
  return (
    <div
      className={cls}
      onClick={onClick}
      title={unmatched ? `${c.name} — no therapist matched` : `${c.name} with ${t.name}`}
    >
      <span style={{fontWeight: 700}}>{c.short}</span>
      <span className="pair-arrow">+</span>
      <span style={{fontWeight: unmatched ? 700 : 600}}>{t ? t.short : '?'}</span>
    </div>
  );
}

function MetricsRow({ metrics, hints, showHints }) {
  const therapistHints = hints.filter(h => h.whoType === 'therapist');
  const clientHints = hints.filter(h => h.whoType === 'client');
  return (
    <div className="metrics-bottom-stack">
      <div className="metrics-row-top">
        <MetricMini label="Slot utilization" value={metrics.slotUtil}
          frac={`${metrics.counts.slotsWithMatch}/${metrics.counts.slotsTotal}`} />
        <MetricMini label="Client utilization" value={metrics.clientUtil}
          frac={`${metrics.counts.clientMatched}/${metrics.counts.clientAvailTotal}`} />
        <MetricMini label="Therapist utilization" value={metrics.therapistUtil}
          frac={`${metrics.counts.therapistMatched}/${metrics.counts.therapistAvailTotal}`} />
      </div>
      {showHints && (
        <div className="nego-full">
          <div className="nego-full-head">
            <div className="nego-full-title">Negotiation suggestions ({hints.length})</div>
            <div className="nego-full-legend">
              <span style={{display: 'inline-flex', alignItems: 'center', gap: 4, marginRight: 10}}>
                <span className="nego-tag">T</span> therapist adds
              </span>
              <span style={{display: 'inline-flex', alignItems: 'center', gap: 4}}>
                <span className="nego-tag t-client">C</span> client adds
              </span>
            </div>
          </div>
          {hints.length === 0 ? (
            <div style={{fontSize: 11, color: 'var(--ink-700)', padding: '4px 4px 2px'}}>
              No single-slot addition unlocks more sessions this week — schedule is locally optimal.
            </div>
          ) : (
            <div className="nego-full-list">
              {hints.map((h, i) => (
                <div key={i} className="nego-row" title={`${h.who} adding ${h.dayLabel} ${h.slotLabel} (${h.slotTime}) unlocks ${h.gain} session${h.gain > 1 ? 's' : ''}`}>
                  <div>
                    <span className={`nego-tag ${h.whoType === 'client' ? 't-client' : ''}`}>
                      {h.whoType === 'client' ? 'C' : 'T'}
                    </span>{' '}
                    <span className="nego-who">{h.who}</span>{' '}
                    <span className="nego-when">+ {h.dayLabel} {h.slotLabel}</span>
                  </div>
                  <span style={{fontSize: 11, fontWeight: 700, color: 'var(--green-700)'}}>+{h.gain}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function MetricMini({ label, value, frac }) {
  const pct = Math.round(value * 100);
  return (
    <div className="metric-mini-card">
      <div className="metric-mini-head">
        <span className="metric-mini-label">{label}</span>
        <span className="metric-mini-frac">{frac}</span>
      </div>
      <div className="metric-mini-row">
        <span className="metric-mini-value">{pct}%</span>
        <div className="metric-mini-bar">
          <div className="metric-mini-bar-fill" style={{ width: `${pct}%` }} />
        </div>
      </div>
    </div>
  );
}

window.SchedulePreview = SchedulePreview;
window.MetricsRow = MetricsRow;
