const STORAGE_KEY = "dashboard_custom_order";

export const getCustomOrders = () => {
  try {
    const orders = localStorage.getItem(STORAGE_KEY);
    return orders ? JSON.parse(orders) : {};
  } catch (error) {
    console.error("Error reading custom orders:", error);
    return {};
  }
};

const saveCustomOrders = (orders) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(orders));
  } catch (error) {
    console.error("Error saving custom orders:", error);
  }
};

export const getRoleCustomOrder = (role) => {
  const orders = getCustomOrders();
  return orders[role] || null;
};

export const saveRoleCustomOrder = (role, items) => {
  const orders = getCustomOrders();

  const routeOrder = items.map((item) => item.route);

  orders[role] = routeOrder;
  saveCustomOrders(orders);
};

export const applyCustomOrder = (items, role) => {
  if (!items || !Array.isArray(items)) return items;

  const customOrder = getRoleCustomOrder(role);

  if (!customOrder || customOrder.length === 0) return items;

  const orderedItems = [];
  const remainingItems = [...items];

  for (const route of customOrder) {
    const index = remainingItems.findIndex((item) => item.route === route);
    if (index !== -1) {
      orderedItems.push(remainingItems[index]);
      remainingItems.splice(index, 1);
    }
  }

  orderedItems.push(...remainingItems);

  return orderedItems;
};

export const clearRoleCustomOrder = (role) => {
  const orders = getCustomOrders();
  if (orders[role]) {
    delete orders[role];
    saveCustomOrders(orders);
  }
};

export const clearAllCustomOrders = () => {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch (error) {
    console.error("Error clearing custom orders:", error);
  }
};

export const hasCustomOrder = (role) => {
  const customOrder = getRoleCustomOrder(role);
  return customOrder !== null && customOrder.length > 0;
};

export const reorderArray = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};
