// Behavior finder — pills for prompt categories with a tiny inline curve.

const { useMemo: useMemoBF } = React;

function BehaviorFinder({ activeBehavior, onSelect, perBehaviorPeak }) {
  return (
    <div className="bf">
      <div className="bf-head">
        <div className="bf-eyebrow">Behavior finder</div>
        <div className="bf-sub">Where does this live in the brain?</div>
      </div>
      <div className="bf-grid">
        {AtlasData.BEHAVIORS.map(b => {
          const active = activeBehavior === b.id;
          const peak = perBehaviorPeak[b.id];
          return (
            <button
              key={b.id}
              className={"bf-pill" + (active ? ' is-active' : '')}
              onClick={() => onSelect(active ? null : b.id)}
              title={(b.samplePrompts || []).slice(0, 3).join('\n• ')}
            >
              <span className="bf-glyph">{b.glyph}</span>
              <span className="bf-label">{b.label}</span>
              <span className="bf-peak">
                {b.count ? `${b.count} prompts` : (peak ? `peak L${peak.layer}` : '')}
              </span>
              <MiniCurve behaviorId={b.id} active={active} />
            </button>
          );
        })}
      </div>
      <div className="bf-foot">
        <span className="muted">
          {activeBehavior
            ? <>Overlay active — heatmap weighted toward <b>{AtlasData.BEHAVIORS.find(x => x.id === activeBehavior)?.label}</b>.</>
            : <>{(AtlasData.BEHAVIORS || []).length} categories from the probe set · per-behavior cell-level fits coming in v0.4.</>}
        </span>
        {activeBehavior && (
          <button className="link-btn" onClick={() => onSelect(null)}>clear overlay</button>
        )}
      </div>
    </div>
  );
}

function MiniCurve({ behaviorId, active }) {
  const pts = useMemoBF(() => {
    const m = AtlasData.BEHAVIOR_MATRICES[behaviorId];
    if (!m) return [];
    return m.map(row => {
      const valid = row.filter(v => Number.isFinite(v));
      if (!valid.length) return 0;
      return valid.reduce((a, b) => a + b, 0) / valid.length;
    });
  }, [behaviorId]);
  if (!pts.length) return null;
  const max = Math.max(...pts, 0.01);
  const W = 120, H = 22;
  const path = pts.map((v, i) => {
    const x = (i / Math.max(1, pts.length - 1)) * W;
    const y = H - (v / max) * (H - 2) - 1;
    return (i === 0 ? 'M' : 'L') + x.toFixed(1) + ' ' + y.toFixed(1);
  }).join(' ');
  const fillPath = path + ` L${W} ${H} L0 ${H} Z`;
  return (
    <svg className="bf-curve" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
      <path d={fillPath} className={"bf-curve-fill" + (active ? ' is-active' : '')} />
      <path d={path}     className={"bf-curve-line" + (active ? ' is-active' : '')} />
    </svg>
  );
}

window.BehaviorFinder = BehaviorFinder;
