import { API_BASE_URL } from "../config/api";

const AVATAR_CACHE_BUST_KEY = "avatarCacheBust";

const getAvatarCacheBustValue = (): string => {
  return localStorage.getItem(AVATAR_CACHE_BUST_KEY) || "";
};

export const bumpAvatarCacheBust = (): string => {
  const value = Date.now().toString();
  localStorage.setItem(AVATAR_CACHE_BUST_KEY, value);
  return value;
};

// Get token from localStorage
export const getAuthToken = (): string | null => {
  const accessToken = localStorage.getItem("accessToken");
  if (accessToken) return accessToken;
  return localStorage.getItem("authToken");
};

// Get user ID from localStorage
export const getUserId = (): string | null => {
  return localStorage.getItem("userId");
};

// Feed Item Interface from server
export interface FeedItem {
  StageID: number;
  user_id: string;
  person_stage_id: string;
  full_name: string;
  title: string;
  description: string;
  film: string;
  image: string;
  audio: string;
  like_count: number;
  dislike_count: number;
  like_state: "پسند" | "عدم پسند" | "";
  comment_count: number;
  datetimee?: string;
  datetime1?: string;
  create_date?: string;
  workflow_ID?: string; // فیلد workflow_ID برای لایک/دیسلایک (با underscore)
  team_member?: string; // شناسه اعضای تیم با کاما جدا شده
}

// Team Member Interface
export interface TeamMember {
  StageID: number;
  full_name: string;
}

// API Response Interface
interface ApiResponse<T> {
  message: string;
  data: string;
  state: number;
  time: number;
  errorCode: number;
  resultType: number;
}

// Helper function to format error messages
const formatErrorMessage = (result: ApiResponse<any>): string => {
  let errorMessage = result.message || "خطا در عملیات";

  // اگر data هم موجود است و یک متن فارسی است، آن را هم اضافه کن
  if (result.data && typeof result.data === 'string') {
    // بررسی اینکه data شامل کاراکترهای فارسی است
    const hasPersianChars = /[\u0600-\u06FF]/.test(result.data);
    if (hasPersianChars && result.data !== result.message) {
      errorMessage = `${errorMessage}\n${result.data}`;
    }
  }

  return errorMessage;
};

// Parse feed data from API response
const parseFeedData = (data: string): FeedItem[] => {
  try {
    const parsed = JSON.parse(data);
    const feedArray = JSON.parse(parsed.feed || "[]");
    return feedArray;
  } catch (error) {
    console.error("Error parsing feed data:", error);
    return [];
  }
};

// Load feeds function
export const loadFeeds = async (
  missionType: string,
  pageNumber: number = 1,
): Promise<{
  success: boolean;
  data: FeedItem[];
  message?: string;
}> => {
  const token = getAuthToken();

  if (!token) {
    return {
      success: false,
      data: [],
      message: "توکن موجود نیست",
    };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        load_feeds_function: {
          mission_type: missionType,
          page_number: pageNumber.toString(),
        },
      }),
    });

    const result: ApiResponse<any> = await response.json();

    if (result.resultType !== 0) {
      return {
        success: false,
        data: [],
        message: result.message,
      };
    }

    const feedItems = parseFeedData(result.data);
    return { success: true, data: feedItems };
  } catch (error) {
    console.error("Error loading feeds:", error);
    return {
      success: false,
      data: [],
      message: "خطا در بارگذاری فید",
    };
  }
};

// Get image URL for avatar
export const getAvatarUrl = (personStageId: string): string => {
  const token = getAuthToken();
  return `${API_BASE_URL}/api/getimage?stageID=${personStageId}&nameOrID=image&token=${token}`;
};

// Get profile image URL from filename
export const getProfileImageUrl = (filename: string, userStageId: string): string => {
  const token = getAuthToken();
  const version = encodeURIComponent(filename || "image");
  const cacheBust = encodeURIComponent(getAvatarCacheBustValue());
  return `${API_BASE_URL}/api/getimage?stageID=${userStageId}&nameOrID=image&token=${token}&v=${version}&cb=${cacheBust}`;
};

// Get image URL for feed content
export const getFeedImageUrl = (stageID: number): string => {
  const token = getAuthToken();
  return `${API_BASE_URL}/api/getimage?stageID=${stageID}&nameOrID=image&token=${token}`;
};

// Get video file URL
export const getVideoUrl = (stageID: number): string => {
  const token = getAuthToken();
  return `${API_BASE_URL}/api/getFile?stageID=${stageID}&nameOrID=film&token=${token}`;
};

// Get audio file URL
export const getAudioUrl = (stageID: number): string => {
  const token = getAuthToken();
  return `${API_BASE_URL}/api/getFile?stageID=${stageID}&nameOrID=audio&token=${token}`;
};

// Check if feed item belongs to current user
export const isOwnFeed = (feedUserId: string): boolean => {
  const currentUserId = getUserId();
  return currentUserId === feedUserId;
};

// Submit like/dislike for a post (optimistic, no waiting for server response)
export const submitLikeDislike = async (
  kind: "پسند" | "عدم پسند" | "حذف",
  missionType: string,
  missionDoneWorkflowID: string,
): Promise<void> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return;
  }

  try {
    // ارسال درخواست بدون انتظار برای پاسخ (fire and forget)
    fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        like_dislike_function: {
          kind: kind,
          mission_type: missionType,
          mission_done_workflowID: missionDoneWorkflowID,
        },
      }),
    }).catch((error) => {
      console.error("Error submitting like/dislike:", error);
    });
  } catch (error) {
    console.error("Error in submitLikeDislike:", error);
  }
};

// Delete post function (optimistic, no waiting for server response)
export const deletePost = async (
  missionType: string,
  missionDoneWorkflowID: string,
): Promise<void> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return;
  }

  try {
    // ارسال درخواست بدون انتظار برای پاسخ (fire and forget)
    fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        delete_done_mission_function: {
          mission_done_workflowID: missionDoneWorkflowID,
          mission_type: missionType,
        },
      }),
    }).catch((error) => {
      console.error("Error deleting post:", error);
    });
  } catch (error) {
    console.error("Error in deletePost:", error);
  }
};

// Save comment function (optimistic, no waiting for server response)
export const saveComment = async (
  missionType: string,
  missionDoneWorkflowID: string,
  text: string,
  replayWorkflowID: string = "",
): Promise<void> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return;
  }

  try {
    // ارسال درخواست بدون انتظار برای پاسخ (fire and forget)
    fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        save_comment_function: {
          mission_type: missionType,
          mission_done_workflowID: missionDoneWorkflowID,
          text: text,
          replay_workflowID: replayWorkflowID,
        },
      }),
    }).catch((error) => {
      console.error("Error saving comment:", error);
    });
  } catch (error) {
    console.error("Error in saveComment:", error);
  }
};

// Delete comment function
export const deleteComment = async (commentId: string): Promise<boolean> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return false;
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        delete_comment_function: {
          comment_id: commentId,
        },
      }),
    });

    if (!response.ok) {
      console.error("Failed to delete comment");
      return false;
    }

    const result = await response.json();
    return result.state === 0;
  } catch (error) {
    console.error("Error deleting comment:", error);
    return false;
  }
};

// Load comments function with pagination
export interface CommentData {
  StageID: string;
  full_name: string;
  user_stage_id: string;
  comment_text: string;
  datetimee: string;
  comment_id: string;
  parent: string;
}

export interface LoadCommentsResponse {
  comments: CommentData[];
}

export const loadComments = async (
  missionDoneWorkflowID: string,
  pageNumber: number = 1,
): Promise<LoadCommentsResponse> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return { comments: [] };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        load_comments_function: {
          mission_done_workflowID: missionDoneWorkflowID,
          page_number: pageNumber.toString(),
        },
      }),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      const data = JSON.parse(result.data);
      const comments = JSON.parse(data.comments);
      return { comments };
    } else {
      console.error("Error loading comments:", result.message);
      return { comments: [] };
    }
  } catch (error) {
    console.error("Error in loadComments:", error);
    return { comments: [] };
  }
};

// Mission Interface from server
export interface MissionData {
  StageID: number;
  mission_workflowID: string;
  title: string;
  description: string;
  coin_count?: string | number;
  duration?: string | number;
  difficulty?: string;
  }

export interface LoadMissionsResponse {
  missions: MissionData[];
}

// Load missions function
export const loadMissions = async (
  missionType: string,
): Promise<LoadMissionsResponse> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return { missions: [] };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        load_missions_function: {
          mission_type: missionType,
        },
      }),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      const data = JSON.parse(result.data);
      const missions = JSON.parse(data.missions);
      return { missions };
    } else {
      console.error("Error loading missions:", result.message);
      return { missions: [] };
    }
  } catch (error) {
    console.error("Error in loadMissions:", error);
    return { missions: [] };
  }
};

// Get mission image URL
export const getMissionImageUrl = (stageID: number): string => {
  const token = getAuthToken();
  if (!token) {
    console.error("No auth token found for mission image");
    return "";
  }
  return `${API_BASE_URL}/api/getimage?stageID=${stageID}&nameOrID=image&token=${token}`;
};

// Chat Message Interface
export interface ChatMessage {
  question: string;
  answer: string;
  chat_list: string;
  datetime1: string;
  actions?: Array<{ multi_choice?: string[] }>;
  is_mission_end?: boolean;
}

// Doing Mission Interface
export interface DoingMission {
  ID: number;
  StageID: number;
  mission: string;
  user_id: string;
  status: string;
  score: string;
  description: string;
  film: string;
  title: string;
  image: string;
  audio: string;
  workflow_ID: string;
  person_stage_id: string;
  chat_list_stageID: string;
  موبایل?: string; // شماره موبایل ناظر (برای آبخوری)
  کد?: string; // کد تایید ناظر (برای آبخوری)
}

// Start Mission Response Interface
export interface StartMissionResponse {
  doing_mission: DoingMission | null;
  chats: ChatMessage[];
}

// Start mission function
export const startMission = async (
  missionType: string,
  missionId: string,
): Promise<StartMissionResponse> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return { doing_mission: null, chats: [] };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        start_mission_function: {
          mission_type: missionType,
          mission_id: missionId,
        },
      }),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      const data = JSON.parse(result.data);
      const doingMissionArray = JSON.parse(data.doing_mission);
      const chatsArray = JSON.parse(data.chats);
      
      return {
        doing_mission: doingMissionArray.length > 0 ? doingMissionArray[0] : null,
        chats: chatsArray,
      };
    } else {
      console.error("Error starting mission:", result.message);
      return { doing_mission: null, chats: [] };
    }
  } catch (error) {
    console.error("Error in startMission:", error);
    return { doing_mission: null, chats: [] };
  }
};

// Send chat message function
export const sendChatMessage = async (
  userMessage: string,
  missionDoneWorkflowID: string,
): Promise<{
  success: boolean;
  message?: string;
  actions?: Array<{ multi_choice?: string[] }>;
  is_mission_end?: boolean;
}> => {
  const token = getAuthToken();

  console.log("sendChatMessage API called:", {
    userMessage,
    missionDoneWorkflowID,
    hasToken: !!token,
  });

  if (!token) {
    console.error("No auth token found");
    return { success: false };
  }

  try {
    const payload = {
      chat_service_function: {
        user_message: userMessage,
        mission_done_workflowID: missionDoneWorkflowID,
      },
    };

    console.log("Sending chat request to server:", JSON.stringify(payload));

    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(payload),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      const data = JSON.parse(result.data);
      // Parse the nested JSON in F3610 or similar keys
      const keys = Object.keys(data);
      if (keys.length > 0) {
        const chatResponse = JSON.parse(data[keys[0]]);
        return { 
          success: true, 
          message: chatResponse.message,
          actions: chatResponse.actions,
          is_mission_end: chatResponse.is_mission_end,
        };
      }
      return { success: false };
    } else {
      console.error("Error sending chat message:", result.message);
      return { success: false };
    }
  } catch (error) {
    console.error("Error in sendChatMessage:", error);
    return { success: false };
  }
};

// Upload File (video/audio)
export const uploadFile = async (file: File): Promise<string | null> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return null;
  }

  try {
    const formData = new FormData();
    formData.append("file", file);

    // ایجاد AbortController با تایم‌اوت 5 دقیقه
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 300000); // 5 دقیقه

    const response = await fetch(`${API_BASE_URL}/api/UploadFile`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    const result = await response.json();

    if (response.ok && result.state === 0) {
      // سرور فقط نام فایل را به صورت رشته ساده برمی‌گرداند
      return result.data || null;
    } else {
      console.error("Error uploading file:", result.message);
      return null;
    }
  } catch (error) {
    if (error instanceof Error && error.name === 'AbortError') {
      console.error("Error in uploadFile: Request timeout after 5 minutes");
    } else {
      console.error("Error in uploadFile:", error);
    }
    return null;
  }
};

// Upload Image
export const uploadImage = async (
  file: File,
  options: { requireResize?: boolean } = {}
): Promise<string | null> => {
  const token = getAuthToken();
  const { requireResize = false } = options;

  if (!token) {
    console.error("uploadImage: No auth token found");
    return null;
  }

  try {
    console.log("uploadImage: Starting upload for file:", file.name, "size:", file.size);
    
    // وارد کردن تابع ریسایز
    const { resizeImage } = await import('../utils/imageResize');
    
    // ریسایز تصویر قبل از آپلود
    let fileToUpload = file;
    try {
      console.log("uploadImage: Resizing image...");
      fileToUpload = await resizeImage(file);
      console.log("uploadImage: Image resized successfully");
    } catch (resizeError) {
      console.warn("uploadImage: Failed to resize image, uploading original:", resizeError);
      if (requireResize) {
        console.error("uploadImage: Resize is required for this upload. Aborting upload.");
        return null;
      }
      // در صورت خطا در ریسایز، فایل اصلی را آپلود می‌کنیم
      fileToUpload = file;
    }
    
    const formData = new FormData();
    formData.append("file", fileToUpload);

    console.log("uploadImage: Sending request to:", `${API_BASE_URL}/api/UploadImage`);
    console.log("uploadImage: Token:", token.substring(0, 20) + "...");

    // ایجاد AbortController با تایم‌اوت 5 دقیقه
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 300000); // 5 دقیقه

    const response = await fetch(`${API_BASE_URL}/api/UploadImage`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: formData,
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    console.log("uploadImage: Response status:", response.status);
    console.log("uploadImage: Response ok:", response.ok);

    const result = await response.json();
    console.log("uploadImage: Response data:", JSON.stringify(result));

    if (response.ok && result.state === 0) {
      // سرور فقط نام فایل را به صورت رشته ساده برمی‌گرداند
      console.log("uploadImage: Success! Filename:", result.data);
      return result.data || null;
    } else {
      console.error("uploadImage: Error - Message:", result.message, "State:", result.state);
      return null;
    }
  } catch (error) {
    if (error instanceof Error && error.name === 'AbortError') {
      console.error("Error in uploadImage: Request timeout after 5 minutes");
    } else {
      console.error("Error in uploadImage:", error);
    }
    return null;
  }
};

// Submit Mission Interface
export interface SubmitMissionData {
  title: string;
  mission_type: string;
  mission_done_workflowID: string; // تغییر از mission_id به mission_done_workflowID
  description: string;
  film?: string;
  image?: string;
  audio?: string;
  team_member?: string; // user_id های با Enter جدا شده
  enter_code?: string; // کد تایید ناظر (فقط برای آبخوری)
}

// Submit Mission (Final Submission)
export const submitMission = async (
  data: SubmitMissionData
): Promise<{ success: boolean; message?: string }> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return { success: false, message: "توکن احراز هویت یافت نشد" };
  }

  try {
    const requestBody: any = {
      do_mission_function: {
        title: data.title || "",
        mission_type: data.mission_type || "",
        mission_done_workflowID: data.mission_done_workflowID || "",
        description: data.description || "",
        film: data.film || "",
        image: data.image || "",
        audio: data.audio || "",
        team_member: data.team_member || "",
      },
    };

    // فقط برای آبخوری enter_code را اضافه کنیم
    if (data.enter_code) {
      requestBody.do_mission_function.enter_code = data.enter_code;
    }

    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(requestBody),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      return { success: true, message: "ماموریت با موفقیت ثبت شد" };
    } else {
      const errorMsg = formatErrorMessage(result);
      console.error("Error submitting mission:", errorMsg);
      return { success: false, message: errorMsg };
    }
  } catch (error) {
    console.error("Error in submitMission:", error);
    return { success: false, message: "خطا در ارتباط با سرور" };
  }
};

// Send supervisor code (for water tap mission)
export const sendSupervisorCode = async (
  mobile: string,
  missionDoneWorkflowID: string
): Promise<{ success: boolean; message?: string }> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return { success: false, message: "توکن احراز هویت یافت نشد" };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        supervisor_registration_function: {
          mission_done_workflowID: missionDoneWorkflowID,
          mobile: mobile,
        },
      }),
    });

    const result = await response.json();

    if (response.ok && result.state === 0) {
      return { success: true, message: "کد با موفقیت ارسال شد" };
    } else {
      const errorMsg = formatErrorMessage(result);
      console.error("Error sending supervisor code:", errorMsg);
      return { success: false, message: errorMsg };
    }
  } catch (error) {
    console.error("Error in sendSupervisorCode:", error);
    return { success: false, message: "خطا در ارتباط با سرور" };
  }
};

// Magic Bag Mission Item Interface
export interface MagicBagMissionItem {
  StageID: number;
  magic_bag_title: string;
  magic_bag_file?: string; // نام و پسوند فایل
}

// Load Magic Bag Missions
export const loadMagicBagMissions = async (): Promise<{
  success: boolean;
  data: MagicBagMissionItem[];
  message?: string;
}> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return {
      success: false,
      data: [],
      message: "توکن موجود نیست",
    };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        load_magic_bag_mission_function: {},
      }),
    });

    const result: ApiResponse<any> = await response.json();

    if (result.state === 0 && result.data) {
      const parsedData = JSON.parse(result.data);
      const magicBag: MagicBagMissionItem[] = JSON.parse(parsedData.magic_bag);
      // فیلتر کردن آیتم‌هایی که عنوان دارند
      const filteredItems = magicBag.filter((item) => item.magic_bag_title);
      return { success: true, data: filteredItems };
    } else {
      return {
        success: false,
        data: [],
        message: result.message || "خطا در بارگذاری ماموریت‌ها",
      };
    }
  } catch (error) {
    console.error("Error loading magic bag missions:", error);
    return {
      success: false,
      data: [],
      message: "خطا در بارگذاری ماموریت‌های کیف جادویی",
    };
  }
};

// Get Magic Bag File URL (برای هر دو تصویر و فایل)
export const getMagicBagFileUrl = (stageID: number): string => {
  const token = getAuthToken();
  return `${API_BASE_URL}/api/getfile?stageID=${stageID}&nameOrID=magic_bag_file&token=${token}`;
};

// بررسی اینکه فایل از نوع تصویر است یا خیر
export const isImageFile = (filename?: string): boolean => {
  if (!filename) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
  const lowerFilename = filename.toLowerCase();
  return imageExtensions.some(ext => lowerFilename.endsWith(ext));
};

// Load Team Members
export const loadTeamMembers = async (teamMemberIds: string): Promise<{
  success: boolean;
  data: TeamMember[];
  message?: string;
}> => {
  const token = getAuthToken();

  if (!token) {
    console.error("No auth token found");
    return {
      success: false,
      data: [],
      message: "توکن موجود نیست",
    };
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/call`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        load_team_member_function: {
          team_member: teamMemberIds,
        },
      }),
    });

    const result: ApiResponse<any> = await response.json();

    if (result.state === 0 && result.data) {
      const parsedData = JSON.parse(result.data);
      const teamMembers: TeamMember[] = JSON.parse(parsedData.team_members);
      return { success: true, data: teamMembers };
    } else {
      return {
        success: false,
        data: [],
        message: result.message || "خطا در بارگذاری اعضای تیم",
      };
    }
  } catch (error) {
    console.error("Error loading team members:", error);
    return {
      success: false,
      data: [],
      message: "خطا در بارگذاری اعضای تیم",
    };
  }
};
