export const SELECTED_FAMILY_STORAGE_KEY = 'id-selected-family-group-id';

export function readStoredFamilyGroupId(): string | null {
  if (typeof window === 'undefined') {
    return null;
  }
  const stored = window.localStorage.getItem(SELECTED_FAMILY_STORAGE_KEY);
  return stored?.trim() ? stored : null;
}

export function writeStoredFamilyGroupId(groupId: string | null) {
  if (typeof window === 'undefined') {
    return;
  }
  if (groupId) {
    window.localStorage.setItem(SELECTED_FAMILY_STORAGE_KEY, groupId);
  } else {
    window.localStorage.removeItem(SELECTED_FAMILY_STORAGE_KEY);
  }
}

export function resolveFamilyGroupId(
  groups: Array<{ id: string }>,
  selectedGroupId: string | null,
  isSelectionHydrated: boolean
): string | null {
  if (!groups.length) {
    return null;
  }

  const candidates: Array<string | null> = [selectedGroupId];
  if (!isSelectionHydrated) {
    candidates.unshift(readStoredFamilyGroupId());
  }

  for (const candidate of candidates) {
    if (candidate && groups.some((group) => group.id === candidate)) {
      return candidate;
    }
  }

  return isSelectionHydrated ? groups[0]!.id : null;
}
