// stores/page.js
import { defineStore } from "pinia";
import { tiptapToBlocks, blocksToTiptap } from "@/utils/tiptapMapper";

export const usePageStore = defineStore("page", {
  state: () => ({
    blocks: [],
    currentPageId: null,
    pages: [],
    _hydrated: false,
  }),

  getters: {
    getBlocks: (state) => state.blocks,
    getPageById: (state) => (id) => {
      return state.pages.find((page) => page.id === id);
    },
    isHydrated: (state) => state._hydrated,
  },

  actions: {
    updateFromEditor(editor) {
      this.blocks = tiptapToBlocks(editor.getJSON());
      this.saveToLocalStorage();
    },

    setBlocks(blocks) {
      this.blocks = blocks;
    },

    addBlock(block) {
      this.blocks.push({
        ...block,
        id: Date.now().toString(),
        createdAt: new Date().toISOString(),
      });
      this.saveToLocalStorage();
    },

    removeBlock(blockId) {
      this.blocks = this.blocks.filter((block) => block.id !== blockId);
      this.saveToLocalStorage();
    },

    updateBlock(blockId, updates) {
      const index = this.blocks.findIndex((block) => block.id === blockId);
      if (index !== -1) {
        this.blocks[index] = { ...this.blocks[index], ...updates };
        this.saveToLocalStorage();
      }
    },

    saveToLocalStorage() {
      // فقط در کلاینت اجرا شود
      if (typeof window !== "undefined" && window.localStorage) {
        try {
          localStorage.setItem(
            "notion-pages",
            JSON.stringify({
              blocks: this.blocks,
              pages: this.pages,
              currentPageId: this.currentPageId,
              lastSaved: new Date().toISOString(),
            })
          );
        } catch (error) {
          console.warn("خطا در ذخیره localStorage:", error);
        }
      }
    },

    loadFromLocalStorage() {
      // فقط در کلاینت اجرا شود
      if (typeof window !== "undefined" && window.localStorage) {
        try {
          const saved = localStorage.getItem("notion-pages");
          if (saved) {
            const data = JSON.parse(saved);
            this.blocks = data.blocks || [];
            this.pages = data.pages || [];
            this.currentPageId = data.currentPageId || null;
            this._hydrated = true;
          }
        } catch (error) {
          console.warn("خطا در بارگذاری localStorage:", error);
        }
      }
    },

    createPage(title) {
      const newPage = {
        id: Date.now().toString(),
        title: title || "صفحه جدید",
        blocks: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      this.pages.push(newPage);
      this.saveToLocalStorage();
      return newPage;
    },

    switchPage(pageId) {
      const page = this.getPageById(pageId);
      if (page) {
        this.currentPageId = pageId;
        this.blocks = page.blocks;
        this.saveToLocalStorage();
      }
    },

    saveCurrentPage() {
      if (this.currentPageId) {
        const pageIndex = this.pages.findIndex(
          (p) => p.id === this.currentPageId
        );
        if (pageIndex !== -1) {
          this.pages[pageIndex].blocks = this.blocks;
          this.pages[pageIndex].updatedAt = new Date().toISOString();
          this.saveToLocalStorage();
        }
      }
    },

    clearAllData() {
      this.blocks = [];
      this.pages = [];
      this.currentPageId = null;
      if (typeof window !== "undefined" && window.localStorage) {
        localStorage.removeItem("notion-pages");
      }
    },
  },
});
