import { useEffect, useRef } from "react";

export default function Terminal({ title, lines, tall = false, onClear }) {
  const scrollRef = useRef(null);

  useEffect(() => {
    if (!scrollRef.current) return;
    scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [lines.length]);

  const levelClass = {
    debug: "terminal-line-debug",
    info: "terminal-line-info",
    error: "terminal-line-error",
    think: "terminal-line-think",
    warning: "terminal-line-warning",
    waring: "terminal-line-warning",
  };

  const levelLabel = {
    debug: "调试",
    error: "错误",
    info: "日志",
    think: "思考",
    warning: "警告",
    waring: "警告",
  };

  return (
    <div className={`terminal ${tall ? "min-h-[520px] basis-[650px]" : "min-h-[220px] basis-[250px]"} flex flex-1 flex-col`}>
      <div className="mb-3 flex shrink-0 items-center justify-between">
        <h3 className="text-[13px] font-black text-[#d7ffe4]">{title}</h3>
        <button className="cursor-pointer border-0 bg-transparent p-0 text-[11px] font-bold text-[#7ea58b]" onClick={onClear}>清理日志</button>
      </div>
      <div ref={scrollRef} className="scrollbar-hidden relative min-h-0 flex-1 overflow-y-auto font-mono text-[12px] leading-5">
        {lines.length ? (
          <div className="space-y-2">
            {lines.map((line, index) => {
              const level = typeof line === "string" ? "info" : line.level;
              const message = typeof line === "string" ? line : line.message;
              const timestamp = typeof line === "string" ? null : line.timestamp;

              return (
                <p key={`${timestamp ?? ""}-${message}-${index}`} className="text-[#d7ffe4]">
                  {timestamp ? <span className="text-[#6f8978]">{timestamp} </span> : null}
                  <span className={levelClass[level] ?? levelClass.info}>[{levelLabel[level] ?? level}] </span>
                  {message}
                </p>
              );
            })}
          </div>
        ) : (
          <div className="absolute inset-0 grid place-items-center">
            <p className="text-[16px] font-medium tracking-[0.18em] text-[#d7ffe4]">引擎未启动</p>
          </div>
        )}
      </div>
    </div>
  );
}
