import { defineStore } from "pinia";
import { toRaw } from "vue";

const STORAGE_KEY = "vue-todos";

export const useTodoStore = defineStore("todoStore", {
  state: () => ({
    todos: JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]"),
    tabType: 0, // 0全部 1未完成 2已完成
  }),

  getters: {
    leftCount(state) {
      return state.todos.filter((t) => !t.completed).length;
    },
  },

  actions: {
    save() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(toRaw(this.todos)));
    },

    setTab(type) {
      this.tabType = type;
    },

    addTodo(txt) {
      const newTodo = {
        id: Date.now(),
        txt,
        completed: false,
      };
      this.todos.push(newTodo);
      this.save();
      console.log("Added:", newTodo);
      console.log("Current todos:", toRaw(this.todos));
    },

    delTodo(item) {
      this.todos = this.todos.filter((t) => t.id !== item.id);
      this.save();
      console.log("Deleted:", item);
      console.log("Current todos:", toRaw(this.todos));
    },

    editTodo({ item, text }) {
      const t = this.todos.find((t) => t.id === item.id);
      if (t) {
        t.txt = text;
        this.save();
        console.log("Edited:", item.id, "=>", text);
        console.log("Current todos:", toRaw(this.todos));
      }
    },

    moveTodo(oldIndex, newIndex) {
      if (oldIndex === newIndex) return;

      const arr = this.todos;
      const moved = arr.splice(oldIndex, 1)[0];
      arr.splice(newIndex, 0, moved);

      this.save();
      console.log(`Move: ${oldIndex} → ${newIndex}`);
      console.log("Current todos:", toRaw(this.todos));
    },

    toggle(item) {
      const t = this.todos.find(t => t.id === item.id);
      if (t) {
        t.completed = !t.completed;
        this.save();
        console.log("Toggled:", t);
      }
    },

    clearCompleted() {
      this.todos = this.todos.filter((t) => !t.completed);
      this.save();
      console.log("Clear completed");
      console.log("Current todos:", toRaw(this.todos));
    },
  },
});
