"use client";

export interface MessageQueue {
  steering: string[];
  followUp: string[];
}

interface Props {
  queue: MessageQueue;
  onClear: () => void;
  disabled?: boolean;
}

function previewLine(text: string, max = 48): string {
  const one = text.replace(/\s+/g, " ").trim();
  if (one.length <= max) return one;
  return one.slice(0, max) + "…";
}

/**
 * Shows pending steer / follow-up messages while the agent is running.
 * Clear restores texts to the editor (handled by parent via onClear).
 */
export function QueueBar({ queue, onClear, disabled }: Props) {
  const steerCount = queue.steering.length;
  const followCount = queue.followUp.length;
  if (steerCount === 0 && followCount === 0) return null;

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        gap: 6,
        padding: "8px 12px",
        marginBottom: 6,
        borderRadius: "var(--radius-lg, 10px)",
        border: "1px solid var(--border)",
        background: "var(--bg-panel)",
        fontSize: 12,
      }}
    >
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
        <span style={{ color: "var(--text-muted)", fontWeight: 600, letterSpacing: "0.02em" }}>
          排队中
          {steerCount > 0 && (
            <span style={{ marginLeft: 8, color: "var(--warning)" }}>Steer ×{steerCount}</span>
          )}
          {followCount > 0 && (
            <span style={{ marginLeft: 8, color: "var(--accent)" }}>Follow-up ×{followCount}</span>
          )}
        </span>
        <button
          type="button"
          onClick={onClear}
          disabled={disabled}
          title="清空队列并回填到输入框"
          style={{
            border: "1px solid var(--border)",
            background: "transparent",
            color: "var(--text-muted)",
            borderRadius: 6,
            padding: "2px 8px",
            fontSize: 11,
            cursor: disabled ? "not-allowed" : "pointer",
            opacity: disabled ? 0.5 : 1,
          }}
        >
          取回
        </button>
      </div>

      {steerCount > 0 && (
        <ul style={{ margin: 0, padding: "0 0 0 14px", color: "var(--warning)" }}>
          {queue.steering.map((msg, i) => (
            <li key={`s-${i}`} style={{ marginBottom: 2 }}>
              <span style={{ color: "var(--text-dim)", marginRight: 6 }}>S{i + 1}</span>
              {previewLine(msg)}
            </li>
          ))}
        </ul>
      )}

      {followCount > 0 && (
        <ul style={{ margin: 0, padding: "0 0 0 14px", color: "var(--accent)" }}>
          {queue.followUp.map((msg, i) => (
            <li key={`f-${i}`} style={{ marginBottom: 2 }}>
              <span style={{ color: "var(--text-dim)", marginRight: 6 }}>F{i + 1}</span>
              {previewLine(msg)}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
