import { useTranslation } from 'react-i18next';
import type { LocalTask } from '../../api';

interface RailPanelProps {
  tasks: LocalTask[];
  activeTaskId: number | null;
  onSelectTask: (id: number) => void;
  onOpenCreate: () => void;
  onExitFocused: () => void;
}

function statusDotClass(status: string | undefined): string {
  switch (status) {
    case 'running':
    case 'dispatching':
      return 'bg-accent animate-pulse';
    case 'queued':
    case 'retry':
      return 'bg-slate-400';
    case 'failed':
    case 'cancelled':
      return 'bg-red-500';
    case 'succeeded':
      return 'bg-green-500';
    case 'waiting_human':
    case 'waiting_subtasks':
      return 'bg-amber-500';
    default:
      return 'bg-slate-300';
  }
}

export function RailPanel({
  tasks,
  activeTaskId,
  onSelectTask,
  onOpenCreate,
  onExitFocused,
}: RailPanelProps) {
  const { t } = useTranslation('list');
  // bg/border は App.tsx の grid cell 側に持たせる (list mode と同じ責務分割)。
  return (
    <div className="flex flex-col h-full overflow-hidden">
      <button
        onClick={onOpenCreate}
        title={t('newTask')}
        aria-label={t('newTask')}
        className="flex-shrink-0 flex items-center justify-center h-10 border-b border-hairline hover:bg-surface transition-colors text-slate-600"
      >
        <svg className="w-4 h-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
          <path d="M8 3v10M3 8h10" />
        </svg>
      </button>
      <div className="flex-1 min-h-0 overflow-y-auto">
        {tasks.map(task => {
          const status = task.latestJob?.status;
          const isActive = task.id === activeTaskId;
          const idLabel = String(task.id).slice(-2);
          return (
            <button
              key={task.id}
              onClick={() => onSelectTask(task.id)}
              title={task.title || `Task #${task.id}`}
              className={`relative w-full flex items-center justify-center h-10 border-b border-hairline transition-colors ${
                isActive
                  ? 'bg-accent/10 text-accent ring-1 ring-inset ring-accent/40'
                  : 'text-slate-600 hover:bg-surface'
              }`}
            >
              <span className={`absolute top-1 left-1 w-2 h-2 rounded-full ${statusDotClass(status)}`} />
              <span className="font-mono text-[11px]">{idLabel}</span>
            </button>
          );
        })}
      </div>
      <button
        onClick={onExitFocused}
        title={t('backToList')}
        aria-label={t('backToList')}
        className="flex-shrink-0 flex items-center justify-center h-10 border-t border-hairline hover:bg-surface transition-colors text-slate-500"
      >
        <svg className="w-4 h-4" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
          <path d="M3 6l5 5 5-5" />
        </svg>
      </button>
    </div>
  );
}
