/**
 * taskStore — 任务 id / 状态 / 已选文案和图 id
 * 按契约 TaskListItem + TaskStatus
 */
import { create } from 'zustand';
import { TaskListItem, TaskStatus } from '@/types/index';

interface TaskState {
  currentTaskId: number | null;
  currentStatus: TaskStatus | null;
  recentTasks: TaskListItem[];

  // 已选候选（按契约 candidate_id 传给后端）
  selectedTextIds: number[];
  selectedImageIds: number[];

  setCurrentTask: (id: number, status: TaskStatus) => void;
  updateStatus: (status: TaskStatus) => void;
  setRecentTasks: (tasks: TaskListItem[]) => void;
  toggleTextSelection: (candidateId: number) => void;
  toggleImageSelection: (candidateId: number) => void;
  clearSelections: () => void;
  reset: () => void;
}

export const useTaskStore = create<TaskState>((set) => ({
  currentTaskId: null,
  currentStatus: null,
  recentTasks: [],
  selectedTextIds: [],
  selectedImageIds: [],

  setCurrentTask(id, status) {
    set({ currentTaskId: id, currentStatus: status });
  },

  updateStatus(status) {
    set({ currentStatus: status });
  },

  setRecentTasks(tasks) {
    set({ recentTasks: tasks });
  },

  toggleTextSelection(candidateId) {
    set((s) => ({
      selectedTextIds: s.selectedTextIds.includes(candidateId)
        ? s.selectedTextIds.filter((id) => id !== candidateId)
        : [...s.selectedTextIds, candidateId],
    }));
  },

  toggleImageSelection(candidateId) {
    set((s) => ({
      selectedImageIds: s.selectedImageIds.includes(candidateId)
        ? s.selectedImageIds.filter((id) => id !== candidateId)
        : [...s.selectedImageIds, candidateId],
    }));
  },

  clearSelections() {
    set({ selectedTextIds: [], selectedImageIds: [] });
  },

  reset() {
    set({
      currentTaskId: null,
      currentStatus: null,
      selectedTextIds: [],
      selectedImageIds: [],
    });
  },
}));
