// timeline.jsx — LLM Timeline experimental UX
// 시간 + 종류 아이콘 + 펼치는 본문, 도구 호출은 args/result, 명령은 입력/출력

const { useState: useTLState, useMemo: useTLMemo } = React;

function timeBetween(prev, cur) {
  if (!prev) return null;
  const ms = +cur - +prev;
  if (ms < 1000) return `+${ms}ms`;
  return `+${(ms / 1000).toFixed(1)}s`;
}

function TimelineRow({ ev, prev, idx, total, filter, openMap, onToggle, live }) {
  if (filter === 'tool' && ev.kind !== 'tool' && ev.kind !== 'cmd') return null;
  if (filter === 'message' && ev.kind === 'tool') return null;
  if (filter === 'thought' && ev.kind !== 'thought') return null;

  const open = !!openMap[ev.id];
  const isLive = live && idx === total - 1;
  const glyph = {
    message: '💬',
    tool: '⚙',
    cmd: '$_',
    thought: '·',
    decision: '✓',
  }[ev.kind];
  const tagLabel = {
    message: 'MSG',
    tool: 'TOOL',
    cmd: 'CMD',
    thought: 'THINK',
    decision: 'FINAL',
  }[ev.kind];

  const delta = timeBetween(prev?.t, ev.t);

  return (
    <div className={cx('tl-row', `tl-${ev.kind}`, isLive && 'live')}>
      <div className="tl-rail" />
      <div className="tl-time">
        {fmtTimeFull(ev.t)}
        {delta && <span className="tl-time-delta">{delta}</span>}
      </div>
      <div className={cx('tl-glyph', `kind-${ev.kind}`)}>
        <div className="tl-glyph-inner mono">{glyph}</div>
      </div>
      <div className="tl-body">
        <div
          className={cx('tl-body-summary', open && 'open', `tl-kind-${ev.kind}`)}
          onClick={() => onToggle(ev.id)}
        >
          <div className="tl-line1">
            <span className="tl-kind-tag">{tagLabel}</span>
            {ev.kind === 'tool' && <span className="mono" style={{ fontSize: 11.5, color: 'var(--accent)' }}>{ev.tool}</span>}
            {ev.kind === 'decision' && <span className="mono" style={{ fontSize: 11.5, color: 'var(--accent)', fontWeight: 600 }}>cycle_complete</span>}
            <div className="tl-summary">{ev.summary}</div>
          </div>
          {(ev.durationMs != null) && (
            <div className="tl-foot">
              <span className="dur">{ev.durationMs}ms</span>
            </div>
          )}
        </div>

        {open && (ev.kind === 'tool' || ev.kind === 'cmd') && (
          <div className="tl-body-detail">
            {ev.kind === 'tool' && (
              <div className="tl-pair">
                <div>
                  <div className="tl-pair-label">args</div>
                  <JSONViewer data={ev.args} />
                </div>
                <div>
                  <div className="tl-pair-label">result</div>
                  <JSONViewer data={ev.result} />
                </div>
              </div>
            )}
            {ev.kind === 'cmd' && (
              <div className="tl-pair">
                <div>
                  <div className="tl-pair-label">command</div>
                  <div className="tl-cmd-block input">{ev.cmd}</div>
                </div>
                <div>
                  <div className="tl-pair-label">output</div>
                  <div className="tl-cmd-block output">{ev.output}</div>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function LLMTimeline({ events, live = false }) {
  const [filter, setFilter] = useTLState('all');
  const [openMap, setOpenMap] = useTLState({});
  const [expandAll, setExpandAll] = useTLState(false);

  const filtered = events;

  const counts = useTLMemo(() => {
    const c = { all: events.length, tool: 0, message: 0, thought: 0 };
    for (const e of events) {
      if (e.kind === 'tool' || e.kind === 'cmd') c.tool++;
      else if (e.kind === 'message' || e.kind === 'decision') c.message++;
      else if (e.kind === 'thought') c.thought++;
    }
    return c;
  }, [events]);

  const onToggle = (id) => setOpenMap(m => ({ ...m, [id]: !m[id] }));
  const onToggleAll = () => {
    const next = !expandAll;
    setExpandAll(next);
    if (next) {
      const m = {};
      for (const e of events) if (e.kind === 'tool' || e.kind === 'cmd') m[e.id] = true;
      setOpenMap(m);
    } else {
      setOpenMap({});
    }
  };

  const totalDuration = events.reduce((a, e) => a + (e.durationMs || 0), 0);
  const toolCount = events.filter(e => e.kind === 'tool' || e.kind === 'cmd').length;

  return (
    <div>
      <div className="timeline-toolbar">
        <div className="timeline-toolbar-info">
          <span className="mono" style={{ color: 'var(--text-2)' }}>{events.length}</span>개 이벤트
          <span style={{ color: 'var(--text-4)' }}>·</span>
          <span className="mono">{toolCount}</span>회 도구
          <span style={{ color: 'var(--text-4)' }}>·</span>
          <span className="mono">{(totalDuration / 1000).toFixed(1)}s</span> 실행
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <Segmented
            size="sm"
            value={filter}
            onChange={setFilter}
            options={[
              { value: 'all',     label: `전체 ${counts.all}` },
              { value: 'tool',    label: `도구 ${counts.tool}` },
              { value: 'message', label: `발화 ${counts.message}` },
              { value: 'thought', label: `사고 ${counts.thought}` },
            ]}
          />
          <button className="subtle-link" onClick={onToggleAll}>
            {expandAll ? '모두 접기' : '모두 펼치기'}
          </button>
        </div>
      </div>
      <div className="timeline">
        {filtered.map((ev, i) => {
          if (filter === 'tool' && ev.kind !== 'tool' && ev.kind !== 'cmd') return null;
          if (filter === 'message' && ev.kind !== 'message' && ev.kind !== 'decision') return null;
          if (filter === 'thought' && ev.kind !== 'thought') return null;
          return (
            <TimelineRow
              key={ev.id}
              ev={ev}
              prev={filtered[i - 1]}
              idx={i}
              total={filtered.length}
              filter={filter}
              openMap={openMap}
              onToggle={onToggle}
              live={live}
            />
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { LLMTimeline, TimelineRow });
