/**
 * Usage Tracker Utility
 * Tracks user clicks on dashboard items and sorts them by usage frequency
 */

const STORAGE_KEY = "dashboard_usage_stats";

/**
 * Get all usage statistics from localStorage
 * @returns {Object} Usage statistics object
 */
export const getUsageStats = () => {
  try {
    const stats = localStorage.getItem(STORAGE_KEY);
    return stats ? JSON.parse(stats) : {};
  } catch (error) {
    console.error("Error reading usage stats:", error);
    return {};
  }
};

/**
 * Save usage statistics to localStorage
 * @param {Object} stats - Usage statistics object
 */
const saveUsageStats = (stats) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(stats));
  } catch (error) {
    console.error("Error saving usage stats:", error);
  }
};

/**
 * Get click count for a specific item in a role
 * @param {string} role - User role (e.g., 'admix', 'Province')
 * @param {string} itemKey - Unique identifier for the item (route or text)
 * @returns {number} Click count
 */
export const getItemClickCount = (role, itemKey) => {
  const stats = getUsageStats();
  return stats[role]?.[itemKey] || 0;
};

/**
 * Increment click count for a specific item
 * @param {string} role - User role (e.g., 'admix', 'Province')
 * @param {string} itemKey - Unique identifier for the item (route or text)
 */
export const trackItemClick = (role, itemKey) => {
  const stats = getUsageStats();

  // Initialize role object if it doesn't exist
  if (!stats[role]) {
    stats[role] = {};
  }

  // Increment click count
  stats[role][itemKey] = (stats[role][itemKey] || 0) + 1;

  saveUsageStats(stats);
};

/**
 * Sort items array by their usage (click count)
 * @param {Array} items - Array of items with route or text property
 * @param {string} role - User role
 * @param {string} keyField - Field to use as key (default: 'route')
 * @returns {Array} Sorted items array (most used first)
 */
export const sortItemsByUsage = (items, role, keyField = "route") => {
  if (!items || !Array.isArray(items)) return items;

  const stats = getUsageStats();
  const roleStats = stats[role] || {};

  return [...items].sort((a, b) => {
    const keyA = a[keyField] || a.text || "";
    const keyB = b[keyField] || b.text || "";

    const countA = roleStats[keyA] || 0;
    const countB = roleStats[keyB] || 0;

    // Sort descending (most clicked first)
    return countB - countA;
  });
};

/**
 * Get usage statistics for a specific role
 * @param {string} role - User role
 * @returns {Object} Usage statistics for the role
 */
export const getRoleUsageStats = (role) => {
  const stats = getUsageStats();
  return stats[role] || {};
};

/**
 * Clear all usage statistics
 */
export const clearUsageStats = () => {
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch (error) {
    console.error("Error clearing usage stats:", error);
  }
};

/**
 * Clear usage statistics for a specific role
 * @param {string} role - User role
 */
export const clearRoleUsageStats = (role) => {
  const stats = getUsageStats();
  if (stats[role]) {
    delete stats[role];
    saveUsageStats(stats);
  }
};

/**
 * Get top N most used items for a role
 * @param {string} role - User role
 * @param {number} limit - Number of top items to return
 * @returns {Array} Array of {itemKey, count} objects
 */
export const getTopUsedItems = (role, limit = 5) => {
  const roleStats = getRoleUsageStats(role);

  return Object.entries(roleStats)
    .map(([itemKey, count]) => ({ itemKey, count }))
    .sort((a, b) => b.count - a.count)
    .slice(0, limit);
};

/**
 * Export usage statistics (for backup or analysis)
 * @returns {string} JSON string of all statistics
 */
export const exportUsageStats = () => {
  const stats = getUsageStats();
  return JSON.stringify(stats, null, 2);
};

/**
 * Import usage statistics (from backup)
 * @param {string} jsonString - JSON string of statistics
 */
export const importUsageStats = (jsonString) => {
  try {
    const stats = JSON.parse(jsonString);
    saveUsageStats(stats);
    return true;
  } catch (error) {
    console.error("Error importing usage stats:", error);
    return false;
  }
};
