import type { MenuProps } from 'antd';

export interface ResolvedMenuItem {
  key: string;
  icon: React.ReactNode;
  label: React.ReactNode;
}

/**
 * Recursively search nested menu items for a matching key.
 * Returns the item's key, icon, and label if found.
 */
export function resolveMenuItem(items: MenuProps['items'], key: string): ResolvedMenuItem | null {
  if (!items) return null;
  for (const item of items) {
    if (!item) continue;
    if ('key' in item && item.key === key) {
      return {
        key: item.key as string,
        icon: 'icon' in item ? item.icon : undefined,
        label: 'label' in item ? item.label : undefined,
      };
    }
    if ('children' in item && item.children) {
      const found = resolveMenuItem(item.children as MenuProps['items'], key);
      if (found) return found;
    }
  }
  return null;
}

/**
 * Filter favorite keys to only those present in the current menu tree.
 * Handles feature flag changes gracefully — missing keys are silently excluded
 * but remain stored so they reappear if re-enabled.
 */
export function resolveValidFavorites(items: MenuProps['items'], favoriteKeys: string[]): ResolvedMenuItem[] {
  const result: ResolvedMenuItem[] = [];
  for (const key of favoriteKeys) {
    const resolved = resolveMenuItem(items, key);
    if (resolved) result.push(resolved);
  }
  return result;
}

/**
 * Collect all leaf-item keys from a menu tree (items that have no children).
 * Used to determine which items can be favorited.
 */
export function collectLeafKeys(items: MenuProps['items']): Set<string> {
  const keys = new Set<string>();
  if (!items) return keys;
  for (const item of items) {
    if (!item) continue;
    if ('children' in item && item.children) {
      for (const k of collectLeafKeys(item.children as MenuProps['items'])) {
        keys.add(k);
      }
    } else if ('key' in item && item.key) {
      keys.add(item.key as string);
    }
  }
  return keys;
}
