import { writable } from "svelte/store";
import { listen } from "@tauri-apps/api/event";

export interface TodoItem {
  content: string;
  status: "pending" | "in_progress" | "completed";
  activeForm: string;
}

interface TodoUpdatePayload {
  todos: TodoItem[];
  conversation_id?: string;
}

// Create the writable store
const { subscribe, set, update } = writable<TodoItem[]>([]);

// Listen for todo updates from the backend
let unlisten: (() => void) | undefined;

export async function initializeTodoListener(): Promise<void> {
  if (unlisten) {
    return; // Already initialized
  }

  unlisten = await listen<TodoUpdatePayload>("claude:todo-update", (event) => {
    set(event.payload.todos);
  });
}

export function cleanupTodoListener(): void {
  if (unlisten) {
    unlisten();
    unlisten = undefined;
  }
}

// Export the store
export const todos = {
  subscribe,
  set,
  update,
  clear: () => set([]),
};
