interface StorageMessage {
  type: "setStorage" | "getStorage" | "removeStorage";
  key: string;
  value?: any;
}

// 统一的发送消息函数
const sendMessageToFigma = (type: string, data?: any) => {
  parent.postMessage({ pluginMessage: { type, ...data } }, '*');
};

export const storage = {
  set: async (key: string, value: any) => {
    try {
      return new Promise((resolve, reject) => {
        const messageHandler = (event: MessageEvent) => {
          const msg = event.data.pluginMessage;
          if (msg?.type === 'storageSet') {
            window.removeEventListener('message', messageHandler);
            if (msg.success) {
              resolve(true);
            } else {
              reject(msg.error);
            }
          }
        };
        window.addEventListener('message', messageHandler);
        
        // 发送设置存储的消息
        sendMessageToFigma('setStorage', { key, value });
      });
    } catch (error) {
      console.log(error, '222222');
    }
  },

  get: async (key: string) => {    
    return new Promise((resolve, reject) => {
      try {
        const messageHandler = (event: MessageEvent) => {
          const msg = event.data.pluginMessage;
          if (msg?.type === 'storageGet') {
            window.removeEventListener('message', messageHandler);
            if (msg.value !== undefined) {
              resolve(msg.value);
            } else {
              reject(msg.error);
            }
          }
        };
        window.addEventListener('message', messageHandler);
        
        // 发送获取存储的消息
        sendMessageToFigma('getStorage', { key });
      } catch (error) {
        reject(null);
        console.log(error, 'getgetgetget4444');
      }
    });
  },

  remove: async (key: string) => {
    try {
      return new Promise((resolve, reject) => {
        const messageHandler = (event: MessageEvent) => {
          const msg = event.data.pluginMessage;
          if (msg?.type === 'storageRemoved') {
            window.removeEventListener('message', messageHandler);
            if (msg.success) {
              resolve(true);
            } else {
              reject(msg.error);
            }
          }
        };
        window.addEventListener('message', messageHandler);
        
        // 发送删除存储的消息
        sendMessageToFigma('removeStorage', { key });
      });
    } catch (error) {
      console.error('Failed to remove storage:', error);
    }
  },
};