import { useEffect, useRef } from "preact/hooks";
import type { ThreadData } from "../../lib/types";
import { useSessionLog } from "../../lib/use-session-log";
import { fmtSessTs, typeClass, formatTypeLabel } from "../../lib/format";

interface Props {
  thread: ThreadData;
  open: boolean;
  onToggle: () => void;
}

export default function LogPanel({ thread, open, onToggle }: Props) {
  const isActive = thread.status === "processing";
  const { entries, loading } = useSessionLog(thread.sessionFile, open, isActive);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (open && containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [entries, open]);

  const hasSession = !!thread.sessionFile;

  return (
    <>
      <button class="log-toggle" onClick={onToggle}>
        {open ? "hide log" : "show log"}
      </button>
      <div
        ref={containerRef}
        class={`log-tail${open ? " open" : ""}`}
        style="white-space: normal"
      >
        {open && hasSession && loading && (
          <div class="sess-loading">Loading session log...</div>
        )}
        {open && hasSession && !loading && entries.length === 0 && (
          <div class="sess-none">No session log entries found.</div>
        )}
        {open && hasSession && entries.map((e, i) => {
          const content = e.type === "TOOL RESULT" && e.content.length > 120
            ? e.content.slice(0, 120) + "..."
            : e.content;
          return (
            <div class="sess-row" key={i}>
              <span class="sess-ts">{fmtSessTs(e.ts)}</span>
              <span class={`sess-type ${typeClass(e.type)}`}>{formatTypeLabel(e.type)}</span>
              <span class="sess-content" title={e.content}>{content}</span>
            </div>
          );
        })}
        {open && !hasSession && (
          thread.logLines.map((l, i) => <div key={i}>{l}</div>)
        )}
      </div>
    </>
  );
}
