// frontend\src\components\ui\TaskList.tsx

'use client'

export type TaskItem = {
  id: string
  status: 'idle' | 'running' | 'done' | 'error' | 'cancelled'
  title: string
  text?: string
  done?: number
  total?: number
  err?: string
  cancellable?: boolean   // zeigt X nur wenn true
  fading?: boolean        // für sanftes Ausblenden
}

type Props = {
  tasks: TaskItem[]
  onCancel?: (id: string) => void
}

function pct(done?: number, total?: number) {
  const d = Number(done ?? 0)
  const t = Number(total ?? 0)
  if (!t || t <= 0) return 0
  return Math.max(0, Math.min(100, Math.round((d / t) * 100)))
}

export default function TaskList({ tasks, onCancel }: Props) {
  const visible = (tasks || []).filter((t) => t.status !== 'idle')

  return (
    <div className="rounded-2xl border border-gray-200 bg-white p-4 shadow-sm dark:border-white/10 dark:bg-gray-950/40">
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="text-sm font-semibold text-gray-900 dark:text-white">Hintergrundaufgaben</div>
          <div className="mt-1 text-xs text-gray-600 dark:text-gray-300">
            Laufende Hintergrundaufgaben (z.B. Assets/Previews).
          </div>
        </div>
      </div>

      <div className="mt-3 space-y-3">
        {visible.length === 0 ? (
          <div className="rounded-xl border border-gray-200 bg-white px-3 py-2 text-sm text-gray-600 dark:border-white/10 dark:bg-white/5 dark:text-gray-300">
            Keine laufenden Aufgaben.
          </div>
        ) : null}

        {visible.map((t) => {
          const p = pct(t.done, t.total)
          const isRunning = t.status === 'running'
          const hasProgress = isRunning && (t.total ?? 0) > 0
          const title = (t.title ?? '').trim()
          const suffix = (t.text ?? '').trim()

          return (
            <div
              key={t.id}
              className={
                "rounded-xl border border-gray-200 bg-white px-3 py-2 dark:border-white/10 dark:bg-white/5 " +
                "transition-opacity duration-500 " +
                (t.fading ? "opacity-0" : "opacity-100")
              }
            >
              <div className="flex items-center gap-3">
                {/* Left icon: Cancel X (running+cancellable) OR green check (done) */}
                <div className="shrink-0">
                  {isRunning && t.cancellable && onCancel ? (
                    <button
                      type="button"
                      onClick={() => onCancel?.(t.id)}
                      className="inline-flex h-7 w-7 items-center justify-center rounded-md
                                text-red-700 hover:bg-red-50 hover:text-red-900
                                dark:text-red-300 dark:hover:bg-red-500/10 dark:hover:text-red-200"
                      title="Abbrechen"
                      aria-label="Task abbrechen"
                    >
                      ✕
                    </button>
                  ) : t.status === 'done' ? (
                    <span
                      className="inline-flex h-7 w-7 items-center justify-center rounded-md text-green-700 dark:text-green-300"
                      title="Fertig"
                      aria-label="Fertig"
                    >
                      ✓
                    </span>
                  ) : (
                    <span className="inline-block h-7 w-7" />
                  )}
                </div>

                {/* One-line row: title (optional) + status + progress */}
                <div className="min-w-0 flex-1 flex items-center gap-2">
                  <div className="min-w-0 truncate text-sm font-semibold text-gray-900 dark:text-white">
                    {title || 'Aufgabe'}
                    {suffix ? (
                      <span className="font-normal text-gray-600 dark:text-gray-300">
                        {' · '}{suffix}
                      </span>
                    ) : null}
                  </div>

                  {/* Status badge (running bewusst ohne Badge) */}
                  {t.status === 'done' ? (
                    <span className="shrink-0 inline-flex items-center rounded-full bg-green-100 px-2 py-0.5 text-[11px] font-semibold text-green-800 ring-1 ring-inset ring-green-200 dark:bg-green-500/20 dark:text-green-200 dark:ring-green-400/30">
                      fertig
                    </span>
                  ) : t.status === 'cancelled' ? (
                    <span className="shrink-0 inline-flex items-center rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-semibold text-gray-700 ring-1 ring-inset ring-gray-200 dark:bg-white/10 dark:text-gray-200 dark:ring-white/10">
                      abgebrochen
                    </span>
                  ) : t.status === 'error' ? (
                    <span className="shrink-0 inline-flex items-center rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-semibold text-red-800 ring-1 ring-inset ring-red-200 dark:bg-red-500/20 dark:text-red-200 dark:ring-red-400/30">
                      fehler
                    </span>
                  ) : null}

                  {/* Spacer */}
                  <div className="flex-1" />

                  {/* Progress compact on same line */}
                  {hasProgress ? (
                    <div className="shrink-0 flex items-center gap-3 text-xs text-gray-600 dark:text-gray-300">
                      <span className="tabular-nums">{t.done ?? 0}/{t.total ?? 0}</span>
                      <span className="tabular-nums">{p}%</span>

                      {/* Progressbar: auf Mobile ausblenden, ab sm anzeigen */}
                      <div className="hidden sm:block h-2 w-40 overflow-hidden rounded-full bg-gray-200 dark:bg-white/10">
                        <div className="h-full bg-indigo-500" style={{ width: `${p}%` }} />
                      </div>
                    </div>
                  ) : null}
                </div>
              </div>

              {/* Error text optional (unter der Zeile) */}
              {t.status === 'error' && t.err ? (
                <div className="mt-2 text-xs text-red-700 dark:text-red-200">
                  {t.err}
                </div>
              ) : null}
            </div>
          )
        })}
      </div>
    </div>
  )
}
